You can add image resizing parameters to GetObject
requests to resize images.
Scenarios
Web page design: During web page design and mobile app development, images must be automatically adjusted to display on devices with different screen sizes and resolutions.
Social media: Images uploaded by users on social media platforms vary in size. To provide a better preview experience, the platforms need to resize the images.
Image recognition and analysis: In computer vision and machine learning, you need to resize images for higher processing efficiency.
Limits
Limit | Item | Description |
Source images | Image format | Only the JPG, PNG, BMP, GIF, WebP, TIFF, and HEIC formats are supported. |
Image size | The size of a source image cannot exceed 20 MB. You can apply to change the limit on the size of source images in the Quota Center. To apply to change the limit, perform the following steps: Go to the Object Storage Service (OSS) console. In the left-side navigation pane, . | |
Image width and height | 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. Note The total pixel number of a dynamic image, such as a GIF image, is calculated based on the following formula: | |
Resized images | Image resizing | The width or height of a resized image cannot exceed 16,384 pixels. The total pixel number of a resized image cannot exceed 16,777,216. |
Billing
When you use the image resizing feature, you are charged for the following billable items:
API operation calling fees: The image resizing feature of OSS is implemented by calling the GetObject operation. You are charged API operation calling fees based on the number of GET requests. For more information, see API operation calling fees.
Traffic fees: You are charged for the outbound traffic over the Internet based on the size of the processed images. For more information, see Traffic fees.
If the storage class of the source images is not Standard, you are also charged image processing fees based on the size of the source images. For more information, see Data processing fees.
Operation methods
In OSS, if an image URL contains the ?x-oss-process=image/resize,parame_value
parameter, OSS processes the image in real time and returns the processed image. In the parameter, image/resize
specifies image resizing, parame
specifies the parameter to be resized, and value
specifies the value of the parameter to be resized. For more information about resizing parameters, see Parameter description. You can use multiple parameters in combination.
If the access control list (ACL) of your image is public-read, you can add image resizing parameters to the URL of the image to allow anonymous users to access the processed image. If the ACL of your image is a private image, you must include a signature in the request to process the image by using an OSS SDK or calling an API operation.
Public-read images
The following table describes how to add the ?x-oss-process=image/resize,parame_value
parameter to the end of the URL of a public-read image. You need to only replace parame_value
with the actual parameters and values.
URL of the source image | URL used to process the source image |
https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg |
Private images
Use OSS SDKs
You can use an OSS SDK to generate a signed URL that contains image resizing parameters to allow the users who obtain the signed URL to temporarily access the processed image. The following sample code provides examples on how to use an OSS SDK to generate a signed URL that contains 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 {
// 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";
// 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 image that you want to process. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/exampleobject.jpg.
String objectName = "exampledir/exampleobject.png";
// 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 cn-hangzhou.
String region = "cn-hangzhou";
// 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 {
// Specify the image resizing parameters. Replace parame_value with the actual parameter values. For example, if you replace parame_value with p_50, the image is proportionally scaled down to 50% of the original size.
String style = "image/resize,parame_value";
// Set the validity period of the signed URL to 3600 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 name of the bucket.
bucket = 'examplebucket'
# Specify the endpoint of the region in which the bucket is located. In this example, the endpoint of the China (Hangzhou) region is used.
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, bucket, region=region)
# Specify the name of the image that you want to process. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/exampleobject.jpg.
key = 'exampledir/exampleobject.png'
# Specify the expiration time. Unit: seconds.
expire_time = 3600
# Specify the image resizing parameters. Replace parame_value with the actual parameter values. For example, if you replace parame_value with p_50, the image is proportionally scaled down to 50% of the original size.
image_process = 'image/resize,parame_value'
# Generate a signed URL that includes Image Processing (IMG) 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();
// 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";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
// Generate a signed URL that includes IMG parameters. The validity period of the URL is 3,600 seconds. The signed URL can be directly used to access the image by using a browser.
$timeout = 3600;
$options = array(
// Specify the image resizing parameters. Replace parame_value with the actual parameter values. For example, if you replace parame_value with p_50, the image is proportionally scaled down to 50% of the 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.
// 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.
// Specify the region of the bucket. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify your actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify 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 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 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/exampleobject.jpg.
ossImageName := "exampledir/exampleobject.png"
// Generate a signed URL that includes IMG parameters. Set the validity period of the URL to 3,600 seconds. The maximum validity period of a signed URL is 32,400 seconds.
// Specify the image resizing parameters. Replace parame_value with the actual parameter values. For example, if you replace parame_value with p_50, the image is proportionally scaled down to 50% of the 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 sample code provides an example on how to generate a 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=6fd07a2ba50bf6891474dc56aed976b556b6fbcd901cfd01bcde5399bf4802cb
For information about how to resize an image by using OSS SDKs for other programming languages, see Overview.
Use the OSS API
If your business requires a high level of customization, you can directly call the OSS API. To directly call an API operation, you must include the signature calculation in your code. For information about how to calculate the Authorization header, see (Recommended) Include a V4 signature in the Authorization header.
You can add image resizing parameters to the GetObject operation to resize an image. 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
Parameter description
Action: resize
Proportional scaling
You can use the p
parameter to specify proportional scaling for an image.
Parameter | Description | Value |
p | Specifies the percentage by which you want to resize the image. | 1 to 1000. A value smaller than 100 specifies that the image is scaled down. A value greater than 100 specifies that the image is scaled up. |
Resize an image based on the specified width and height
You can use the w
and h
parameters to specify the width and height to which you want to resize an image and use the m
parameter to specify the type of the resize action. This allows you to satisfy different layout requirements. If you want to limit the length of the longer side or shorter side of a resized image, use the l
or s
parameter. If you want to scale up an image, you must add the limit_0
parameter.
Parameter | Description | Value |
w | Specifies the width to which you want to resize the image. | 1 to 16384. |
h | Specifies the height to which you want to resize the image. | 1 to 16384. |
m | Specifies the type of the resize action. |
For information about the descriptions of resized images, see Methods to calculate the sizes of resized images. Note If you specify a value for the |
l | Specifies the length of the longer side to which you want to resize the image. Note The longer side refers to the side with a larger ratio between the original size and the target size. For example, if a source image is resized from 100 × 200 pixels to 100 × 100 pixels, the original-to-target ratios are 2 (200/100) and 1 (100/100). Given that 2 is larger than 1, the side that was originally 200 pixels is the longer side and the side that was originally 100 pixels is the shorter side. | 1 to 16384. |
s | Specifies the length of the shorter side to which you want to resize the image. | 1 to 16384. |
limit | Specifies whether to resize the image when the resolution of the target image is higher than the resolution of the source image. Important If the size of the resized image is larger than the size of the source image, the source image is returned. If you want to scale up an image, add the |
Note The size of a GIF image can only be scaled down based on the specified width and height. |
color | 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. |
If you specify only the width or height of the resized image, take note of the following items:
If you set the resizing type to lfit, mfit, or fixed, OSS proportionally resizes the source image. For example, if you resize the height of a source image of 256 × 144 pixels to 100 pixels, the width of the source image is resized to 178 pixels.
If you set the resizing type to pad or fill, OSS resizes the source image based on the specified value. For example, if you resize the height of a source image of 256 × 144 pixels to 100 pixels, the width of the source image is also resized to 100 pixels.
If you specify only one of the
l
ands
parameters, OSS resizes the specified side of the source image based on the specified value and automatically adjusts the other side based the original aspect ratio. In this case, the setting of them
parameter does not take effect.If you specify the
l
ands
parameters at the same time, OSS maintains the original aspect ratio while resizing the source image. In this case, the setting of them
parameter takes effect. If you do not specify the resizing type,lfit
is used by default.
Methods to calculate the sizes of resized images
Size of the source image | Specified image resizing parameter | Resizing type | Size of the resized image |
200 × 100 pixels | 150 × 80 pixels | lfit (default) OSS resizes the source image proportionally to the largest possible size in a rectangle based on the specified width and height. | 150 × 75 pixels |
mfit OSS proportionally resizes the source image to the smallest possible size that extends beyond a rectangle of the specified width and height. | 160 × 80 pixels | ||
fill OSS proportionally resizes the source image to the smallest possible size that extends beyond a rectangle of the specified width and length and then crops the image from the center to the specified width and height. | 150 × 80 pixels | ||
pad OSS proportionally resizes the source image to the largest possible size that fits in a rectangle with the specified width and length and then fills the empty space in the rectangle based on the specified width and height to produce a final image that has the required size. | 150 × 80 pixels | ||
fixed OSS forcibly resizes the source image based on the specified width and height. If the aspect ratio of the resized image is different from that of the source image, the image is distorted. | 150 × 80 pixels |
If you set the m parameter to lfit or mfit, the aspect ratio of the source image is rounded to an integer if the ratio is a decimal.