Todos os produtos
Search
Central de documentação

Object Storage Service:Ajuste de qualidade

Última atualização: Sep 09, 2026

O ajuste de qualidade comprime imagens mantendo o formato original. Use os parâmetros de ajuste de qualidade para controlar a qualidade das imagens armazenadas no OSS.

Importante

O ajuste de qualidade não afeta formatos sem perdas, como PNG.

O formato PNG usa compressão sem perdas. Quando resize e quality são usados em conjunto, o redimensionamento pode aumentar a complexidade da imagem e o custo de compressão, resultando possivelmente em um arquivo maior. O parâmetro quality não se aplica a imagens PNG e é ignorado.

Para reduzir o tamanho de uma imagem PNG, use primeiro o parâmetro format para convertê-la para JPG ou WebP e, em seguida, aplique o parâmetro quality. Exemplo:

image/format,jpg/quality,Q_30

Ou:

image/format,webp/quality,Q_30

Parâmetros

Ação: quality

A tabela a seguir descreve os parâmetros.

Parâmetro

Descrição

Valores válidos

q

Define a qualidade relativa. Comprime a imagem source por porcentagem.

Por exemplo, se a qualidade da imagem source for 100%, adicionar o parâmetro quality,q_90 gera uma imagem com 90% de qualidade. Se a qualidade da imagem source for 80%, adicionar o parâmetro quality,q_90 gera uma imagem com 72% de qualidade.

Nota

O parâmetro q aplica-se apenas a JPG. Para WebP, ele se comporta como o parâmetro Q e define a qualidade absoluta.

[1,100]

Q

Define a qualidade absoluta.

  • Se a qualidade source for igual ou superior a Q%, a imagem será comprimida para Q%.

    Por exemplo, se a qualidade da imagem source for 95%, adicionar o parâmetro quality,Q_90 gera uma imagem com 90% de qualidade.

  • Caso a qualidade source seja inferior a Q%, nenhuma compressão ocorre. A qualidade permanece inalterada.

    Por exemplo, se a qualidade da imagem source for 80%, adicionar o parâmetro quality,Q_90 gera uma imagem com 80% de qualidade.

[1,100]

Exemplos

Ajustar a qualidade de uma imagem com leitura pública ou leitura/gravação pública

Adicione parâmetros de processamento de imagem à URL da imagem para ajustar a qualidade.

Estes exemplos usam o bucket oss-console-img-demo-cn-hangzhou na região China (Hangzhou). O endpoint público é:

https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpgOriginal image

Ajustar qualidade relativa

Defina a qualidade relativa como 80% com quality,q_80. A URL para processar a imagem é: https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/quality,q_80

Ajustar qualidade absoluta

Defina a qualidade absoluta como 90% com quality,Q_90. A URL para processar a imagem é: https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/quality,Q_90

Ajustar a qualidade de uma imagem privada

Use os SDKs da Alibaba Cloud ou a API REST para ajustar a qualidade de imagens privadas.

Usar SDKs da Alibaba Cloud

Os exemplos a seguir ajustam a qualidade da imagem com SDKs comuns da Alibaba Cloud. O Overview aborda outros SDKs.

Java

É necessário 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 China (Hangzhou) endpoint 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 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, for example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the full path of the object. The full path cannot include the bucket name.
        String objectName = "example.jpg";
        // Specify the full path of the local file, for example, D:\\dest.jpg. If the specified local file exists, it is overwritten. Otherwise, a new file is created.
        String pathName = "D:\\dest.jpg";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Set the absolute quality of the source image to 80%.
            String image = "image/quality,Q_80";
            GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
            request.setProcess(image);
            // Name the processed image dest.jpg and save it to a local path.
            // If you specify only the filename, such as dest.jpg, without a full path, the file is saved to the local path of the project by default.
            ossClient.getObject(request, new File("D:\\dest.jpg"));
        } 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 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 the sample 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. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to 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, for example, exampledir/exampleobject.jpg. The full path cannot include the bucket name.
$object = "src.jpg";
// Specify the full path of the local file, for example, D:\\dest.jpg. If the specified local file exists, it is overwritten. Otherwise, a new file is created.
// If you specify only the filename, such as dest.jpg, without a full path, the file is saved to the local path of the project by default.
$download_file = "D:\\dest.jpg";

$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);

// Set the absolute quality of the source image to 80%.
$image = "image/quality,Q_80";

$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 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 the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to 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, specify the full path, for example, exampledir/example.jpg.
key = 'src.jpg'
# Specify the name of the processed image.
new_pic = 'D:\\dest.jpg'

# Set the absolute quality of the source image to 80%.
image = 'image/quality,Q_80'
bucket.get_object_to_file(key, new_pic, process=image)

Go

É necessário 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 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.
	// Set yourEndpoint to the endpoint of the bucket. The China (Hangzhou) endpoint is used as an example. Set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify the actual endpoint for other regions.
	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, specify the full path, for example, exampledir/example.jpg.
	sourceImageName := "src.jpg"
	// Specify the name of the processed image.
	targetImageName := "D:\\dest.jpg"
	// Set the absolute quality of the source image to 80%.
	image := "image/quality,Q_80"
	err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(image))
	if err != nil {
		HandleError(err)
	}
}

Usar a API REST

Para maior personalização, chame a API REST diretamente. Implemente o algoritmo de assinatura Signature V4 (recommended).

Adicione parâmetros de ajuste de qualidade a uma solicitação GetObject.

GET /oss.jpg?x-oss-process=image/quality,Q_80 HTTP/1.1
Host: oss-example.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: OSS4-HMAC-SHA256 Credential=LTAI********************/20250417/cn-hangzhou/oss/aliyun_v4_request,Signature=a7c3554c729d71929e0b84489addee6b2e8d5cb48595adfc51868c299c0c218e