すべてのプロダクト
Search
ドキュメントセンター

Object Storage Service:平均トーンを照会する

最終更新日:Oct 08, 2024

このトピックでは、画像の平均階調を照会するためのパラメーターと例について説明します。

パラメーター

アクション: 平均色相

返された平均トーン情報は、0xRRGGBBのフォーマットである。 RR、GG、およびBBは2つの16進数を使用します。 RRは赤、GGは緑、BBは青を示す。

方法

パブリック読み取りイメージまたはパブリック読み取り /書き込みイメージの平均トーンの照会

イメージ処理 (IMG) パラメーターをパブリック読み取りイメージまたはパブリック読み取り書き込みイメージのURLに追加して、イメージの平均階調を照会できます。

この例では、中国 (杭州) リージョンのoss-console-img-demo-cn-hangzhouバケットにあるexample.jpgという名前のイメージが使用されています。 イメージは次のURLでホストされます。

次のURLは、画像の平均階調を照会するために使用されます。 https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/average-hue

ブラウザで返される平均トーンは0xbbcd7fです。 0xbbcd7fは、RGBカラー値 (187,205,127) を示す。

平均色调

プライベート画像の平均トーンの照会

OSS SDKとOSS APIを使用して、プライベートイメージの平均トーンを照会できます。

OSS SDKの使用

次のサンプルコードは、一般的なプログラミング言語のOSS SDKを使用してプライベートイメージの平均トーンをクエリする方法の例を示しています。 他のプログラミング言語を使用してプライベートイメージの平均トーンを照会する方法の詳細については、「概要」をご参照ください。

Java

Java 3.17.4以降のOSS SDKが必要です。

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. 
        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

PHP 2.7.0以降のOSS SDKが必要です。

<?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

Python 2.18.4以降のOSS SDKが必要です。

# -*- 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

Go 3.0.2以降のOSS SDKが必要です。

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))
}

OSS APIの使用

ビジネスで高度なカスタマイズが必要な場合は、RESTful APIを直接呼び出すことができます。 APIを直接呼び出すには、コードに署名計算を含める必要があります。 詳しくは、「GetObject」をご参照ください。

GetObject操作で平均トーンパラメーターを指定して、イメージの平均トーンを照会できます。

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: OSS qn6q**************:77Dv****************