You can scale an image up or down by adding image scaling parameters to a GetObject request.
Scenarios
Web design: Adapt images to different screen sizes and resolutions for web and mobile app development.
Social media: Process user-uploaded images of various sizes into standard preview dimensions.
Image recognition and analysis: Scale images to improve processing efficiency in computer vision and machine learning.
Limits
Limit | Item | Description |
Source image limits | Image format | Source images can be in JPG, PNG, BMP, GIF, WebP, TIFF, or HEIC format. |
Image size | A source image cannot exceed 20 MB in size. To adjust the source image size limit, submit a request in Quota Center. | |
Image dimensions | The width or height of the source image cannot exceed 30,000 px. The total number of pixels cannot exceed 250 million. Note For animated images, such as GIFs, the total number of pixels is calculated as | |
Scaled image limits | Image scaling | The width or height of the scaled image cannot exceed 16,384 px. The total number of pixels cannot exceed 16,777,216. |
Methods
When you include the ?x-oss-process=image/resize,parame_value parameter in a request, OSS processes the image in real time and returns the result. image/resize specifies the scaling operation. parame is a supported scaling parameter, and value is the value of the parameter. For more information about the parameters, see Parameters. You can use multiple parameters together.
For public-read images, you can add processing parameters to the image URL to allow permanent anonymous access. For private images, you can call an SDK with signature information or an API to process the image.
Public-read images
The following table describes how to add the ?x-oss-process=image/resize,parame_value parameter to the URL of a public-read image. Replace parame_value with the specific parameters and values that you need.
Original image URL | Image URL with processing parameters |
https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg |
Private images
You can use an OSS SDK to generate a signed URL with image scaling parameters. This grants users temporary access to the processed image. The following examples show how to generate a signed URL with the ?x-oss-process=image/parame_value parameter for a private image:
Java
package com.aliyun.oss.demo;
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import java.net.URL;
import java.util.Date;
public class Demo {
public static void main(String[] args) throws Throwable {
// Set the endpoint. In this example, the China (Hangzhou) region is used. Specify the 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 bucket name, for example, examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. If the image is not in the root directory of the bucket, include the full path, for example, exampledir/exampleobject.jpg.
String objectName = "exampledir/exampleobject.png";
// Specify the region where the bucket is located. In this example, the China (Hangzhou) region is used. Set Region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// When the OSSClient instance is no longer used, call the shutdown method to release resources.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Scale the image. Replace parame_value with a specific parameter and value. For example, p_50 indicates that the image is proportionally scaled down to 50% of its original size.
String style = "image/resize,parame_value";
// Set the expiration time of the signed URL to 3,600 seconds.
Date expiration = new Date(new Date().getTime() + 3600 );
GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
req.setExpiration(expiration);
req.setProcess(style);
URL signedUrl = ossClient.generatePresignedUrl(req);
System.out.println(signedUrl);
} 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();
}
}
}
}Python
# -*- 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 bucket name.
bucket = 'examplebucket'
# Specify the endpoint of the region where the bucket is located. In this example, the China (Hangzhou) region is used.
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# Specify the general-purpose region ID of Alibaba Cloud.
region = 'cn-hangzhou'
bucket = oss2.Bucket(auth, endpoint, bucket, region=region)
# Specify the name of the source image. If the image is not in the root directory of the bucket, include the full path, for example, exampledir/exampleobject.jpg.
key = 'exampledir/exampleobject.png'
# Specify the expiration time in seconds.
expire_time = 3600
# Scale the image. Replace parame_value with a specific parameter and value. For example, p_50 indicates that the image is proportionally scaled down to 50% of its original size.
image_process = 'image/resize,parame_value'
# Generate a signed URL that contains image processing parameters.
url = bucket.sign_url('GET', key, expire_time, params={'x-oss-process': image_process}, slash_safe=True)
# Print the signed URL.
print(url)PHP
<?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();
// Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "yourEndpoint";
// Specify the bucket name, for example, examplebucket.
$bucket= "examplebucket";
// Specify the full path of the object, for example, exampledir/exampleobject.jpg. The full path cannot contain the bucket name.
$object = "exampledir/exampleobject.jpg";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
// Generate a signed URL that contains image processing parameters. The URL is valid for 3,600 seconds and can be accessed in a browser.
$timeout = 3600;
$options = array(
// Scale the image. Replace parame_value with a specific parameter and value. For example, p_50 indicates that the image is proportionally scaled down to 50% of its original size.
OssClient::OSS_PROCESS => "image/resize,parame_value");
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
print("rtmp url: \n" . $signedUrl);Go
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.
// Set yourEndpoint to the endpoint of the bucket. In this example, the China (Hangzhou) region is used. Set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify the actual endpoint for other regions.
// Set yourRegion to the region where the bucket is located. In this example, the China (Hangzhou) region is used. Set the region to cn-hangzhou. Specify the actual region for other regions.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
HandleError(err)
}
// Specify the name of the bucket where the image is stored, for example, examplebucket.
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
HandleError(err)
}
// Specify the name of the image. If the image is not in the root directory of the bucket, include the full path, for example, exampledir/exampleobject.jpg.
ossImageName := "exampledir/exampleobject.png"
// Generate a signed URL and set the expiration time to 3,600s. The maximum validity period is 32,400 seconds.
// Scale the image. Replace parame_value with a specific parameter and value. For example, p_50 indicates that the image is proportionally scaled down to 50% of its original size.
signedURL, err := bucket.SignURL(ossImageName, oss.HTTPGet, 3600, oss.Process("image/resize,parame_value"))
if err != nil {
HandleError(err)
} else {
fmt.Println(signedURL)
}
}The following is an example of a generated signed URL:
https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampledir/exampleobject.png?x-oss-process=image%2Fresize%2Cp_50&x-oss-date=20241111T113707Z&x-oss-expires=3600&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI********************%2F20241111%2Fcn-hangzhou%2Foss%2Faliyun_v4_request&x-oss-signature=6fd07a2ba50bf6891474dc56aed976b556b6fbcd901cfd01bcde5399bf4802cbFor more information about how to use other SDKs to scale images, see SDK overview.
Parameters
Action: resize
Proportional scaling
You can use the p parameter to specify the percentage for proportional scaling.
Parameter | Description | Value |
p | Scales the image by percentage. | [1,1000] A value less than 100 scales down the image. A value greater than 100 scales up the image. |
This type of proportional scaling is not supported for animated images.
Scaling by specified dimensions
You can use the w and h parameters to specify the width and height. You can use the m parameter to control the scaling mode for different layouts. To control the longer or shorter edge of the scaled image, you can use the l or s parameter. To scale up an image, you must add the limit_0 parameter.
Parameter | Description | Value |
w | The width of the scaled image. | [1,16384] |
h | The height of the scaled image. | [1,16384] |
m | The scaling mode. |
For more information about the images that are obtained after you scale an image in different modes, see Scaling calculation methods. Note If you set the scaling mode |
l | The longer edge of the scaled image. Note The longer edge is the greater of the width and height. For example, if the source image is 100 px × 200 px, the longer edge is 200 px and the shorter edge is 100 px. | [1,16384] |
s | The shorter edge of the scaled image. | [1,16384] |
limit | Specifies whether to scale the image if the resolution of the target image is higher than the resolution of the source image. Important By default, if the target image is larger than the source image, the source image is returned. To scale up the image, you must add the |
Note For animated images, you can only scale them down by specifying the width and height. Proportional scaling down and scaling up are not supported. |
color | The color for padding when the scaling mode is set to pad. | An RGB color value. Example: 000000 for black and FFFFFF for white. Default value: FFFFFF (white) |
If you specify only the width or height for scaling:
If the scaling mode is `lfit`, `mfit`, or `fixed`, the image is scaled proportionally. For example, if the source image is 256 px × 144 px and you scale the height to 100 px, the width is scaled to 178 px.
If the scaling mode is `pad` or `fill`, the image is scaled to the specified dimensions. For example, if the source image is 256 px × 144 px and you scale the height to 100 px, the width is also scaled to 100 px.
If you specify only the
lorsparameter, the image is scaled based on the specified edge, and the other edge is automatically adjusted based on the aspect ratio of the source image. In this case, themparameter does not take effect.If you specify both the
landsparameters, the image is scaled while maintaining the aspect ratio. In this case, themparameter takes effect. If you do not specify a scaling mode, the defaultlfitmode is used.
Scaling calculation methods
Source image size | Scaling parameters | Scaling mode | Scaled image size |
200 px × 100 px | 150 px × 80 px | lfit (default) Proportionally scales the image to the maximum size that fits within the rectangle of the specified width and height. | 150 px × 75 px
|
mfit Proportionally scales the image to the minimum size that extends beyond the rectangle of the specified width and height. | 160 px × 80 px
| ||
fill Proportionally scales the image to the minimum size that extends beyond the rectangle of the specified width and height, and then crops the image to the specified dimensions. | 150 px × 80 px
| ||
pad Proportionally scales the image to the maximum size that fits within the rectangle of the specified width and height, and then pads the image with a color to meet the specified dimensions. | 150 px × 80 px
| ||
fixed Forces the image to be scaled to the specified width and height. If the aspect ratio is different from that of the source image, the image is distorted. | 150 px × 80 px
|
If the scaling mode is `lfit` or `mfit` and the ratio is a decimal, the value is rounded to the nearest integer.
Examples
Billing
When you resize images, the following fees are incurred. For pricing details of billable items, see OSS Pricing.
API
Billable item
Description
GetObject
GET requests
You are charged request fees based on the number of successful requests.
Outbound traffic over the Internet
If you call the GetObject operation by using a public endpoint, such as oss-cn-hangzhou.aliyuncs.com, or an acceleration endpoint, such as oss-accelerate.aliyuncs.com, you are charged fees for outbound traffic over the Internet based on the data size.
Retrieval of IA objects
If IA objects are retrieved, you are charged IA data retrieval fees based on the size of the retrieved IA data.
Retrieval of Archive objects in a bucket for which real-time access is enabled
If you retrieve Archive objects in a bucket for which real-time access is enabled, you are charged Archive data retrieval fees based on the size of retrieved Archive objects.
Transfer acceleration fees
If you enable transfer acceleration and use an acceleration endpoint to access your bucket, you are charged transfer acceleration fees based on the data size.
Related API operations
If your application has high custom requirements, you can directly call REST APIs. This requires you to manually write code to calculate signatures. For more information about how to calculate the Authorization header for public requests, see Signature V4 (recommended).
You can process images by adding image scaling parameters to the GetObject operation. For more information, see GetObject.
GET /oss.jpg?x-oss-process=image/resize,p_50 HTTP/1.1
Host: oss-example.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: SignatureValue


















