You can convert the format of a source image in Object Storage Service (OSS) by appending format conversion parameters to its URL. This eliminates the need to download the image for conversion. This topic describes the parameters and provides examples for image format conversion.
Use cases
-
Adapt to different devices and platforms: Different devices and platforms support different image formats. OSS format conversion ensures compatibility and optimal display on various terminals.
-
Reduce storage costs: Certain image formats, such as WebP, have smaller file sizes while maintaining visual quality. Converting to these formats reduces storage space usage and lowers storage costs.
-
Standardize resource management: In industries like e-commerce, social media, and digital media, convert all uploaded images to a standard format to simplify management and distribution.
Usage notes
-
When an image processing operation includes resizing, place the format conversion parameter at the end of the processing parameters. For example,
image/resize,w_100/format,jpg. -
When image processing includes both resizing and watermarking, the format conversion parameter must be added after the resizing parameter. For example,
image/resize,w_100/format,jpg/watermark,.... -
When converting an image without an alpha channel to a format that supports transparency, such as PNG, WebP, or BMP, any resulting transparent areas are filled with white by default. OSS does not support filling transparent areas with black.
-
When converting an image to the WebP format, the width and height of the source image cannot exceed 16,383 px. If either dimension exceeds this limit, the conversion fails.
Image processing methods
Object URLs are suitable only for public-read images; for private images, you must use an SDK or the REST API. For more information, see Image processing methods.
Public images
For public-read images, you can append processing parameters directly to the image URL for permanent, anonymous access to the processed image.
The following describes how to add the ?x-oss-process=image/format,parame_value parameter to a public-read image URL. You only need to replace parame_value with specific parameters and values based on your business requirements. You can also combine multiple parameters.
|
Source URL |
Processed URL |
|
https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example.gif |
Private images
Use Alibaba Cloud SDKs or the REST API to convert the format of private images.
SDKs
The following sections provide code examples for image format conversion by using common SDKs. For code examples for other SDKs, see SDK overview.
Java
Java SDK 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 {
// The endpoint of the China (Hangzhou) region is used as an example. Specify the endpoint of the region where your bucket is located.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region ID. 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 bucket name. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the source object. The full path cannot contain the bucket name.
String objectName = "src.gif";
// Specify the full local path to which to save the processed image. Example: D:\\dest.png. If the specified local file exists, it is overwritten. If the file does not exist, it is created.
String pathName = "D:\\dest.png";
// Create an OSSClient instance.
// When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Convert the source image to the PNG format.
String image = "image/format,png";
GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
request.setProcess(image);
// Download the processed image and save it to the specified local path.
// If you specify only a filename without a full path, such as dest.png, the file is saved to the project's root directory.
ossClient.getObject(request, new File("D:\\dest.png"));
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request reached OSS, "
+ "but was rejected with an error.");
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 a 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
PHP SDK 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();
// The endpoint of the China (Hangzhou) region is used as an example. Specify the endpoint of the region where your bucket is located.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the bucket name. Example: examplebucket.
$bucket= "examplebucket";
// Specify the full path of the source object. The full path cannot contain the bucket name.
$object = "src.gif";
// Specify the full local path to which to save the processed image. Example: D:\\dest.png. If the specified local file exists, it is overwritten. If the file does not exist, it is created.
// If you specify only a filename without a full path, such as dest.png, the file is saved to the project's root directory.
$download_file = "D:\\dest.png";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
// Specify the region ID. Example: cn-hangzhou.
"region" => "cn-hangzhou"
);
$ossClient = new OssClient($config);
// Convert the source image to the PNG format.
$image = "image/format,png";
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => $image);
// Download the processed image and save it to the specified local path.
$ossClient->getObject($bucket, $object, $options);
Python
Python SDK 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())
# The endpoint of the China (Hangzhou) region is used as an example. Specify the endpoint of the region where your bucket is located.
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# Specify the region ID. Example: cn-hangzhou.
region = 'cn-hangzhou'
# Specify the bucket name.
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)
# Specify the full path of the source object. If the object is not in the root directory of the bucket, you must specify the full path, for example, exampledir/src.gif.
key = 'src.gif'
# Specify the full local path to which to save the processed image.
new_pic = 'D:\\dest.png'
# Convert the source image to the PNG format.
image = 'image/format,png'
# Download the processed image and save it to the specified local path.
bucket.get_object_to_file(key, new_pic, process=image)
Go
Go SDK 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.
// The endpoint of the China (Hangzhou) region is used as an example. Specify the endpoint of the region where your bucket is located.
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 bucket name. Example: examplebucket.
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
HandleError(err)
}
// Specify the full path of the source object. If the object is not in the root directory of the bucket, you must specify the full path, for example, exampledir/src.gif.
sourceImageName := "src.gif"
// Specify the full local path to which to save the processed image.
targetImageName := "D://dest.png"
// Convert the source image to the PNG format.
image := "image/format,png"
// Download the processed image and save it to the specified local path.
err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(image))
if err != nil {
HandleError(err)
}
}
REST API
If your application has highly custom requirements, you can call the REST API directly. This requires manually calculating the signature. For information about how to calculate the Authorization header, see Signature Version 4 (Recommended).
You can process images by adding format conversion parameters to the GetObject operation. For more information, see GetObject.
GET /oss.jpg?x-oss-process=image/format,png HTTP/1.1
Host: oss-example.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: <AuthorizationValue>
Parameters
Action: format
|
Value |
Description |
|
|
Converts the source image to the JPG format. Important
Converting a HEIC image that has an alpha channel to the JPG format is not supported. |
|
|
Converts the source image to the PNG format. |
|
|
Converts the source image to the WebP format. Note
The width and height of the source image cannot exceed 16,383 px. |
|
|
Converts the source image to the BMP format. |
|
|
If the source image is a GIF, it remains a GIF. If the source image is not a GIF, its original format is retained. |
|
|
Converts the source image to the TIFF format. |
|
|
Converts the source image to the HEIF format. Note
Supported only in: China (Zhangjiakou), China (Shanghai), China (Shenzhen), China (Hangzhou), China (Beijing), and Singapore. |
|
|
Converts the source image to the AVIF format. Note
Supported only in: China (Zhangjiakou), China (Shanghai), China (Shenzhen), China (Hangzhou), China (Beijing), and Singapore. |
Examples
FAQ
Image quality control
Each image format has a default quality setting. If you do not specify a quality parameter during format conversion, OSS applies the default quality.
To improve image quality, specify a quality of 100 when you convert the format, for example, ?x-oss-process=image/quality,Q_100. For more information about quality conversion, see Quality conversion.
Does format conversion affect page load speed?
OSS performs format conversion dynamically on request, which may cause a slight delay on first access. However, the converted image is typically smaller and in a more efficient format, such as converting a PNG to a WebP. As a result, subsequent loads are faster, improving overall page performance.
Can I convert GIF to MP4?
To convert a GIF to the MP4 format, submit a ticket to request this feature.



