All Products
Search
Document Center

Object Storage Service:Resize images

Last Updated:Oct 12, 2024

You may want to resize an image to accelerate image loading, reduce storage usage, lower bandwidth costs, or present the image in a preferred size. Object Storage Service (OSS) provides the resize action to resize an image in a bucket. This topic describes the parameters used in the resize action and provides some examples of image resizing.

Usage notes

  • Limits on source images

    • The following image formats are supported: JPG, PNG, BMP, GIF, WebP, TIFF and HEIC.

      Important
      • The size of a GIF image can be reduced based on the specified width and height but cannot be reduced by percentage. GIF images become static images if you reduce the sizes of the images by percentage.

      • GIF images cannot be enlarged.

    • The size of a source image cannot exceed 20 MB. You can apply to adjust the limit on the size of source images in the Quota Center..

      Note

      The limit on the size of source images can be adjusted only when you use image resizing parameters to resize images.

    • The width or height of a source image cannot exceed 30,000 pixels. The total number of pixels of a source image cannot exceed 250 million.

      The total number of pixels of a dynamic image, such as a GIF image, is calculated by using the following formula: Width × Height × Number of image frames. The total number of pixels of a static image, such as a PNG image, is calculated by using the following formula: Width × Height.

  • Limits on resized images

    The width or height of a resized image cannot exceed 16,384 pixels. The total number of pixels of a resized image cannot exceed 16,777,216.

  • Resizing priorities

    If you specify parameters both for resizing based on the width and height and for proportionally resizing in a URL, the image is resized based on the specified width and height.

  • Image resizing based on the specified width or height

    • The source image is proportionally resized when proportional resizing is performed. For example, if you resize the width of a source image of 200 × 100 pixels to 100 pixels, the height of the source image is resized to 50 pixels.

    • The source image is resized based on the specified width or height. For example, if you resize the height of a source image of 200 × 100 pixels to 100 pixels, the width of the source image is also resized to 100 pixels.

  • If the size of the resized image is larger than the size of the source image, the source image is returned. You can add the limit_0 parameter to enlarge the image. Example: https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/resize,w_500,limit_0.

Parameter description

Action: resize

Resize an image based on the specified height and width

  • Parameters

    Parameter

    Required

    Description

    Valid value

    m

    Yes

    Specifies the type of the resize action.

    • lfit: OSS proportionally resizes the source image as large as possible in a rectangle based on the specified width and height. This is the default value.

    • mfit: OSS proportionally resizes the source image as small as possible outside a rectangle based on the specified width and height.

    • fill: OSS proportionally resizes the source image as small as possible outside a rectangle based on the specified width and height, and then crop the image from the center to the specified width and height.

    • pad: OSS proportionally resizes the source image as large as possible in a rectangle based on the specified width and height, and fills the empty space in the rectangle from the center with a specific color.

    • fixed: OSS forcibly resizes the source image based on the fixed width and height.

    For more information about examples of each resizing type, see Examples.

    Important
    • If you set this parameter to lfit or mfit, the aspect ratio (the ratio of the width to the height) of the source image is rounded to an integer if the ratio is a decimal.

    • If you specify the m parameter and specify a value for w or h, the values specified for l and s do not take effect.

    w

    No

    Specifies the width to which you want to resize the image.

    [1,16384]

    h

    No

    Specifies the height to which you want to resize the image.

    [1,16384]

    l

    Yes

    Specifies the length of the longer side to which you want to resize the image.

    Note

    If you specify only the l parameter or the s parameter, the source image is resized based on the longer or the shorter side, and the other side is resized based on the ratio that is calculated according to the specified width and height. In this case, the m parameter is invalid.

    If you specify both the l and s parameters, the source image is resized based on the specified ratio. The m parameter takes effect. The default resizing type is lfit.

    [1,16384]

    s

    Yes

    Specifies the length of the shorter side to which you want to resize the image.

    Note

    If you specify only the l parameter or the s parameter, the source image is resized based on the longer or the shorter side, and the other side is resized based on the ratio that is calculated according to the specified width and height. In this case, the m parameter is invalid.

    If you specify both the l and s parameters, the source image is resized based on the specified ratio. The m parameter takes effect. The default resizing type is lfit.

    [1,16384]

    limit

    No

    Specifies whether to resize the image when the resolution of the target image is higher than the resolution of the source image.

    • 1 (default): OSS returns the image that is processed based on the resolution of the source image. The size of the returned image may be different from the size of the source image.

    • 0: OSS resizes the source image based on the specified parameter.

    Note

    The size of a GIF image can only be reduced.

    color

    Yes (only when the value of m is pad)

    If you set the resizing type to pad, you can select a color to fill the empty space.

    RGB color values. For example, 000000 specifies black, and FFFFFF specifies white.

    Default value: FFFFFF.

  • Examples

    The source image is 200 × 100 pixels in size. The w parameter is set to 150, and the h parameter is set to 80. The source image is resized to different sizes when you specify different resize types.

    lfit

    • Proportional resizing: The aspect ratio of the resized image must be equal to the aspect ratio of the source image. If the width of the resized image is 150 pixels, the height of the resized image is 75 pixels. If the height of the resized image is 80 pixels, the width of the resized image is 160 pixels.

    • Maximum image size in a rectangle based on the specified width and height: The width and height of the resized image cannot exceed 150 pixels and 80 pixels, respectively.

    In this case, the resized image is 150 × 75 pixels in size.

    lfit

    mfit

    • Proportional resizing: The aspect ratio of the resized image must be equal to the aspect ratio of the source image. If the width of the resized image is 150 pixels, the height of the resized image is 75 pixels. If the height of the resized image is 80 pixels, the width of the resized image is 160 pixels.

    • Minimum image size outside a rectangle based on the specified width and height: The resized image must be a minimum rectangle whose size is greater than 150 × 80 pixels.

    In this case, the resized image is 160 × 80 pixels in size.

    mfit

    fill

    The fill resize type is used to proportionally resize the source image to an image as small as possible outside a rectangle with the specified w and h as its side lengths and then crop the image from the center to the specified width and height. In this case, the source image is resized to 160 × 80 pixels. The resulting image is then cropped to a width of 150 pixels from the center to produce a final image whose size is 150 × 80 pixels.fill

    pad

    The pad resize type is used to proportionally resize the source image to an image as large as possible in a rectangle with the specified w and h as its side lengths and then fill the remaining empty space in the rectangle based on the specified width and height to produce a final image that has the required size. In this case, the source image is resized to 150 × 75 pixels. The height of the resulting image is filled to 80 pixels from the center to produce a final image whose size is 150 × 80 pixels.pad

    fixed

    The fixed resize type resizes the source image based on the specified width and height. If the aspect ratio of the intended image is different from that of the source image, the resulting image is distorted.fixed

