# How to optimize image processing at the edge

import Tabs from '~/components/tabs/Tabs'
import Apiv4Rollout from '~/includes/snippets/apiv4Rollout/en/snippet.mdx'
import Code from '~/components/Code/Code.astro'


<Apiv4Rollout />

Through the [Image Processor](/en/documentation/products/build/applications/image-processor/) module, you can adjust image sizes, add filters and watermarks, or convert formats to suit for more efficient content delivery, bandwidth saving, and reduce object storage costs. These changes can be applied directly in the URL of your image by appending `ims` queries to the image's URL.

:::caution[warning]
If you wish to optimize your images, in addition to the **Image Processor module, the activation of the [Application Accelerator](/en/documentation/products/build/applications/application-accelerator/) module is recommended for cache efficiency. If these modules are activated, images processed and data transfer could generate usage-related costs. Check the [pricing page](/en/documentation/products/pricing/) for more information.
:::

:::tip
In this guide, there are separate instructions for API v3 and API v4. If you're not sure which steps apply to your account, see [the Verify Your Account Migration guide](/en/documentation/products/guides/verify-account-migration/) to determine if your account has already been migrated.
:::

---

<Tabs client:visible>
    <Fragment slot="tab.console">Console</Fragment>
    <Fragment slot="tab.apiv3">API v3</Fragment>
    <Fragment slot="tab.apiv4">API v4</Fragment>

