Cette rubrique décrit les paramètres et fournit des exemples pour interroger la tonalité moyenne d'une image.
Paramètres
Action : average-hue
Les informations de tonalité moyenne renvoyées suivent le format 0xRRGGBB. RR, GG et BB utilisent deux chiffres hexadécimaux. RR indique le rouge, GG le vert et BB le bleu.
Méthodes
Interroger la tonalité moyenne d'une image en lecture publique ou en lecture-écriture publique
Ajoutez des paramètres de traitement d'image (IMG) à l'URL d'une image en lecture publique ou en lecture-écriture publique pour interroger sa tonalité moyenne.
Dans cet exemple, nous utilisons une image nommée example.jpg stockée dans le bucket oss-console-img-demo-cn-hangzhou de la région Chine (Hangzhou). L'image est hébergée à l'URL suivante :
https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg
L'URL suivante permet d'interroger la tonalité moyenne de l'image : https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/average-hue.
La tonalité moyenne renvoyée dans le navigateur est 0xbbcd7f. La valeur 0xbbcd7f correspond à la couleur RGB (187 205 127).

Interroger la tonalité moyenne d'une image privée
Utilisez les SDK OSS et l'API OSS pour interroger la tonalité moyenne d'une image privée.
Utiliser les SDK OSS
Le code suivant illustre comment interroger la tonalité moyenne d'une image privée à l'aide des SDK OSS pour les langages de programmation courants. Pour plus d'informations sur l'interrogation de la tonalité moyenne d'une image privée avec d'autres langages, consultez Présentation.
Java
Le SDK OSS pour Java version 3.17.4 ou ultérieure est requis.
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyuncs.exceptions.ClientException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class Demo{
public static void main(String[] args) throws ClientException, ClientException {
// Specify the endpoint of the region in which the bucket is located.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region of the bucket in which the private image is stored. 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.
String bucketName = "examplebucket";
// If the image is stored in the root directory of the bucket, enter the image name. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg.
String key = "example.jpg";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Create a processing instruction to query the average tone of the image.
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
getObjectRequest.setProcess("image/average-hue");
// Use the process parameter of the getObject method to pass the processing instruction.
OSSObject ossObject = ossClient.getObject(getObjectRequest);
// Read and display the query results.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = ossObject.getObjectContent().read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
String imageInfo = baos.toString("UTF-8");
System.out.println("Image Info:");
System.out.println(imageInfo);
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} finally {
// Shut down the OSSClient instance.
ossClient.shutdown();
}
}
}
PHP
Le SDK OSS pour 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;
try {
// 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';
// If the image is stored in the root directory of the bucket, enter the image name. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg.
$key = 'example.jpg';
$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);
// Create a processing instruction to query the average tone of the image.
$options[$ossClient::OSS_PROCESS] = "image/average-hue";
$result = $ossClient->getObject($bucket,$key,$options);
var_dump($result);
} catch (OssException $e) {
printf($e->getMessage() . "\n");
return;
}
Python
Le SDK OSS pour 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())
# 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)
# If the image is stored in the root directory of the bucket, enter the image name. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg.
key = 'example.jpg'
# Create a processing instruction to query the average tone of the image.
process = 'image/average-hue'
try:
# Use the get_object method and pass the processing instruction by using the process parameter.
result = bucket.get_object(key, process=process)
# Read and display the query results.
image_info = result.read().decode('utf-8')
print("Image Info:")
print(image_info)
except oss2.exceptions.OssError as e:
print("Error:", e)
Go
Le SDK OSS pour Go version 3.0.2 ou ultérieure est requis.
package main
import (
"fmt"
"io"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain the temporary access credentials from the 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.
// Specify the ID of the Alibaba Cloud region in which the bucket is located. Example: cn-hangzhou.
client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region("cn-hangzhou"))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of the bucket. Example: examplebucket.
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// If the image is stored in the root directory of the bucket, enter the image name. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg.
// Use the oss.Process method to pass the processing instruction of querying the average tone of the image.
body, err := bucket.GetObject("example.jpg", oss.Process("image/average-hue"))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
defer body.Close()
data, err := io.ReadAll(body)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
fmt.Println("data:", string(data))
}
Utiliser l'API RESTful
Si votre activité nécessite un niveau élevé de personnalisation, vous pouvez appeler directement les API RESTful. Pour appeler directement une API, vous devez inclure le calcul de signature dans votre code. Pour plus d'informations, consultez (Recommandé) Inclure une signature V4.
Spécifiez les paramètres de tonalité moyenne dans l'opération GetObject pour interroger la tonalité moyenne d'une image.
GET /oss.jpg?x-oss-process=image/average-hue 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