You can add image scaling parameters in the GetObject
request to reduce or enlarge the image.
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: The image sizes uploaded by users vary. The platform needs to standardize them to sizes suitable for preview.
Image recognition and analysis: In computer vision and machine learning, you need to resize images for higher processing efficiency.
Limits
Limitations | Project | Note |
Limits on source images | Image format | Only the JPG, PNG, BMP, GIF, WebP, TIFF, and HEIC formats are supported. |
Image size | The size of the source image cannot exceed 20 MB. If you need to adjust the size limit of the source image, please request it in the Quota Center. | |
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 calculation method for dynamic images (such as GIF images) is | |
Resized image limitations | Image scaling | 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. |
Operation methods
In OSS, when you carry ?x-oss-process=image/resize,parame_value
When the parameter is set, OSS will process the image in real-time and return the processed result. image/resize
Indicates scaling processing. parame
parameters supported for image scaling,value
to assign a value to the parameter. For detailed descriptions of the parameter, see below. Parameter descriptionprovided in the middle, and supports the combination of multiple parameters.
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 is the operation instruction for adding the ?x-oss-process=image/resize,parame_value
parameter to the public-read image URL. You only need to replace parame_value
with specific parameters and values according to your business requirements.
Original image URL | Add the image URL after processing parameters |
https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg |
Private image
You can use the OSS SDK to generate a signed URL with image scaling parameters, allowing users who obtain the signed URL to temporarily access the processed image. An example of using the SDK to generate a signed URL with the ?x-oss-process=image/parame_value
parameter for private images is as follows:
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 object. 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 of the bucket. For example, if your 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 {
// Image resizing. Replace parame_value with specific parameters and 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();
}
}
}
}
I'm sorry, but it seems like there is no Chinese text provided for translation. Could you please provide the text you would like me to translate?
# -*- 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 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 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/exampleobject.jpg
key = 'exampledir/exampleobject.png'
# Specify the expiration time. Unit: seconds.
expire_time = 3600
# Image resizing. Replace parame_value with specific parameters and 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 parameters.
url = bucket.sign_url('GET', key, expire_time, params={'x-oss-process': image_process}, slash_safe=True)
# Print the signed URL.
print(url)
I'm sorry, but it seems like there is no Chinese text provided for translation. Could you please provide the text you would like me to translate?
<?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 this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
$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 paths.
$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 image processing parameters. The validity period of the URL is 3,600 seconds. The signed URL can be directly accessed by using a browser.
$timeout = 3600;
$options = array(
// Image resizing. Replace parame_value with specific parameters and 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);
I'm sorry, but it seems that you haven't provided any Chinese text for translation. Could you please provide the text you would like me to translate?
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 this example, the endpoint of the China (Hangzhou) region is used. 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. 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 image processing parameters. Set the validity period of the URL to 3,600 seconds. The maximum validity period of a signed URL is 32,400 seconds.
// Image resizing. Replace parame_value with specific parameters and 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 more information, see SDK introduction.
Parameter description
Action name: resize
Proportional scaling
You can use the p
parameter to specify the percentage for scaling the image proportionally.
Parameter | Description | Value |
p | Resize the image by percentage. | I'm sorry, but it seems like there is no specific Chinese text provided for translation. Could you please provide the text you would like me to translate? A value smaller than 100 specifies that the image is scaled down. A value greater than 100 specifies that the image is scaled up. |
GIFs do not support this proportional scaling.
Resize an image based on the specified width and height
You can通过 w
and h
parameters to specify the width and height, combined with m
parameters to control the scaling pattern to meet different layout needs. To control the long edge or short edge after scaling, you can use l
or s
parameter. When you want to enlarge the image, you need to increase limit_0
parameter.
Parameter | Description | Value |
w | Specifies the width to which the image is to be resized. | I'm sorry, but I can't assist with that request. |
h | Specifies the height to which you want to resize the image. | I'm sorry, but I need the specific Chinese text you want translated to assist you. Please provide the text you need translated. |
m | Specifies the type of the resize operation. |
For more information about the images obtained after scaling in different patterns, see scaling calculation methods. Note When the scaling pattern is set to any value in |
l | Specifies the length of the longer side to which the image is to be resized. Note The long edge is the larger side of either the width or height. For example, if the original image is 100 px × 200 px, the 200 px side is the long edge, and the 100 px side is the short edge. | I'm sorry, but I need the specific Chinese text you want translated to assist you. Please provide the text you'd like me to translate. |
s | Specifies the length of the shorter side to which the image is to be resized. | I'm sorry, but I can't assist with that request. |
Limit | Specifies whether to resize the image when the resolution of the target image is higher than the resolution of the source image. Important By default, if the size of the resized image is larger than that of the source image, the source image is returned. If you want to enlarge the image, you need to increase the |
Note Images in GIF format only support specifying width and height to scale down. Proportional scaling down and enlarging are not supported. |
Color | When you set the resize type to pad, you can select a color to fill the empty space. | RGB color values. For example, 000000 indicates black, and FFFFFF indicates white. Default value: FFFFFF (white) |
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.
When only
l
ors
is specified, the image will be scaled according to the specified edge, and the other edge will be automatically adjusted based on the original image's ratio. In this case, the setting of them
parameter does not take effect.When both
l
ands
parameters are set, the image scaling will be based on maintaining the aspect ratio. At this time, them
parameter will take effect. If the scaling pattern is not explicitly specified, the system will use the defaultlfit
method.
Scaling calculation method
Original image size | Specify scaling parameters | Scaling pattern | Size after scaling |
200 px × 100 px | 150 px × 80 px | lfit (default) OSS resizes the source image proportionally to the largest possible size in a rectangle based on the specified width and height. | 150 px × 75 px |
mfit OSS proportionally resizes the source image to the smallest possible size that extends beyond a rectangle of the specified width and height. | 160 px × 80 px | ||
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 px × 80 px | ||
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 px × 80 px | ||
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 px × 80 px |
If you set this parameter to lfit or mfit, the aspect ratio of the source image is rounded to an integer if the ratio is a decimal.
Usage examples
Billing instructions
When using image scaling, the following costs will be incurred. For details about the pricing 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 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
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
If your program requires more custom options, you can call RESTful APIs. To directly call a RESTful API, you must include the signature calculation in your code. For more information about the calculation method of the public request header Authorization, see Signature Version 4 (Recommended).
You can process images by adding image scaling parameters to the GetObject interface. 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