<Fragment slot="panel.console">
1. Access [Azion Console](/en/documentation/products/guides/how-to-access-azion-console/) > **Applications**.
2. Click the Application you want to configure. 
3. Activate the **Application Accelerator** and **Image Processor** modules.
4. Click the **Save** button.
5. Navigate to the **Cache Settings** tab.
6. Click the **+ Cache Setting** button.
7. In the **Cache Expiration Policies** section, configure the [expiration policy](/en/documentation/products/build/applications/cache-settings/#browser-cache-settings) for your images.
- For images, you may add larger time-to-live (TTL) values, such as `1296000` seconds (15 days).
1. In the **Advanced Cache Key** section, choose one of the following options:
    - **Content varies by some Query String fields (Allowlist)**: if you want to list all the fields in the Query String that will identify your images. **Image Processor** uses the *ims* field, so this has to be included in the list as one of the required fields for your image manager application.
    - **Content varies by Query String, except for some fields (Blocklist)**: if you only want to list those fields in the Query String that should be ignored to identify the objects in your cache. In this case, it guarantees that the *ims* field will be removed from the list.
    - **Content varies by all Query String fields**: if you don't know or aren't sure about which fields to list in the Query String because you aren't responsible for all the content in the cache or don't have [Application Accelerator](/en/documentation/products/build/applications/application-accelerator/) activated.
2. Click the **Save** button.

Now you need to indicate what will trigger the activation of the **Image Processor** module. You can create a rule that identifies image formats as follows:

1. Still on the **Applications** page, navigate to the **Rules Engine** tab.
2. Click the **+ Rule** button.
3. Name your rule.
4. Select **Request Phase**.
5. In the **Criteria** section, select the variable `${request_uri}`.
6. Select the comparsion operator **matches**
7. As an argument, add `\.(jpg|jpeg|gif|bmp|png)`.
8. Click **+ Or** to add another criterium.
9. In the new field, select the variable `${uri}`.
10. Select the comparsion operator **matches**
11. As an argument, add `\.(jpg|jpeg|gif|bmp|png)$`
12. In the **Behavior** section, select **Set Cache Policy** and select the cache setting you created.
13. Click the **+ Add Behavior** button.
14. Add the **Optimize Images** behavior.

:::note[Optional]
To ensure images are successfully converted to WEBP format, you must also add the behavior **Add Request Header** and send the header `Accept: image/webp`.
:::

:::note[Optional]
To ensure images are successfully converted to AVIF format, you must also add the behavior **Add Request Header** and send the header `Accept: image/avif`.
:::

15. Click the **Save** button to save your rule.

To confirm whether your image is being optimized, [inspect the page](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools) using your browser and find the corresponding path in the image. In the URL's query string, the `ims=VALUExVALUE` field corresponds to the resolution loaded on the page. To see the original file, you only need to remove the query string added in the URL.
</Fragment>
<Fragment slot="panel.apiv4">

1. Run the following `PATCH` request in your terminal, replacing `[TOKEN VALUE]` with your [personal token](/en/documentation/products/guides/personal-tokens/) and the `<application_id>` variable with [your Application ID](/en/documentation/products/guides/build/configure-main-settings/) to activate the [Application Accelerator](/en/documentation/products/build/applications/application-accelerator/) and [Image Processor](/en/documentation/products/build/applications/image-processor/) modules:

<Code lang="bash" code={` 
curl --request PATCH \
  --url https://api.azion.com/v4/edge_application/applications/<application_id> \
  --header 'Accept: application/json' \
  --header 'Authorization: Token [TOKEN VALUE]]' \
  --header 'Content-Type: application/json' \
  --data '{
  "modules": {
    "application_accelerator": {
      "enabled": true
    },
    "image_processor": {
      "enabled": true
    }
  },
  "active": true,
  "debug": false
}'
`} />

2. You'll receive a response with the updated value.
3. Run the following `POST` request in your terminal, replacing `[TOKEN VALUE]` with your [personal token](/en/documentation/products/guides/personal-tokens/) and the `<application_id>` variable with the `id` of your application:

<Code lang="bash" code={` 
curl --request POST \
  --url https://api.azion.com/v4/edge_application/applications/<application_id>/cache_settings \
  --header 'Accept: application/json' \
  --header 'Authorization: Token [TOKEN VALUE]' \
  --header 'Content-Type: application/json' \
  --data '{
  "name": "QS15D img",
  "browser_cache": {
    "behavior": "override",
    "max_age": 60
  },
  "modules": {
    "edge_cache": {
      "behavior": "override",
      "max_age": 1296000
    },
    "application_accelerator": {
      "cache_vary_by_method": [
        "options"
      ],
      "cache_vary_by_querystring": {
        "behavior": "allowlist",
        "fields": ["ims"],
        "sort_enabled": true
      },
      "cache_vary_by_cookies": {
        "behavior": "ignore",
        "cookie_names": []
      },
      "cache_vary_by_devices": {
        "behavior": "ignore"
      }
    }
  }
}'
`} />

:::note
For more information on the cache settings endpoint, see how to [Tune your cache settings](/en/documentation/products/guides/build/tune-cache-settings/).
:::

4. You'll receive a response similar to this:

<Code lang="json" code={` 
{
  "state": "executed",
  "data": {
    "id": <cache_setting_id>,
    "name": "QS15D img",
    "browser_cache": {
      "behavior": "override",
      "max_age": 60
    },
    "modules": {
      "edge_cache": {
        "behavior": "override",
        "max_age": 1296000,
        "stale_cache": {
          "enabled": false
        },
        "large_file_cache": {
          "enabled": false,
          "offset": 1024
        }
      },
      "tiered_cache": null,
      "application_accelerator": {
        "cache_vary_by_method": [
          "options"
        ],
        "cache_vary_by_querystring": {
          "behavior": "allowlist",
          "fields": [
            "ims"
          ],
          "sort_enabled": true
        },
        "cache_vary_by_cookies": {
          "behavior": "ignore",
          "cookie_names": []
        },
        "cache_vary_by_devices": {
          "behavior": "ignore",
          "device_group": []
        }
      }
    }
  }
}
`} />

5. Copy the cache setting ID received in the response.
6. Run the following `POST` request to create a rule in the **Request Phase**, replacing the application ID value and the cache setting ID you received in the previous response:

<Code lang="bash" code={` 
curl --request POST \
  --url https://api.azion.com/v4/edge_application/applications/<application_id>/request_rules \
  --header 'Accept: application/json' \
  --header 'Authorization: Token [TOKEN VALUE]' \
  --header 'Content-Type: application/json' \
  --data '{
    "name": "ImgProcessor",
    "active": true,
    "criteria": [
      [
        {
          "variable": "\${request_uri}",
          "operator": "matches",
          "conditional": "if",
          "input_value": "\\.(jpg|jpeg|gif|bmp|png)"
        },
        {
          "variable": "\${uri}",
          "operator": "matches",
          "conditional": "or",
          "input_value": "\\.(jpg|jpeg|gif|bmp|png)$"
        }
      ]
    ],
    "behaviors": [
      {
        "type": "set_cache_settings",
        "cache_settings_id": "<cache_settings_id>"
      },
      {
        "type": "optimize_images"
      }
    ],
    "description": "Apply cache settings and optimize images"
  }'
`} />

:::note
For more information on the rules endpoint, see how to [Work with Rules Engine](/en/documentation/products/guides/build/work-with-rules-engine/).
:::

To confirm whether your image is being optimized, [inspect the page](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools) using your browser and find the corresponding path in the image. In the URL's query string, the `ims=VALUExVALUE` field corresponds to the resolution loaded on the page. To see the original file, you only need to remove the query string added in the URL.

:::tip
Check the [Azion API documentation](https://api.azion.com/) and the [OpenAPI specification](https://github.com/aziontech/azionapi-openapi/) to know more about all features available via API.
:::

</Fragment>

<Fragment slot="panel.apiv3">
1. Run the following `PATCH` request in your terminal, replacing `[TOKEN VALUE]` with your [personal token](/en/documentation/products/guides/personal-tokens/) and the `<application_id>` variable with [your application ID](/en/documentation/products/guides/build/configure-main-settings/) to activate the [Application Accelerator](/en/documentation/products/build/applications/application-accelerator/) and [Image Processor](/en/documentation/products/build/applications/image-processor/) modules:

<Code lang="bash" code={` 
curl --location --request PATCH 'https://api.azionapi.net/edge_applications/<application_id>' \
--header 'Accept: application/json; version=3' \
--header 'Content-Type: application/json' \
--header 'Authorization: Token [TOKEN VALUE]' \
--data '{
    "application_acceleration": true,
    "image_optimization": true
}'
`} />

2. You'll receive a response with the updated value.
3. Run the following `POST` request in your terminal, replacing `[TOKEN VALUE]` with your [personal token](/en/documentation/products/guides/personal-tokens/) and the `<application_id>` variable with the `id` of your application:

<Code lang="bash" code={` 
curl --location 'https://api.azionapi.net/edge_applications/<application_id>/cache_settings' \
--header 'Accept: application/json; version=3' \
--header 'Content-Type: application/json' \
--header 'Authorization: Token [TOKEN VALUE]' \
--data '{
    "name": "QS15D img",
    "browser_cache_settings": "override",
    "browser_cache_settings_maximum_ttl": 60,
    "cdn_cache_settings": "override",
    "cdn_cache_settings_maximum_ttl": 1296000,
    "cache_by_query_string": "whitelist",
    "query_string_fields": [
        "ims"
    ]
}'
`} />

:::note
For more information on the cache settings endpoint, see [Tune your cache settings](/en/documentation/products/guides/build/tune-cache-settings/).
:::

4. You'll receive a response similar to this:

<Code lang="json" code={` 
{
    "results": {
        "id": <cache_setting_id>,
        "name": "QS15D img",
        "browser_cache_settings": "override",
        "browser_cache_settings_maximum_ttl": 60,
        "cdn_cache_settings": "override",
        "cdn_cache_settings_maximum_ttl": 1296000,
        "cache_by_query_string": "whitelist",
        "query_string_fields": [
            "ims"
        ],
        "enable_query_string_sort": false,
        "cache_by_cookies": "ignore",
        "cookie_names": null,
        "adaptive_delivery_action": "ignore",
        "device_group": [],
        "enable_caching_for_post": false,
        "l2_caching_enabled": false,
        "is_slice_configuration_enabled": false,
        "is_slice_edge_caching_enabled": false,
        "is_slice_l2_caching_enabled": false,
        "slice_configuration_range": 1024,
        "enable_caching_for_options": false,
        "enable_stale_cache": true,
        "l2_region": null
    }
}
`} />

5. Copy the cache setting ID received in the response.
6. Run the following `POST` request to create a rule in the **Request Phase**, replacing the application ID value and the cache setting ID you received in the previous response:

<Code lang="bash" code={` 
curl --location --globoff 'https://api.azionapi.net/edge_applications/<application_id>/rules_engine/request/rules' \
--header 'Accept: application/json; version=3' \
--header 'Authorization: Token [TOKEN VALUE]' \
--header 'Content-Type: application/json' \
--data '{
    "name": "ImgProcessor",
    "behaviors": [
        {
            "name": "set_cache_policy",
            "target": "<cache_settings_id>"
        },
        {
            "name": "optimize_images",
            "target": null
        }
    ],
    "criteria": [
        [
            {
                "variable": "\${request_uri}",
                "operator": "matches",
                "conditional": "if",
                "input_value": "\\.(jpg|jpeg|gif|bmp|png)"
            },
            {
                "variable": "\${uri}",
                "operator": "matches",
                "conditional": "or",
                "input_value": "\\.(jpg|jpeg|gif|bmp|png)$"
            }
        ]
    ]
}'
`} />

:::note
For more information on the rules endpoint, see [Work with Rules Engine](/en/documentation/products/guides/build/work-with-rules-engine/).
:::

7. You'll receive the following response:

<Code lang="json" code={` 
{
    "results": {
        "id": <rule_id>,
        "name": "ImgProcessor",
        "phase": "request",
        "behaviors": [
            {
                "name": "set_cache_policy",
                "target": "132186"
            },
            {
                "name": "optimize_images",
                "target": null
            }
        ],
        "criteria": [
            [
                {
                    "variable": "\${request_uri}",
                    "operator": "matches",
                    "conditional": "if",
                    "input_value": "\\.(jpg|jpeg|gif|bmp|png)"
                },
                {
                    "variable": "\${uri}",
                    "operator": "matches",
                    "conditional": "or",
                    "input_value": "\\.(jpg|jpeg|gif|bmp|png)$"
                }
            ]
        ],
        "is_active": true,
        "order": 3,
        "description": null
    }
}
`} />

To confirm whether your image is being optimized, [inspect the page](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools) using your browser and find the corresponding path in the image. In the URL's query string, the `ims=VALUExVALUE` field corresponds to the resolution loaded on the page. To see the original file, you only need to remove the query string added in the URL.

:::tip
Check the [Azion API documentation](https://api.azion.com/v3) to know more about all features available via API.
:::
</Fragment>

</Tabs>