L'ajustement de la qualité compresse les images en conservant leur format d'origine. Utilisez les paramètres d'ajustement de la qualité pour contrôler la qualité des images stockées dans OSS.
L'ajustement de la qualité n'a aucun effet sur les formats sans perte tels que PNG.
Paramètres
Action : quality
Le tableau suivant décrit les paramètres.
|
Paramètre |
Description |
Valeurs valides |
|
q |
Définit la qualité relative. Compresse l'image source selon un pourcentage. Par exemple, si la qualité de l'image source est de 100 %, l'ajout du paramètre Remarque
Le paramètre q s'applique uniquement au format JPG. Pour le format WebP, il se comporte comme le paramètre Q et définit la qualité absolue. |
[1,100] |
|
Q |
Définit la qualité absolue.
|
[1,100] |
Exemples
Ajuster la qualité d'une image en lecture publique ou en lecture-écriture publique
Ajoutez des paramètres de traitement d'image à l'URL de l'image pour ajuster sa qualité.
Ces exemples utilisent le bucket oss-console-img-demo-cn-hangzhou dans la région Chine (Hangzhou). L'endpoint public est le suivant :
https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg
Ajuster la qualité relative
Définissez la qualité relative à 80 % avec quality,q_80. L'URL pour traiter l'image est : https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/quality,q_80
Ajuster la qualité absolue
Définissez la qualité absolue à 90 % avec quality,Q_90. L'URL pour traiter l'image est : https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/quality,Q_90
Ajuster la qualité d'une image privée
Utilisez les SDK Alibaba Cloud ou l'API REST pour ajuster la qualité des images privées.
Utiliser les SDK Alibaba Cloud
Les exemples suivants ajustent la qualité des images à l'aide des SDK Alibaba Cloud courants. La rubrique Vue d'ensemble couvre d'autres SDK.
Java
Le SDK Java version 3.17.4 ou ultérieure est requis.
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
Le SDK PHP version 2.7.0 ou ultérieure est requis.
<?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
Le SDK Python version 2.18.4 ou ultérieure est requis.
# -*- 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.
## Set 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
Le SDK Go version 3.0.2 ou ultérieure est requis.
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)
}
}
Utiliser l'API REST
Pour une personnalisation plus poussée, appelez directement l'API REST. Vous devez implémenter l'algorithme de signature Signature V4 (recommandé).
Ajoutez des paramètres d'ajustement de la qualité à une requête 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