Converta o formato das imagens armazenadas no Object Storage Service (OSS) em tempo real adicionando parâmetros à URL da imagem. Isso elimina a necessidade de processamento offline. Este tópico descreve os parâmetros e fornece exemplos de conversão de formato de imagem.
Casos de uso
Adaptação a dispositivos e plataformas: converta imagens para diferentes formatos para garantir compatibilidade e exibição ideal em diversos dispositivos.
Redução de custos de armazenamento: alguns formatos, como WebP, possuem tamanhos de arquivo menores sem perda de qualidade visual. Converta imagens para esses formatos para reduzir o uso e os custos de armazenamento.
Padronização de formatos de ativos: converta todas as imagens carregadas para um único formato padrão (como WebP). Essa prática simplifica o gerenciamento de ativos e os pipelines de entrega, sendo comum em aplicações de e-commerce, redes sociais e notícias.
Observações de uso
Se uma solicitação de processamento de imagem incluir redimensionamento, coloque o parâmetro de conversão de formato ao final dos parâmetros de processamento. Exemplo:
image/resize,w_100/format,jpg.Caso a solicitação inclua redimensionamento e marca d'água, adicione o parâmetro de conversão de formato após o parâmetro de redimensionamento. Exemplo:
image/resize,w_100/format,jpg/watermark,....Ao converter uma imagem sem canal alfa para um formato que o suporte (como PNG ou WebP), as áreas transparentes resultantes serão preenchidas com branco por padrão. O OSS não oferece suporte ao preenchimento da área transparente com preto.
Métodos
Processe imagens por meio de parâmetros de URL, SDKs ou APIs REST. O processamento via URL está disponível apenas para imagens acessíveis publicamente. Para imagens privadas, use um SDK ou chame a API diretamente. Para mais informações, consulte Métodos de processamento de imagem.
Public-read images
Para imagens de leitura pública, adicione parâmetros de processamento diretamente à URL da imagem. Em seguida, acesse a imagem processada usando a URL gerada.
Para processar uma imagem de leitura pública, adicione o parâmetro ?x-oss-process=image/format,parameter_value à URL da imagem. Substitua parameter_value pelos parâmetros e valores necessários. Também é possível combinar vários parâmetros.
|
URL da imagem original |
URL da imagem com parâmetros de processamento |
|
https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example.gif |
Private images
Converta o formato de imagens privadas usando SDKs da Alibaba Cloud ou APIs REST.
Use Alibaba Cloud SDKs
As seções a seguir apresentam amostras de código para converter formatos de imagem com SDKs comuns. Para amostras com outros SDKs, consulte Visão geral do SDK.
Java
É necessário o Java SDK 3.17.4 ou posterior.
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
É necessário o PHP SDK 2.7.0 ou posterior.
<?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
É necessário o Python SDK 2.18.4 ou posterior.
# -*- 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
É necessário o Go SDK 3.0.2 ou posterior.
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
Se o seu negócio exigir alto nível de personalização, chame as APIs RESTful diretamente. Para isso, inclua o cálculo da assinatura no código. Para mais informações sobre como calcular o cabeçalho Authorization, consulte Versão de Assinatura 4 (Recomendado).
Especifique parâmetros de formato na chamada GetObject para processar uma imagem. Para mais informações, consulte 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
Parâmetros
Ação: format
|
Valor |
Descrição |
|
jpg |
Salva a imagem original no formato JPG. Importante
Não é possível salvar uma imagem no formato HEIC com canal alfa para o formato JPG. |
|
png |
Salva a imagem original no formato PNG. |
|
webp |
Salva a imagem original no formato WebP. |
|
bmp |
Salva a imagem original no formato BMP. |
|
gif |
Se a imagem original estiver no formato GIF, ela será salva nesse formato. Caso contrário, será salva em seu formato original. |
|
tiff |
Salva a imagem original no formato TIFF. |
|
heic |
Salva a imagem original no formato HEIF. Nota
O formato HEIF tem suporte apenas nas regiões China (Zhangjiakou), China (Shanghai), China (Shenzhen), China (Hangzhou), China (Beijing) e Singapura. |
|
avif |
Salva a imagem original no formato AVIF. Nota
O formato AVIF tem suporte apenas nas regiões China (Zhangjiakou), China (Shanghai), China (Shenzhen), China (Hangzhou), China (Beijing) e Singapura. |
Exemplos
Converter uma imagem original para o formato PNG
Converter uma imagem original para o formato JPG e ativar exibição gradual
Converter uma imagem original para o formato WebP e redimensioná-la
Perguntas frequentes
Como controlar a qualidade da imagem convertida?
Cada formato de imagem possui uma configuração de qualidade padrão. Se você não especificar o parâmetro de qualidade durante a conversão, o OSS aplicará esse padrão.
Para melhorar a qualidade da imagem, defina a qualidade como 100 durante a conversão de formato. Por exemplo, use ?x-oss-process=image/quality,Q_100. Para mais informações sobre conversão de qualidade, consulte Conversão de qualidade.
A conversão de formato de imagem afeta a velocidade de carregamento da página?
A conversão de formato de imagem ocorre em tempo real. Embora a primeira solicitação possa apresentar leve atraso de processamento, o formato resultante, menor e mais eficiente (como WebP), geralmente acelera os carregamentos subsequentes e melhora o desempenho geral da página.
É possível converter uma imagem GIF para o formato MP4?
Para converter uma imagem GIF para o formato MP4, envie um ticket para solicitar este recurso.



