You can add multiple Image Processing (IMG) parameters to an image style to perform complex operations on images that are stored in a bucket. This topic describes how to create and use image styles.

Create an image style

You can create up to 50 image styles for a bucket. These image styles can be used only for images in the bucket. To create more than 50 image styles for a bucket, contact technical support.

  1. Log on to the OSS console.
  2. In the left-side navigation pane, click Buckets. On the Buckets page, click the bucket that you want to configure.
  3. In the left-side navigation pane, choose Data Processing > Image Processing (IMG). Then, click Create Rule.
  4. In the Create Rule pane, configure the style.
    You can use Basic Edit or Advanced Edit to create a style:
    • Basic Edit: You can use the IMG parameters listed by using the graphical user interface (GUI) to choose the IMG methods. For example, resize an image, add a watermark, and modify the image format.
    • Advanced Edit: You can use the API code to edit the IMG methods. The format is: image/action1,parame_value1/action2,parame_value2/.... For more information about supported IMG parameters, see the "Parameters" section of the Overview topic.

      Example: image/resize,p_63/quality,q_90 indicates that the image is scaled down to 63% of the source image, and then the relative quality of the image is set to 90%.

      Note If you want to add image and text watermarks to images at the same time by using a style, use Advanced Edit to create the style.
  5. Click OK.

Usage notes

After you configure an image style for a bucket, you can use the style when you process images in the bucket by means of image URLs or OSS SDKs.

Notice If you use an image style to process dynamic images such as GIFs, you must add the /format,gif parameter to the image style. Otherwise, the GIF images may become static images after they are processed.

Use the image URL

You can add an image style to the URL of an image in the following format: http(s)//:BucketName.Endpoint/ObjectName?x-oss-process=style/<StyleName>. Example: https://image-demo-oss-zhangjiakou.oss-cn-zhangjiakou.aliyuncs.com/example.jpg?x-oss-process=style/small.

If a custom delimiter is specified, use the delimiter to replace ? x-oss-process=style/. This simplifies the IMG URL. For more information about how to configure a custom delimiter, see Source image protection.

For example, if you set the delimiter to an exclamation point (!), the IMG URL can be simplified to http(s)//:BucketName.Endpoint/ObjectName!StyleName.

You can also map a custom domain name to the bucket to further simplify the IMG URL. For example, if the custom domain name example.com is mapped to the bucket, the sample URL can be replaced with https://example.com/example.jpg!small. After you map a custom domain name, you can also preview the effect of IMG online. For more information, see Map custom domain names.

Use OSS SDKs

You can work with OSS SDKs to encapsulate various IMG parameters within a style and then use the style to concurrently process multiple images. The following code provides examples on how to use an image style to process images by means of OSS SDKs for common programming languages. For more information about how to use an image style to process images by means of OSS SDKs for other programming languages, see Overview.

import com.aliyun.oss.*;
import com.aliyun.oss.model.GetObjectRequest;
import java.io.File;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify the actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to access OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. The full path cannot contain the name of the bucket. 
        String objectName = "exampleobject.jpg";
        // Specify the full path to which you want to save the processed image. Example: D:\\localpath\\example-new.jpg. If a file with the same name already exists in the path, the processed image overwrites the file. Otherwise, a new file is created. 
        String pathName = "D:\\localpath\\example-new.jpg";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // Use the custom style to process the image. 
            // Set yourCustomStyleName to the name of the image style that you create in the OSS console. 
            String style = "style/yourCustomStyleName";
            GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
            request.setProcess(style);
            // Name the processed image example-new.jpg and save the image to your local computer. 
            // By default, if you only specify the name of a local file such as example-new.jpg without specifying the local path of the file, the processed image is saved to the local path of the project to which the sample program belongs. 
            ossClient.getObject(request, new File(pathName));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\OssClient;
// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
$accessKeyId = "yourAccessKeyId";
$accessKeySecret = "yourAccessKeySecret";
// Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
$endpoint = "yourEndpoint";
// Specify the name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.jpg. The full path of the object cannot contain the bucket name. 
$object = "exampledir/exampleobject.jpg";
// Specify the local path to which you want to save the image. Example: D:\\localpath\\example-new.jpg. If the specified local file exists, it is overwritten by the processed image. Otherwise, the local file is created. 
// By default, if you set this parameter to the name of a local file such as example-new.jpg without specifying the local path of the file, the processed object is saved to the local path of the project to which the sample program belongs. 
$download_file = "D:\\localpath\\example-new.jpg";

$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

