All Products
Search
Document Center

Object Storage Service:Image styles

Last Updated:Jan 22, 2024

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. You can use the image styles only for the images that are stored in the bucket. If your business requires more image styles, contact technical support.

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  3. In the left-side navigation tree, choose Data Processing > IMG.

  4. On the IMG page, click Create Style.

  5. In the Create Style panel, use one of the following methods to configure the style:

    • Basic Settings: Use a GUI to configure the following parameters that you want to use to process your images.

      Parameter

      Description

      Rule Name

      Specify the name of the image style rule. The name must be 1 to 63 characters in length and can contain only letters, digits, underscores (_), hyphens (-), and periods (.).

      Format Conversion

      Specify the format to which you want to convert the image. If you set Format Conversion to Original Format, the format of the image is not converted.

      If you want to convert the format of the image, you can set Format Conversion to one of the following values based on your requirements: jpg, jpeg, png, bmp, gif, webp, and tiff.

      Progressive Display

      Select whether to enable progressive display. Progressive display first provides a fuzzy outline of an image and gradually loads the image until the complete image is displayed.

      Note

      This parameter is valid only for images that are in the JPG format.

      Auto Orientation

      Specify whether to rotate the image based on the EXIF data of the image before it is resized.

      Quality

      Specifies the quality of the image. Valid values: Relative, Absolute, and Uncompressed.

      For more information about image quality, see Adjust image quality.

      Cropping

      Specify the Mode, Cropping Effect, Ratio, and Shape parameters in the Cropping section.

      Resize Type

      Specify the resize type of the image. Valid values: Thumbnail Disabled, Proportional Scale Down, Proportional Scale Up, and Fixed Width and/or Height.

      Brightness

      Specify the brightness of the image. You can drag the slider to adjust the brightness.

      A value of 0 specifies the same brightness level as the source image. A value smaller than 0 specifies a brightness level lower than that of the source image. A value greater than 0 specifies a brightness level higher than that of the source image.

      Contrast

      Specify the contrast of the image. You can drag the slider to adjust the contrast.

      A value of 0 specifies the same contrast level as the source image. A value smaller than 0 specifies a contrast level lower than that of the source image. A value greater than 0 specifies a contrast level higher than that of the source image.

      Sharpen

      Specify whether to sharpen the image.

      After you turn on Sharpen, you can drag the slider to adjust the sharpness.

      Blur

      Specify whether to blur the image. After you turn on Blur, you can drag the slider to adjust the blur radius and blur deviation.

      Rotate

      Specify the angle of rotation for the image. You can drag the slider to adjust the image rotation angle.

      Add Watermark

      Select whether to add watermarks to the image. After you turn on Add Watermark, you can add image watermarks or text watermarks to the image.

    • Advanced Settings: Create an image style rule by adding code to the Code field. Enter the code in the following format: image/action1,parame_value1/action2,parame_value2/.... For more information about the supported IMG parameters, see IMG Parameters.

      For example, image/resize,p_63/quality,q_90 is used to resize an image to 63% of the original size and change the relative quality of the image to 90%.

      Note

      If you want to add image and text watermarks to an image by using an image style, use Advanced Settings to create an image style.

  6. Click OK.

Usage notes

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

Important

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, dynamic images may become static images after they are processed.

Use an image style for image processing by using image URLs

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

If you specify a custom delimiter, you can simplify the URL for image processing by replacing ?x-oss-process=style/ with the delimiter. For more information about how to specify a custom delimiter, see Protect source images.

For example, if you specify the exclamation mark (!) as the delimiter, the URL format for image processing is simplified as 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 a bucket, the URL for processing the example.jpg image in the bucket is https://example.com/example.jpg!small. After you map a custom domain name, you can preview the effect of IMG online. For more information, see Map custom domain names.

Use an image style for image processing by using OSS SDKs

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

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
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 your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Do not include the bucket name in the full path. 
        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, the processed image is saved in the path. 
        String pathName = "D:\\localpath\\example-new.jpg";

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

        try {
            // Use a custom image style to process the image. 
            // In this example, replace yourCustomStyleName with the name of the image style that you created 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. 
            // If you specify only 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;
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
$accessKeyId = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// 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 = "yourEndpoint";
// Specify the name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.jpg. Do not include the bucket name in the full path. 
$object = "exampledir/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, the processed image is saved in the path. 
// If you specify only the name of the file, such as example-new.jpg, but do not specify the local path, the file is saved to the 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 that you want to process does not exist in the specified bucket, you must upload the image to the specified bucket. 
// $ossClient->uploadFile($bucket, $object, "D:\\localpath\\exampleobject.jpg");

// Use a custom image style to process the image. 
// Replace yourCustomStyleName with the name of the image style that you created 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 from the bucket if you no longer need the image. 
// $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',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the name of the bucket. 
  bucket: 'yourbucketname'
});