Resize an image by percentage

Parameter

Required

Description

Valid value

p

Yes

Specifies the percentage by which you want to resize the image.

[1,1000]

A value smaller than 100 specifies that the image size is reduced. A value greater than 100 specifies that the image is enlarged.

Implementation methods

Resize a public-read or public-read write image

You can add image processing (IMG) parameters to the URL of a public-read or public-read write image to resize the image.

This section provides examples on how to resize an image in the oss-console-img-demo-cn-Hangzhou bucket in the China (Hangzhou) region. The image is 400 × 300 pixels in size and is hosted at the following URL:

Resize a private image

You can use OSS SDKs and API operations to resize a private image.

Use OSS SDKs

The following sample code provides examples on how to resize an image by using OSS SDKs for common programming languages. For more information about how to resize an image by using other programming languages, see Overview.

Java

OSS SDK for Java 3.17.4 or later is required.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GetObjectRequest;
import java.io.File;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // Specify the endpoint of the region. In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the region of the bucket in which the private image is stored. Example: cn-hangzhou. 
        String region = "cn-hangzhou";
        // 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 = "src.jpg";
        // Specify the full path to which you want to save the processed image. Example: D:\\localpath\\example-new.jpg. If a file that has 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:\\dest.jpg";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Resize the image to 100 x 100 pixels. 
            String image = "image/resize,m_fixed,w_100,h_100";
            GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
            request.setProcess(image);
            // Save the processed image as example-new.jpg 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("D:\\dest.jpg"));
        } 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

OSS SDK for PHP 2.7.0 or later is required.

<?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\Credentials\EnvironmentVariableCredentialsProvider;
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. 
$provider = new 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. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 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 = "src.jpg";
// Specify the full path to which you want to save the processed image. Example: D:\\localpath\\example-new.jpg. If a file that has 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 local file such as example-new.jpg without specifying the local path of the file, the processed image is saved to the path of the project to which the sample program belongs. 
$download_file = "D:\\dest.jpg";

$config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,        
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        // Specify the ID of the Alibaba Cloud region in which the bucket is located. 
        "region" => "cn-hangzhou"
    );
$ossClient = new OssClient($config);

// Resize the image to 100 x 100 pixels. 
$image = "image/resize,m_fixed,w_100,h_100";

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

// Save the processed image to your local computer. 
$ossClient->getObject($bucket, $object, $options);                           

Python

OSS SDK for Python 2.18.4 or later is required.

# -*- coding: utf-8 -*-
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.ProviderAuthV4(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 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'
# Specify the ID of the Alibaba Cloud region in which the bucket is located. 
region = 'cn-hangzhou'
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)
# 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. 
key = 'src.jpg'
# Specify the name of the processed image. 
new_pic = 'D:\\dest.jpg'

# Resize the image to 100 × 100 pixels. 
image = 'image/resize,m_fixed,w_100,h_100'
bucket.get_object_to_file(key, new_pic, process=image)

Go

OSS SDK for Go 3.0.2 or later is required.

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() {
	// 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. 
	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("https://oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region("cn-hangzhou"))
	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, you must specify the full path of the image. Example: exampledir/example.jpg. 
	sourceImageName := "src.jpg"
	// Specify the name of the processed image. 
	targetImageName := "D://dest.jpg"
	// Resize the image to 100 x 100 pixels. 
	image := "image/resize,m_fixed,w_100,h_100"
	err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(image))
	if err != nil {
		HandleError(err)
	}
}

Use the OSS API

If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see GetObject.

You can add image resizing parameters to the GetObject operation to resize an image.

GET /oss.jpg?x-oss-process=image/resize,w_100 HTTP/1.1
Host: oss-example.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: OSS qn6q**************:77Dv****************

FAQ

How do I access a compressed image if the access control list (ACL) of the image is private?

To access the image, add signature information to the URL of the image. For more information, see Share objects with object URLs.

Am I charged for sending image compression requests?

Yes. You are charged for sending image compression requests. For more information, see API operation calling fees.

Am I charged for compressing images?

No. You are not charged for compressing images.

Is the traffic fee for an image resizing request calculated based on the source image or the resized image?

The traffic fee for an image resizing request is calculated based on the resized image. For example, if you request to resize a 20 MB image to a 2 MB image, the traffic fee generated for the request is calculated based on the resized image, which is 2 MB.

What do I do if an image fails to be enlarged by width or height?

To enlarge an image by width or height, set the limit parameter to 0. Otherwise, the image fails to be enlarged.

For example, the following URL enlarges an image by height from 300 pixels to 500 pixels.

https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/resize,h_500,limit_0