// If the image does not exist in the required bucket, you must upload the image to the required bucket. 
// $ossClient->uploadFile($bucket, $object, "D:\\localpath\\exampleobject.jpg");

// Use the custom style to process the image. 
// Set yourCustomStyleName to the name of the image style you create in the OSS console. 
$style = "style/yourCustomStyleName";

$options = array(
    OssClient::OSS_FILE_DOWNLOAD => $download_file,
    OssClient::OSS_PROCESS => $style);

// Name the processed image example-new.jpg and save the image to your local computer. 
$ossClient->getObject($bucket, $object, $options);

// After the image is processed, you can delete the source image if you no longer use the image from the bucket. 
// $ossClient->deleteObject($bucket, $object);                              
const OSS = require('ali-oss');

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourregion',
  // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
  accessKeyId: 'yourAccessKeyId',
  accessKeySecret: 'yourAccessKeySecret',
  // Specify yourbucketname as the name of the bucket. 
  bucket: 'yourbucketname'
});
// Specify the custom image style. 
async function style () {
  try {
    const result = await client.get('example.jpg', './example-custom-style.jpg', {process: 'style/example-style"'});
  } catch (e) {
    console.log(e);
  }
}
style();
# -*- coding: utf-8 -*-
import os
import oss2
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
access_key_id = 'yourAccessKeyId'
access_key_secret = 'yourAccessKeySecret'
# Specify the name of the bucket in which the source image is stored. Example: examplebucket. 
bucket_name = 'examplebucket'
# Specify the name of the source image. If the image is not stored in the root directory of the bucket, you must add the full path of the image. Example: exampledir/example.jpg. 
key = 'exampledir/example.jpg'
# Specify the name of the processed image. 
new_pic = 'exampledir/newexample.jpg'

# Specify the bucket instance. You must use the bucket instance to call all object-related methods. 
bucket = oss2.Bucket(oss2.Auth(access_key_id, access_key_secret), endpoint, bucket_name)
# If the image is not stored in the specified bucket, you must upload the image from the local path to the specified bucket. 
# bucket.put_object_from_file(key, 'D:\\localpath\\example.jpg')

