Image Optimization - Overview

Image Optimization / Overview

On this page:

Perfect visuals are essential elements of every website and application. They sell products and services, convert new users and create consistent look and feel of interfaces. They are also the biggest contributors to the Internet traffic currently occupying 64.2% of the bandwidth world-wide.

Serving bloated, unoptimized images on your websites will have a very negative effect on your site speed and will lead to inevitable drops in conversions rates and customer satisfaction. Also, Google has indicated site speed is one of the important signals used by its algorithm to rank pages. Slower loading times will negatively affect your search ranking.

Image optimization is the art and science of minimizing image file size without affecting its visual quality. Our proprietary Smart Lossy Optimization algorithms excel at determining the perfect balance of image quality and file size, achieving on average 60% of savings without any perceptible impact on the image quality.

With Smart Lossy Optimization, you can also set a custom compression preset depending on your use-case. We also offer a lossless mode of image optimization which will yield smaller savings (around 20% size reduction), but the pixel information will remain untouched. You may also bypass our smart image optimization pipeline and set a custom image quality level by yourself.

Optidash API supports JPEG, PNG, Animated PNG, WebP, GIF, Animated GIF and SVG as input formats for image optimization pipeline.

Default Image Optimization Mode

It's worth noting that all images will be automatically optimized with Smart Lossy mode (unless you specify a lossless mode) and no additional user action is required to have your visuals prepared for the Web. In other words, Optidash Image API will always yield perfectly optimized output images.

Smart Lossy Image Optimization

This is the default mode applied to all processed images. Images in JPEG, PNG, GIF, Animated GIF and SVG formats will be treated with Smart Lossy Optimization giving you confidence that your visuals will always have an unmatched quality with the smallest possible file size. Quality loss when using Smart Lossy Optimization is not noticeable to the human eye.

Because Smart Lossy Optimization is enabled by default, if you just want to optimize your images without performing any transformations, you only have to upload your file to the Optidash Image API without any additional parameters.

An example cURL request incorporating Image Upload method used only to optimize your images would look like so:

curl https://api.optidash.ai/1.0/upload \
     --user your-api-key: \
     --form file=@/path/to/image/file.jpg

Or with Image Fetch method:

curl https://api.optidash.ai/1.0/fetch \
     --user your-api-key: \
     --header "Content-Type: application/json" \
     --data '{
         "url": "https://www.website.com/image.jpg"
     }'

Lossy Optimization Presets

In addition to the default smart lossy optimization mode which will yield images of excellent quality, the Optidash Image API offers you three compression presets for different use-cases you may have. Those presets differ in terms of image quality and therefore the resulting file size; they describe the level of compression used to encode the output image.

PresetDescription
lowLow compression level is still lossy, but avoids any compression artifacts and therefore guarantees a bit higher file size savings than the lossless mode of image optimization. It's recommended for images with very high contrast ratio, gradients and visuals that will be enlarged on the client-side.
mediumMedium compression level is enabled by default if the preset is not explicitly specified. If offers a perfect balance of file size and image quality and it's recommended for most use-cases. Quality degradation will be imperceptible under normal viewing conditions.
highHigh compression level guarantees the smallest possible file size at the expense of image quality. This mode is recommended for non-critical parts of your websites. It's also perfect for visuals prepared specificaly for high DPI screens (eg. Retina) as images on those screens will typically be scaled down by a factor of 2x and therefore compression artifacts will be less visible.
{
    "optimize": {
        "compression": "high"
    }
}

An example cURL request of using Image Fetch method with lossy optimization preset will look like the following:

curl https://api.optidash.ai/1.0/fetch \
     --user your-api-key: \
     --header "Content-Type: application/json" \
     --data '{
         "url": "https://www.website.com/image.jpg",
         "optimize": {
             "compression": "high"
         }
     }'

Lossless Image Optimization

Optidash Image API can also apply mathematically lossless image optimization and recompression without altering a single pixel of the image. If you are confident that your image transformation requests must result in a pristine look of your visuals, you may use the lossless mode for image optimization. Enabling this will disable Smart Lossy Optimization alltogether. To use Lossless Mode, simply set "lossless": true within the optimize hash:

{
    "optimize": {
        "lossless": true
    }
}

An example cURL request of using Image Fetch method with lossless optimization will look like the following:

curl https://api.optidash.ai/1.0/fetch \
     --user your-api-key: \
     --header "Content-Type: application/json" \
     --data '{
         "url": "https://www.website.com/image.jpg",
         "optimize": {
             "lossless": true
         }
     }'

Custom Image Quality

If you would like to exercise more control over the compression process, you may optionally specify an explicit quality (Q) value. To set the Q value, specify "quality": N within the optimize hash where N is an integer within the range 1 - 100 (1 being the lowest with maximum compression and 100 with the best image quality).

Custom Image Quality is supported for JPEG, PNG, WebP, GIF and Animated GIF image formats.

{
    "optimize": {
        "quality": 75
    }
}

Since image quality cannot improve after being processed, setting a very high Q value for low quality images will not make them look any better and will only lead to extremely large file sizes of output images.

We recommend against setting one quality value for all your visuals as for example Q75 might only look good on a small subset of images and specific image formats. It's always best to rely on our default Smart Lossy Optimization.

An example cURL request of using custom image quality will look like the following:

