El ajuste de calidad comprime las imágenes en su formato original. Use los parámetros de ajuste de calidad para controlar la calidad de las imágenes almacenadas en OSS.
El ajuste de calidad no tiene efecto en formatos sin pérdida como PNG.
PNG usa compresión sin pérdida. Cuando se usan juntos resize y quality, el cambio de tamaño puede aumentar la complejidad de la imagen y el costo de compresión, lo que podría incrementar el tamaño del archivo. El parámetro quality no aplica a las imágenes PNG y se ignora.
Para reducir el tamaño de una imagen PNG, primero use el parámetro format para convertirla a JPG o WebP. Después, aplique el parámetro quality. Por ejemplo:
image/format,jpg/quality,Q_30
O bien:
image/format,webp/quality,Q_30
Parámetros
Acción: quality
A continuación se describen los parámetros.
Parámetro | Descripción | Valores válidos |
q | Establece la calidad relativa. Comprime la imagen de origen según un porcentaje. Por ejemplo, si la calidad de la imagen de origen es del 100 %, agregar el parámetro Nota El parámetro q aplica únicamente a JPG. Para WebP, funciona igual que el parámetro Q y establece la calidad absoluta. | [1,100] |
Q | Establece la calidad absoluta.
| [1,100] |
Ejemplos
Ajustar la calidad de una imagen pública o de lectura y escritura públicas
Agregue los parámetros de procesamiento de imágenes a la URL de la imagen para ajustar la calidad.
Estos ejemplos usan el bucket oss-console-img-demo-cn-hangzhou en la región China (Hangzhou). El endpoint público es:
https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg
Ajustar la calidad relativa
Establezca la calidad relativa en 80 % con quality,q_80. La URL para procesar la imagen es: https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/quality,q_80
Ajustar la calidad absoluta
Establezca la calidad absoluta en 90 % con quality,Q_90. La URL para procesar la imagen es: https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/quality,Q_90
Ajustar la calidad de una imagen privada
Use los SDK de Alibaba Cloud o la API REST para ajustar la calidad de las imágenes privadas.
Usar los SDK de Alibaba Cloud
Los siguientes ejemplos ajustan la calidad de la imagen con los SDK más comunes de Alibaba Cloud. Descripción general cubre otros SDK adicionales.
Java
Se requiere Java SDK 3.17.4 o 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
Se requiere PHP SDK 2.7.0 o 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
Se requiere Python SDK 2.18.4 o 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
Se requiere Go SDK 3.0.2 o 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 la API REST
Para mayor personalización, llame directamente a la API REST. Debe implementar el algoritmo de firma Signature V4 (recommended).
Agregue los parámetros de ajuste de calidad a una solicitud 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