# Use the custom style to process the image. Set yourCustomStyleName to the name of the image style that you have created in the OSS console. 
style = 'yourCustomStyleName'
# Save the processed image to your local computer. 
bucket.get_object_to_file(key, new_pic, process=style)
# After the image is processed, you can delete the source image from the bucket if you no longer need the image. 
# bucket.delete_object(key)
# If you no longer use the processed image, you can delete the image. 
# os.remove(new_pic)
using System;
using System.IO;
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Util;
namespace ImageProcessCustom
{
    class Program
    {
        static void Main(string[] args)
        {
            Program.ImageProcessCustomStyle();
            Console.ReadKey();
        }
        public static void ImageProcessCustomStyle()
        {
            // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
            var endpoint = "yourEndpoint";
            // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
            var accessKeyId = "yourAccessKeyId";
            var accessKeySecret = "yourAccessKeySecret";
            // Specify the name of the bucket in which the source image is stored. Example: examplebucket. 
            var bucketName = "examplebucket";
            // Specify the name of the source image. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg. 
            var objectName = "exampledir/example.jpg";
            // Specify the local full path of the source image. 
            // var localImageFilename = "D:\\localpath\\example.jpg";
            // Specify the local directory to which you want to save the processed image. 
            var downloadDir = "yourDownloadDir";
            // Create an OSSClient instance. 
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            try
            {
                // If the image that you want to process does not exist in the specified bucket, you must upload the image to the specified bucket.    
                // client.PutObject(bucketName, objectName, localImageFilename);
                // Use an image style to process the image. In this example, yourCustomStyleName is set to the name of the image style that you created in the OSS console. 
                var process = "style/yourCustomStyleName";
                var ossObject = client.GetObject(new GetObjectRequest(bucketName, objectName, process));
                // Specify the name of the processed image.             
                WriteToFile(downloadDir + "/yourLocalFilename", ossObject.Content);
                Console.WriteLine("Get Object:{0} with process:{1} succeeded ", objectName, process);
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
        private static void WriteToFile(string filePath, Stream stream)
        {
            using (var requestStream = stream)
            {
                using (var fs = File.Open(filePath, FileMode.OpenOrCreate))
                {
                    IoUtils.WriteTo(stream, fs);
                }
            }
        }
    }
}
package main

import (
    "fmt"
    "os"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func HandleError(err error) {
    fmt.Println("Error:", err)
    os.Exit(-1)
}

func main() {
    // Create an OSSClient instance.    
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
    // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
    client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
    if err != nil {
    HandleError(err)
    }

    // Specify the name of the bucket in which the source image is stored. Example: examplebucket. 
    bucketName := "examplebucket"
    bucket, err := client.Bucket(bucketName)
    if err != nil {
     HandleError(err)
    }
    // Specify the name of the source image. If the image is not stored in the root directory of the bucket, precede the image name with the path to the image. Example: example/example.jpg. 
    sourceImageName := "example/example.jpg"
    // Set the name of the processed image to newexample.jpg and specify the path where you want to store the processed image on your local computer. 
    targetImageName := "D:\\localpath\\newexample.jpg"
    // Use the specified image style to process the image. In this example, yourCustomStyleName is set to the name of the image style that you created in the OSS console. 
    style := "style/yourCustomStyleName"
    // Save the processed image to your local computer. 
    err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(style))
    if err != nil {
    HandleError(err)
    }
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
     /* Initialize OSS account information. */
    /* The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. */
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the name of the bucket in which the source image is stored. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the name of the source image. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg. */
    std::string ObjectName = "exampledir/example.jpg";

     /* Initialize resources such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf) ;

    /* Use the image style to process the image. In this example, replace yourCustomStyleName with the name of the image style that you create in the OSS console. */
    std::string Process = "style/yourCustomStyleName";
    GetObjectRequest request(BucketName, ObjectName);
    request.setProcess(Process);
    auto outcome = client.GetObject(request);

    /* Release resources such as network resources. */
    ShutdownSdk();
    return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. */
const char *access_key_id = "yourAccessKeyId";
const char *access_key_secret = "yourAccessKeySecret";
/* Specify the bucket name. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. The full path of the object cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Use a char* string to initialize the aos_string_t data type. */
    aos_str_set(&options->config->endpoint, endpoint);
    aos_str_set(&options->config->access_key_id, access_key_id);
    aos_str_set(&options->config->access_key_secret, access_key_secret);
    /* Specify whether to use CNAME. A value of 0 indicates that CNAME is not used. */
    options->config->is_cname = 0;
    /* Configure network parameters such as the timeout period. */
    options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
    /* Call the aos_http_io_initialize method in main() to initialize global resources such as networks and memory. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* Create a memory pool to manage memory. aos_pool_t is equivalent to apr_pool_t. The code used to create a memory pool is included in the APR library. */
    aos_pool_t *pool;
    /* Create a memory pool. The value of the second parameter is NULL. This value indicates that the pool does not inherit other memory pools. */
    aos_pool_create(&pool, NULL);
    /* Create and initialize options. This parameter includes global configuration information such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
    oss_request_options_t *oss_client_options;
    /* Allocate the memory resources in the memory pool to the options. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize oss_client_options. */
    init_options(oss_client_options);
    /* Initialize the parameters. */
    aos_string_t bucket;
    aos_string_t object;
    aos_string_t file;
    aos_table_t *headers = NULL;
    aos_table_t *params = NULL;
    aos_table_t *resp_headers = NULL;
    aos_status_t *resp_status = NULL;
    aos_str_set(&bucket, bucket_name);
    aos_str_set(&object, object_name);
    /* Specify the image style. */
    params = aos_table_make(pool, 1);
    apr_table_set(params, OSS_PROCESS, "style/<yourCustomStyleName>");
    /* Save the processed image to your local computer. */
    aos_str_set(&file, "<LocalFileName>");
    resp_status = oss_get_object_to_file(oss_client_options, &bucket, &object, headers, params, &file, &resp_headers);
    if (aos_status_is_ok(resp_status)) {
        printf("get object to file succeeded\n");
    } else {
        printf("get object to file failed\n");  
    }
    /* Release the memory pool. This operation releases the memory resources allocated for the request. */
    aos_pool_destroy(pool);
    /* Release the allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}

Import a style of the source bucket to the destination bucket

You can export a style that is created in the source bucket and import the style to the destination bucket. This way, you can apply the style in the destination bucket to process image objects.

  1. Export a style from the source bucket.
    1. On the Overview page of the source bucket, choose Data Processing > Image Processing (IMG) in the left-side navigation pane.
    2. Click Export.
    3. In the Save As dialog box, select the path to which you want to save the style, and click Save.
  2. Import the style to the destination bucket.
    1. On the Overview page of the destination bucket, choose Data Processing > Image Processing (IMG) in the left-side navigation pane.
    2. Click Import.
    3. In the Open dialog box, select the exported image style file and click Open.
      After the style is imported to the destination bucket, you can use the style to process images stored in the bucket.

References