curl https://api.optidash.ai/1.0/fetch
     --user your-api-key: \
     --header "Content-Type: application/json" \
     --data '{
         "url": "https://www.website.com/image.jpg",
         "optimize": {
             "quality": 75
         }
     }'

Code Examples for Image Optimization

Below you'll find examples of how to set compression level in all official integrations for Optidash Image API.

  • PHP
  • Node
  • Ruby
  • Go
  • Python
  • Java
<?php

/**
* Instantiate new `$opti` by calling a constructor
*/

$opti = new Optidash\Optidash('your-api-key');


/**
* Provide a publicly available image URL with fetch(string) method
* and optimize the image by setting compression mode to "high"
*/

$opti
    ->fetch('https://www.website.com/image.jpg')
    ->optimize(array(
        'compression' => 'high'
    ))
    ->toJSON(function ($error, $meta) {
        if (!empty($error)) {
            throw new Exception($error);
        }

        /**
        * You'll find the full JSON metadata array within the `$meta` variable.
        * Remember to always check if the `success` property is set to `true`.
        */

        if ($meta['success'] == true) {
            print ($meta['output']['url']);
        } else {
            print ($meta['message']);
        }
    });
/**
* Module dependencies
*/

const Optidash = require("optidash");


/**
* Instantiate new `opti` by calling a constructor
*/

const opti = new Optidash("your-api-key");


/**
* Provide a publicly available image URL with fetch(string) method
* and optimize the image by setting compression mode to "high"
*/

opti
    .fetch("https://www.website.com/image.jpg")
    .optimize({
        compression: "high"
    })
    .toJSON((err, meta) => {
        if (err) {
            return console.log(err);
        }

        /**
        * You'll find the full JSON metadata hash within the `meta` variable.
        * Remember to always check if the `success` property is set to `true`.
        */

        if (meta.success) {
            console.log(meta.output.url);
        } else {
            console.log(meta.message);
        }
    });
##
# Require dependencies

require "optidash"


##
# Instantiate new `opti` by calling a constructor

opti = Optidash.new("your-api-key")


##
# Provide a publicly available image URL with fetch(string) method,
# and optimize the image by setting compression mode to "high"

err, meta = opti
    .fetch("https://www.website.com/image.jpg")
    .optimize(
        compression: "high"
    )
    .to_json

abort(err) if err


##
# You'll find the full JSON metadata hash within the `meta` variable.
# Remember to always check if the `success` property is set to `true`.

if meta["success"]
    puts meta["output"]["url"]
else
    puts meta["message"]
end
package main

import (
    "fmt"
    "github.com/optidash/optidash-go"
)

func main() {

    /**
    * Instantiate new `opti` by calling a constructor
    */

    opti, err := optidash.NewClient("your-api-key")

    if err != nil {
        panic(err)
    }


    /**
    * Provide a publicly available image URL with Fetch(string) method,
    * and optimize the image by setting compression mode to "high"
    */

    meta, err := opti.
        Fetch("https://www.website.com/image.jpg").
        Optimize(optidash.P{
            "compression": "high"
        }).
        ToJSON()

    if err != nil {
        panic(err)
    }


    /**
    * You'll find the full JSON metadata hash within the `meta` variable.
    * Remember to always check if the `success` property is set to `true`.
    */

    if meta["success"].(map[string]interface{})["success"].(bool) {
        fmt.Println(meta["output"].(map[string]interface{})["url"])
    } else {
        fmt.Println(meta["message"])
    }
}
##
# Import dependencies

from optidash import optidash


##
# Instantiate new `opti` by calling a constructor

opti = optidash('your-api-key')


##
# Provide a publicly available image URL with fetch(string) method
# and optimize the image by setting compression mode to "high"

err, meta = (
    opti
        .fetch('https://www.website.com/image.jpg')
        .optimize({
            'compression': 'high'
        })
        .toJSON()
)

if err is not None:
    raise StandardError(err)


##
# You'll find the full JSON metadata hash within the `meta` variable.
# Remember to always check if the `success` property is set to `true`.

if meta['success'] is True:
    print (meta['output']['url'])
else:
    print (meta['message'])
package com.optidash.examples;

/**
* Import dependencies
*/

import static com.optidash.OperationConfiguration.settings;
import com.optidash.Optidash;
import com.optidash.Response;

public class ImageOptimization {
    public static void main(String[] args) {

        /**
        * Instantiate new `opti` by calling a constructor
        */

        Optidash opti = new Optidash("your-api-key");

        /**
        * Provide a publicly available image URL with fetch(string) method
        * and optimize the image by setting compression mode to "high"
        */

        final Response response = opti.fetch("https://www.website.com/image.jpg");

        fetch.optimize(
            settings()
                .set("compression", "high")
        );

        final Response response = fetch.toJson();

        /**
        * You'll find the full JSON metadata hash within the `Response#getMetadata()` property.
        * Remember to always check if the `Response#successful` property is set to `true`.
        */

        if (response.isSuccessful()) {
            System.out.println(response.getMetadata().getOutput().get("url"));
        } else {
            System.out.println(response.getMessage());
        }
    }
}
Grace Przemek Magda Damian
Have questions? Let's talk!We usually respond in just under an hour

Thanks for reaching out!

We've received your message
and will get to it as quickly as possible.

Whoops, looks like something went wrong.

We encountered an unexpected error and cannot complete your request. Please try reloading the page.