You can convert the format of images stored in Object Storage Service (OSS) on-the-fly by simply adding parameters to the image URL, eliminating the need for offline processing. This topic describes the parameters and provides examples for image format conversion.
Use cases
Device and platform adaptation: Convert images to different formats to ensure compatibility and optimal display across various devices.
Save storage costs: Some image formats, such as WebP, have smaller file sizes while maintaining visual quality. Convert images to these formats to reduce storage usage and lower storage costs.
Standardize asset formats: Convert all uploaded images to a single, standard format (such as WebP) to simplify asset management and delivery pipelines, which is common in e-commerce, social media, and news applications.
Usage notes
If an image processing request includes a scaling operation, place the format conversion parameter at the end of the processing parameters. For example,
image/resize,w_100/format,jpg.If an image processing request includes both scaling and watermark operations, add the format conversion parameter after the scaling parameter. For example,
image/resize,w_100/format,jpg/watermark,....When converting an image without an alpha channel to a format that supports one (such as PNG or WebP), any resulting transparent areas will be filled with white by default. Note that OSS does not support filling the transparent area with black.
Methods
Perform image processing via URL parameters, SDKs, or REST APIs. URL-based processing is only available for publicly accessible images; for private images, you must use an SDK or call the API directly. For more information, see Image processing methods.
Public-read images
For public-read images, add processing parameters directly to the image URL. The processed image can then be accessed using the generated URL.
To process a public-read image, add the ?x-oss-process=image/format,parameter_value parameter to the image URL. Replace parameter_value with the required parameters and values. You can also combine multiple parameters.
Source image URL | Image URL with processing parameters |
https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example.gif |
Private images
Convert the format of private images using Alibaba Cloud SDKs or REST APIs.
Use Alibaba Cloud SDKs
The following sections provide code samples that show how to convert image formats with common SDKs. For code samples that use 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 actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region that corresponds to the endpoint, for example, cn-hangzhou.
String region = "cn-hangzhou";
// Obtain access credentials from environment variables. Before you run this 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. The full path cannot contain the bucket name.
String objectName = "src.gif";
// Specify the full path of the local file, for example, D:\\dest.jpg. 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 used, call the shutdown method to release the 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);
// Name the processed image dest.png and save it to a local path.
// If you specify only the file name, such as dest.png, without a local path, the file is saved to the project's corresponding local path by default.
ossClient.getObject(request, new File("D:\\dest.png"));
} 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
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 this 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. The endpoint of the China (Hangzhou) region is used as an example: https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the bucket name, for example, examplebucket.
$bucket= "examplebucket";
// Specify the full path of the object. The full path cannot contain the bucket name.
$object = "src.gif";
// Specify the full path of the local file, for 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 the file name, such as dest.png, without a local path, the file is saved to the project's corresponding local path by default.
$download_file = "D:\\dest.png";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
// Specify the general-purpose region ID of Alibaba Cloud.
"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);
// Save the processed image to a 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 this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set the endpoint to your bucket's endpoint. The endpoint of the China (Hangzhou) region is used as an example: https://oss-cn-hangzhou.aliyuncs.com.
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# Specify the general-purpose region ID of Alibaba Cloud.
region = 'cn-hangzhou'
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)
# Specify the name of the source image. If the image 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 name of the processed image.
new_pic = 'D:\\dest.png'
# Convert the source image to the PNG format.
image = 'image/format,png'
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 this 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. The endpoint of the China (Hangzhou) region is used as an example: https://oss-cn-hangzhou.aliyuncs.com. Specify the endpoint based on your region.
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 where the source image is stored, for 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 in the root directory of the bucket, you must specify the full path, for example, exampledir/src.gif.
sourceImageName := "src.gif"
// Specify the name of the processed image.
targetImageName := "D://dest.png"
// Convert the source image to the PNG format.
image := "image/format,png"
err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(image))
if err != nil {
HandleError(err)
}
}Use a REST API
If your business requires a high level of customization, call RESTful APIs directly. To call an API directly, you must include the signature calculation in your code. For more information about how to calculate the Authorization header, see Signature Version 4 (Recommended).
Specify format parameters in the GetObject call to process an image. 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: AuthorizationValueParameters
Action: format
Value | Description |
jpg | Saves the source image in the JPG format. Important You cannot save an image in the HEIC format that has an alpha channel to the JPG format. |
png | Saves the source image in the PNG format. |
webp | Saves the source image in the WebP format. |
bmp | Saves the source image in the BMP format. |
gif | If the source image is in the GIF format, it is saved in the GIF format. If the source image is not in the GIF format, it is saved in its original format. |
tiff | Saves the source image in the TIFF format. |
heic | Saves the source image in the HEIF format. Note The HEIF format is supported only in the China (Zhangjiakou), China (Shanghai), China (Shenzhen), China (Hangzhou), China (Beijing), and Singapore regions. |
avif | Saves the source image in the AVIF format. Note The AVIF format is supported only in the China (Zhangjiakou), China (Shanghai), China (Shenzhen), China (Hangzhou), China (Beijing), and Singapore regions. |
Examples
FAQ
How can I control the quality of the converted image?
Each image format has a default quality setting. If you do not specify the quality parameter during format conversion, OSS will apply this default.
If you want to improve the image quality, set the quality to 100 during format conversion, for example, using ?x-oss-process=image/quality,Q_100. For more information about quality conversion, see Quality conversion.
Does the image format conversion process affect page loading speed?
Image format conversion is performed on-the-fly. While the first request may experience a slight processing delay, the resulting smaller and more efficient image format (such as WebP) typically leads to faster subsequent load times and improved overall page performance.
Can I convert a GIF image to the MP4 format?
To convert a GIF image to the MP4 format, submit a ticket to request this feature.



