You can specify format parameters in the image URL to convert the format of an image that is stored in Object Storage Service (OSS) without downloading the image. This topic describes the format parameters and provides examples on how to convert the format of an image.
Scenarios
Adaptive to different devices and platforms: Different browsers, operating systems, or mobile devices may support different image formats. For example, the WebP format provides better compression efficiency on browsers. By using OSS image format conversion, you can convert uploaded images into multiple formats to ensure compatibility and optimal display effects on various devices.
Reduced storage costs: In most cases, specific image formats, such as WebP, provide smaller sizes than other traditional formats while maintaining visual quality. You can convert image formats to reduce storage usage without compromising image quality. This way, storage costs are reduced.
Centralized resource management: In e-commerce, social networking, media, and other industries, images uploaded by a large number of users need to be standardized. You can convert uploaded images to a specific format for subsequent management and distribution.
Usage notes
If an image processing (IMG) request includes format and resize parameters, we recommend that you place the format parameters at the end.
Example: image/resize,w_100/format,jpg
If an IMG request includes format, resize, and watermark parameters, we recommend that you place the format parameters after the resize parameters.
Example:
image/resize,w_100/format,jpg/watermark,...
If the source image does not support alpha channels, the format of the source image is converted to a format that supports alpha channels. Formats that support alpha channels include PNG, WebP, and BMP. By default, OSS fills the transparent area with white.
You cannot use OSS to fill the transparent area with black.
Parameters
Action: format
The following table describes the parameters that you can configure when you convert the format of a source image.
Valid value | Description |
jpg | Converts the format of the source image to JPG. Important Images in the HEIC format that support alpha channels cannot be converted to JPG images. |
png | Converts the format of the source image to PNG. |
webp | Converts the format of the source image to WebP. |
bmp | Converts the format of the source image to BMP. |
gif | Converts the format of the source image to GIF. The conversion takes effect only when the source image is also a GIF image. If the source image is not a GIF image, the processed image is stored in the original format. |
tiff | Converts the format of the source image to TIFF. |
Methods
Convert the format of a public-read or public-read-write image
You can add IMG parameters to the URL of an image to convert the format of a public-read or public-read-write image.
In the following examples, an image named example.gif in the image-demo bucket in the China (Hangzhou) region is used as the source image. The image is hosted at the following URL:
Convert the format of the source image to PNG
The URL used to process the source image is https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example.gif?x-oss-process=image/format,png.
Convert the format of the source image to JPG that supports gradual display
Configure the following parameters:
Apply gradual display:
interlace,1
Convert the format of the source image to JPG:
format,jpg
The URL used to process the source image is https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example.gif?x-oss-process=image/interlace,1/format,jpg.
Resize the image to a width of 200 pixels and convert the format of the image to WebP
Configure the following parameters:
Resize the image to a width of 200 pixels: resize,w_200
Convert the format of the image to WebP: format,webp
The URL used to process the source image is https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example.gif?x-oss-process=image/resize,w_200/format,webp.
Convert the format of a private image
You can use OSS SDKs and OSS API to convert the format of private images.
Use OSS SDKs
The following sample code provides examples on how to convert the format of a private image by using OSS SDKs for common programming languages. For more information about how to convert the format of a private image by using other programming languages, see Overview.
Java
OSS SDK for Java 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 {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region of the endpoint. 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 name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object that you want to process. Do not include the bucket name in the full path.
String objectName = "src.gif";
// Specify the full path of the processed image. Example: D:\\dest.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path.
String pathName = "D:\\dest.png";
// 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 {
// Convert the format of the source image to PNG.
String image = "image/format,png";
GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
request.setProcess(image);
// Set the name of the processed image to dest.png and save it to your local computer.
// If you specify only the name of the processed image such as dest.png without specifying the local path of the processed image, the processed image is saved to the path of the project to which the sample program belongs.
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
OSS SDK for PHP 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();
// 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 = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the bucket. Example: examplebucket.
$bucket= "examplebucket";
// Specify the full path of the object that you want to process. Do not include the bucket name in the full path.
$object = "src.gif";
// Specify the full path of the processed image. Example: D:\\dest.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path.
// If you specify only the name of the processed image such as dest.png without specifying the local path of the processed image, the processed image is saved to the path of the project to which the sample program belongs.
$download_file = "D:\\dest.png";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
// Specify the ID of the Alibaba Cloud region in which the bucket is located.
"region" => "cn-hangzhou"
);
$ossClient = new OssClient($config);
// Convert the format of the source image to PNG.
$image = "image/format,png";
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => $image);
// Save the processed image to your local computer.
$ossClient->getObject($bucket, $object, $options);
Python
OSS SDK for Python 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())
# 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 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 = '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, 'examplebucket', region=region)
# Specify the name of the source image. If the image is not stored in the root directory of the bucket, you must include the full path of the image. Example: exampledir/src.gif.
key = 'src.gif'
# Specify the name of the processed image.
new_pic = 'D:\\dest.png'
# Convert the format of the source image to PNG.
image = 'image/format,png'
bucket.get_object_to_file(key, new_pic, process=image)
Go
OSS SDK for Go 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.
// 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.
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 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 source image. If the image is not stored in the root directory of the bucket, you must include the full path of the image. Example: exampledir/src.gif.
sourceImageName := "src.gif"
// Specify the name of the processed image.
targetImageName := "D://dest.png"
// Convert the format of the source image to PNG.
image := "image/format,png"
err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(image))
if err != nil {
HandleError(err)
}
}
Use the OSS API
If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see GetObject.
You can specify format parameters when you call the GetObject operation to process an image.
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: OSS qn6q**************:77Dv****************
FAQ
What do I do if black borders appear when the image format is converted?
The image format has a default quality. If no quality is specified during format conversion, the image format is converted based on the default quality. In this case, black borders may appear in the image.
If you want to improve the image quality, we recommend that you set the image quality parameter to 100 (?x-oss-process=image/quality,Q_100). For more information about image quality adjustment, see Adjust image quality.
Does the image format conversion affect the page loading speed?
The image format conversion affects the page loading speed.
Can I convert the format of a GIF image to MP4?
Yes, you can convert the format of a GIF image to MP4. To convert the format of a GIF image into MP4, you need to submit a ticket.