// Resize the image to 100 × 100 pixels. 
async function scale() {
  try {
    const result = await client.get('example.jpg', './example-resize.jpg', { process: 'image/resize,m_fixed,w_100,h_100'});
  } catch (e) {
    console.log(e);
  }
}

scale()

// Crop the image to 100 x 100 pixels starting from the position specified by the coordinate pair (100, 100). 
async function cut() {
  try {
     const result = await client.get('example.jpg', './example-crop.jpg', { process: 'image/crop,w_100,h_100,x_100,y_100,r_1'});
  } catch (e) {
    console.log(e)
  }
}

cut()

// Rotate the image 90 degrees. 
async function rotate() {
  try {
    const result = await client.get('example.jpg', './example-rotate.jpg', { process: 'image/rotate,90'});
  } catch (e) {
    console.log(e);
  }
}

rotate()

// Sharpen the image. Set the parameter to 100. 
async function sharpen() {
  try {
    const result = await client.get('example.jpg', './example-sharpen.jpg', { process: 'image/sharpen,100'});
  } catch (e) {
    console.log(e);
  }
}

sharpen()

// Add watermarks to the image. 
async function watermark() {
  try {
    const result = await client.get('example.jpg', './example-watermark.jpg', { process: 'image/watermark,text_SGVsbG8g5Zu-54mH5pyN5YqhIQ'});
  } catch (e) {
    console.log(e);
  }
}

watermark()

// Convert the format of the image. 
async function format() {
  try {
    const result = await client.get('example.jpg', './example-format.jpg', { process: 'image/format,png'});
  } catch (e) {
    console.log(e);
  }
}

format()

// Obtain the image information. 
async function info() {
  try {
    const result = await client.get('example.jpg', './example-info.txt', {process: 'image/info'});
  } catch (e) {
    console.log(e);
  }
}

info()
# -*- coding: utf-8 -*-
import os
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# 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 the name of the bucket. 
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
# 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 specify the path of the image. Example: example/example.jpg. 
key = 'exampledir/example.jpg'
# Specify the name of the processed image. 
new_pic = 'exampledir/newexample.jpg'

# If the image that you want to process does not exist in the specified bucket, you must upload the image that is stored in the local path of the bucket. 
# bucket.put_object_from_file(key, 'D:\\localpath\\example.jpg')

# Use a custom image style to process the image. Set yourCustomStyleName 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. 
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 need the processed image, you can delete the image. 
# os.remove(new_pic)
package main

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

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

func main() {
	// Obtain access credentials from the environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// 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. 
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// 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, you must specify the full path of the image. Example: example/example.jpg. 
	sourceImageName := "example/example.jpg"
	// Save the image as newexample.jpg to your local computer. 
	targetImageName := "D:\\localpath\\newexample.jpg"
	// Use the image style to process the image. In this example, replace yourCustomStyleName with 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 information about the account that is used to access OSS. */
    
    /* 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;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);

    /* Use the image style to process the image. Replace yourCustomStyleName with the name of the image style that you created in Step 1. */
    std::string Process = "style/yourCustomStyleName";
    GetObjectRequest request(BucketName, ObjectName);
    request.setProcess(Process);
    auto outcome = client.GetObject(request);
    if (outcome.isSuccess()) {
    std::cout << "Image processed successfully." << std::endl;
    } else {
    std::cout << "Failed to process image. Error code: " << outcome.error().Code()
              << ", Message: " << outcome.error().Message()
              << ", RequestId: " << outcome.error().RequestId() << std::endl;
    }
  
    /* 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";
/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. Do not include the bucket name in the full path. 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 data of the aos_string_t type. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
    aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
    /* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
    options->config->is_cname = 0;
    /* Specify 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 network resources and memory resources. */
    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);
    /* Set yourCustomStyleName to the name of the image style that you created in Step 1. */
    apr_table_set(params, OSS_PROCESS, "style/yourCustomStyleName");
    /* Save the processed image to your local computer. */
    aos_str_set(&file, "yourLocalFileName");
    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 image styles from a source bucket to a destination bucket

You can import image styles that are created for a source bucket to a destination bucket. This way, you can use the image styles to process image objects in the destination bucket.

  1. Export image styles from a source bucket.

    1. In the left-side navigation tree of the source bucket, choose Data Processing > IMG.

    2. On the IMG page, click Export Style.

    3. Save.

  2. Import the image styles to a destination bucket.

    1. In the left-side navigation tree of the destination bucket, select Data Processing > IMG.

    2. On the IMG page, click Import Style.

    3. In the dialog box that appears, select the exported image style file and click Open.

      After the image style file is imported to the destination bucket, you can use the image styles to process images in the destination bucket.

References