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

Object Storage Service:カスタム作物

最終更新日:Jan 13, 2025

webページやレイアウト要件に合わせてObject Storage Service (OSS) に保存されている画像のサイズを変更する場合は、カスタムクロップ機能を使用して、必要なサイズに画像をトリミングできます。

シナリオ

  • Webページのデザインと制作: webページのレイアウトをデザインするときは、アバター、背景画像、製品の表示など、webページの要素に合わせて画像を特定のサイズにトリミングする必要がある場合があります。

  • ソーシャルメディアに必要なカスタム画像サイズ: さまざまなソーシャルメディアプラットフォームでは、サムネイル、投稿できる画像、ストーリー画像など、アップロードする画像のサイズ要件が異なります。 最適な表示パフォーマンスを実現するには、推奨サイズに基づいてソース画像をトリミングする必要があります。

  • モバイルアプリ開発: 特定の仕様に基づいて、アプリ内のアイコン、スタートアップページ、埋め込み画像などの画像をトリミングして、さまざまな解像度と画面サイズのデバイスで画像が期待どおりに表示されるようにする必要があります。

  • 画像データベース管理: ライブラリやアーカイブなど、多数の画像リソースを持つ機関のソートとアーカイブの要件を満たすには、画像を事前設定されたサイズにトリミングする必要があります。

使用上の注意

  • 指定された開始X座標とY座標がソースイメージの開始X座標とY座標を超える場合、BadRequestエラーコードとアドバンスカットの位置はイメージ外になります。 エラーメッセージが返されます。

  • 開始点から指定された幅と高さがソースイメージの幅と高さを超える場合、ソースイメージは境界までトリミングされます。

方法

オブジェクトURLとOSS SDKを使用するか、API操作を呼び出して、イメージの処理に使用するイメージ処理 (IMG) パラメーターを設定できます。 オブジェクトURLを使用して、パブリック読み取りまたはパブリック読み書きイメージに対してのみIMGパラメーターを設定できます。 プライベートイメージのIMGパラメーターを設定する場合は、OSS SDKを使用するか、API操作を呼び出します。 詳細については、「IMG実装モード」をご参照ください。

パブリック読み取りイメージまたはパブリック読み取り /書き込みイメージのクロップ

処理するイメージオブジェクトのアクセス制御リスト (ACL) がpublic-readまたはpublic-read-writeの場合、オブジェクトのURLにIMGパラメーターを追加して、匿名ユーザーが処理されたオブジェクトにアクセスできるようにすることができます。

この例では、? x-oss-process=image/crop,parame_valueは、公开イメージのURLの末尾に追加されます。 parame_valueを、ビジネス要件に基づいて、[パラメーター] セクションに記載されている特定のパラメーターと値に置き換えるだけです。 URLに複数のパラメーターを追加できます。

ソースイメージのURL

ソースイメージの処理に使用されるURL

https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg

https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg?x-oss-process=image/crop,x_800,y_50

プライベート画像をトリミング

OSS SDKの使用

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

Java

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

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 {
        // Specify the endpoint of the region. In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the region of the endpoint. 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. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the source image. Do not include the bucket name in the full path. 
        String objectName = "example.jpg";
        // Specify the full path of the processed image. Example: D:\\dest.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
        String pathName = "D:\\dest.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 {
            // Crop an area of 900 × 900 pixels in the lower-right corner of the image. 
            String image = "image/crop,w_900,h_900,g_se";
            GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
            request.setProcess(image);
            // Save the processed image to your local computer. 
            // If you specify only the name of the processed image such as dest.jpg without specifying the local path, the processed image is saved to the local path of the project to which the sample program belongs. 
            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

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;

// 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";
// Specify the full path of the source image. Do not include the bucket name in the full path. 
$object = "src.jpg";
// Specify the full path of the processed image. Example: D:\\dest.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
// If you specify only the name of the processed image such as dest.jpg without specifying the local path, the processed image is saved to the local path of the project to which the sample program belongs. 
$download_file = "D:\\dest.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);

// Crop an area of 900 × 900 pixels in the lower-right corner of the image. 
$image = "image/crop,w_900,h_900,g_se";

$options = array(
    OssClient::OSS_FILE_DOWNLOAD => $download_file,
    OssClient::OSS_PROCESS => $image);

// Save the processed image to your local computer. 
$ossClient->getObject($bucket, $object, $options);                           

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 source image is stored in the root directory of the bucket, you can specify only the image name. Example: source-example.jpg. If the source image is not stored in the root directory of the bucket, you must specify the full path of the source image. Example: exampledir/source-example.jpg. 
key = 'source-example.jpg'

# Specify the full path of the processed image. Example: D:\\target-example.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
local_file_name = 'D:\\target-example.jpg'

# Configure the crop parameters to crop an area of 900 × 900 pixels in the lower-right corner of the image. 
process = 'image/crop,w_900,h_900,g_se'

# Use the get_object method and pass the processing instruction by using the process parameter. 
result = bucket.get_object_to_file(key, local_file_name, process=process)

Go

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

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. 
	// 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. 
	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 in which the source image is stored. Example: examplebucket. 
	bucketName := "examplebucket"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		HandleError(err)
	}

	// Specify the name of the source image. If the source image is not stored in the root directory of the bucket, you must specify the full path of the source image. Example: exampledir/example.jpg. 
	sourceImageName := "example.jpg"
	// Specify the name of the processed image. 
	targetImageName := "D://dest.jpg"
	// Crop an area of 900 × 900 pixels in the lower-right corner of the image. 
	image := "image/crop,w_900,h_900,g_se"
	err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(image))
	if err != nil {
		HandleError(err)
	}
}

OSS APIの使用

ビジネスで高度なカスタマイズが必要な場合は、RESTful APIを直接呼び出すことができます。 APIを直接呼び出すには、コードに署名計算を含める必要があります。 承認ヘッダーの計算方法の詳細については、「 (推奨) 承認ヘッダーにV4署名を含める」をご参照ください。

GetObject操作でクロップパラメータを指定して、必要なサイズに画像をトリミングできます。 詳細については、「GetObject」をご参照ください。

GET /oss.jpg?x-oss-process=image/crop,w_900,h_900,g_se HTTP/1.1
Host: oss-example.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: SignatureValue

パラメーター

アクション: 作物

次の表に、イメージをトリミングするために設定できるパラメーターを示します。

パラメーター

説明

有効値

w

トリミングする領域の幅。

[0, イメージ幅]

デフォルト値: 最大値。

h

トリミングするエリアの高さ。

[0, イメージの高さ]

デフォルト値: 最大値。

x

トリミングする領域のX座標。 デフォルト値は、画像の左上隅のX座標です。

[0, 画像バインド]

y

トリミングするエリアのY座標。 デフォルト値は、画像の左上隅のY座標です。

[0, 画像バインド]

g

3x3グリッドでトリミングするエリアの位置。 画像は3x3のグリッドにあります。 グリッドには9つのタイルがあります。

  • nw: 左上

  • 北: アッパーミドル

  • ne: 右上

  • west: 中央左

  • センター: センター

  • 東: ミドル右

  • sw: 左下

  • 南: 下ミドル

  • se: 右下

各タイルの位置を計算する方法の詳細については、次の表をご参照ください。

次の表に、3x3グリッド内の各タイルの位置を計算する方法を示します。 srcWはソースイメージの幅を指定し、srcHはソースイメージの高さを指定します。

タイル

計算方法

nw

0, 0

srcW/2 - w/2, 0

ne

srcW - w, 0

西

0、srcH/2 - h/2

center

srcW/2 - w/2、srcH/2 - h/2

srcW - w、srcH/2 - h/2

sw

0、srcH - h

srcW/2 - w/2、srcH - h

se

srcW - w、srcH - h

特定の開始点から画像をトリミングする

開始点 (800、50) から境界まで画像をトリミングします。

  • アクション: cropを指定します。

  • 開始点 (800, 500) をx_800,y_500として指定します。

  • 境界までのクロップ: デフォルトでは、wとhの最大値が画像のクロップに使用されます。 wおよびhパラメーターを指定する必要はありません。

パブリック読み取りイメージまたはパブリック読み取り /書き込みイメージの場合は、? x-oss-process=image/crop,x_800,y_500イメージURLの末尾に 次に、指定されたパラメーターに基づいてリアルタイムで画像を処理し、処理された画像を返します。 プライベートイメージをトリミングする方法の詳細については、「プライベートイメージのトリミング」をご参照ください。

サンプル効果

次の例では、を追加して開始点 (800、50) から境界までソースイメージをトリミングする方法を説明します。? x-oss-process=image/crop,x_800,y_500ソースイメージのURLの末尾に

ソースイメージ

処理されたイメージ

image

image

ソースイメージのURL: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg

ソースイメージの処理に使用されるURL: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg?x-oss-process=image/crop,x_800,y_500

特定の開始点から指定された幅と高さに基づいて領域をトリミングする

始点から300 × 300ピクセルの領域をトリミングする (800、500)

  • アクション: cropを指定します。

  • 開始点 (800, 500) をx_800,y_500として指定します。

  • w_300、h_300: 300 × 300ピクセルの領域をトリミングします。

パブリック読み取りイメージまたはパブリック読み取り /書き込みイメージの場合は、? x-oss-process=image/crop,x_800,y_500,w_300,h_300イメージURLの末尾に 次に、指定されたパラメーターに基づいてリアルタイムで画像を処理し、処理された画像を返します。 プライベートイメージをトリミングする方法の詳細については、「プライベートイメージのトリミング」をご参照ください。

サンプル効果

次の例では、開始点 (800、500) から300 × 300ピクセルの領域を追加してトリミングする方法を説明します。? x-oss-process=image/crop,x_800,y_500,w_300,h_300ソースイメージのURLの末尾に

ソースイメージ

処理されたイメージ

image

image

ソースイメージのURL: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg

画像の処理に使用されるURL: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg?x-oss-process=image/crop,x_800,y_500,w_300,h_300

画像の右下隅の指定された幅と高さに基づいて領域をトリミングする

画像の右下隅にある900 × 900ピクセルの領域をトリミングする

  • アクション: cropを指定します。

  • 右下隅で開始点を指定します: g_se

  • w_900、h_900: 900 × 900ピクセルの領域をトリミングします。

パブリック読み取りイメージまたはパブリック読み取り /書き込みイメージの場合は、? x-oss-process=image/crop,g_se,w_900,h_900イメージURLの末尾に 次に、指定されたパラメーターに基づいてリアルタイムで画像を処理し、処理された画像を返します。 プライベートイメージをトリミングする方法の詳細については、「プライベートイメージのトリミング」をご参照ください。

サンプル効果

次の例では、画像の右下隅にある900 × 900ピクセルの領域を追加してトリミングする方法について説明します。? x-oss-process=image/crop,g_se,w_900,h_900画像のURLの末尾に

ソースイメージ

処理されたイメージ

image

image

ソースイメージのURL: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg

画像の処理に使用されるURL: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg?x-oss-process=image/crop,g_se,w_900,h_900

画像の右下隅の指定された幅と高さに基づいて領域をトリミングし、トリミングされた領域を引き伸ばします。

画像の右下隅にある900 × 900ピクセルの領域をトリミングし、トリミングした領域を (100,200)

  • アクション: cropを指定します。

  • 画像の右下隅に開始点を指定し、トリミングされた領域を (100,200) で下に伸ばします。g_se,x_100,y_200

  • w_900、h_900: 900 × 900ピクセルの領域をトリミングします。

パブリック読み取りイメージまたはパブリック読み取り /書き込みイメージの場合は、? x-oss-process=image/crop,g_se,x_100,y_200,w_900,h_900イメージURLの末尾に 次に、指定されたパラメーターに基づいてリアルタイムで画像を処理し、処理された画像を返します。 プライベートイメージをトリミングする方法の詳細については、「プライベートイメージのトリミング」をご参照ください。

サンプル効果

次の例では、画像の右下隅にある900 × 900ピクセルの領域を追加してトリミングする方法について説明します。? x-oss-process=image/crop,g_se,x_100,y_200,w_900,h_900画像のURLの末尾に

ソースイメージ

処理されたイメージ

image

image

ソースイメージのURL: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg

画像の処理に使用されるURL: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg?x-oss-process=image/crop,g_se,x_100,y_200,w_900,h_900

スマートクロッピングを使用して画像をトリミングする

スマートクロッピングを使用して画像をトリミングするには、次のパラメーターを設定します。

  • アクション: cropを指定します。

  • アルゴリズムを指定する: g_auto

OSS SDKを使用してイメージを処理するには、バケットをIntelligent Media Management (IMM) プロジェクトにバインドする必要があります。

サンプルコード

Java

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

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 {
        // Specify the endpoint of the region. In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the region of the endpoint. 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. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the source image. Do not include the bucket name in the full path. 
        String objectName = "example.jpg";
        // Specify the full path of the processed image. Example: D:\\dest.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
        String pathName = "D:\\dest.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 {
            // Perform smart cropping. 
            String image = "image/crop,g_auto";
            GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
            request.setProcess(image);
            // Save the processed image to your local computer. 
            // If you specify only the name of the processed image such as dest.jpg without specifying the local path, the processed image is saved to the local path of the project to which the sample program belongs. 
            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

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;

// 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";
// Specify the full path of the source image. Do not include the bucket name in the full path. 
$object = "src.jpg";
// Specify the full path of the processed image. Example: D:\\dest.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
// If you specify only the name of the processed image such as dest.jpg without specifying the local path, the processed image is saved to the local path of the project to which the sample program belongs. 
$download_file = "D:\\dest.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);

// Perform smart cropping. 
$image = "image/crop,g_auto";

$options = array(
    OssClient::OSS_FILE_DOWNLOAD => $download_file,
    OssClient::OSS_PROCESS => $image);

// Save the processed image to your local computer. 
$ossClient->getObject($bucket, $object, $options);                           

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 source image is stored in the root directory of the bucket, you can specify only the image name. Example: source-example.jpg. If the source image is not stored in the root directory of the bucket, you must specify the full path of the source image. Example: exampledir/source-example.jpg. 
key = 'source-example.jpg'

# Specify the full path of the processed image. Example: D:\\target-example.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
local_file_name = 'D:\\target-example.jpg'

# Perform smart cropping. 
process = 'image/crop,g_auto'

# Use the get_object method and pass the processing instruction by using the process parameter. 
result = bucket.get_object_to_file(key, local_file_name, process=process)

Go

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

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. 
	// 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. 
	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 in which the source image is stored. Example: examplebucket. 
	bucketName := "examplebucket"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		HandleError(err)
	}

	// Specify the name of the source image. If the source image is not stored in the root directory of the bucket, you must specify the full path of the source image. Example: exampledir/example.jpg. 
	sourceImageName := "example.jpg"
	// Specify the name of the processed image. 
	targetImageName := "D://dest.jpg"
	// Perform smart cropping. 
	image := "image/crop,g_auto"
	err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(image))
	if err != nil {
		HandleError(err)
	}
}

サンプル効果

次の表は、image/crop,g_autoパラメーターを使用して処理されたソースイメージとイメージを示しています。

ソースイメージ

処理されたイメージ

原图

image

画像内の最大の顔の中心から指定された幅と高さに基づいて領域をトリミングする

画像内の最大の顔の中心から200 × 200ピクセルの領域をトリミングする

  • アクション: cropを指定します。

  • 画像内の最大の顔の中心から領域をトリミングします: g_face

  • w_200、h_200: 200 × 200ピクセルの領域をトリミングします。

OSS SDKを使用してイメージを処理するには、バケットをIMMプロジェクトにバインドする必要があります。

サンプルコード

Java

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

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 {
        // Specify the endpoint of the region. In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the region of the endpoint. 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. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the source image. Do not include the bucket name in the full path. 
        String objectName = "example.jpg";
        // Specify the full path of the processed image. Example: D:\\dest.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
        String pathName = "D:\\dest.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 {
            // Crop an area of 200 × 200 pixels from the center of the maximum face in the image. 
            String image = "image/crop,g_face,w_200,h_200";
            GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
            request.setProcess(image);
            // Save the processed image to your local computer. 
            // If you specify only the name of the processed image such as dest.jpg without specifying the local path, the processed image is saved to the local path of the project to which the sample program belongs. 
            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

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;

// 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";
// Specify the full path of the source image. Do not include the bucket name in the full path. 
$object = "src.jpg";
// Specify the full path of the processed image. Example: D:\\dest.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
// If you specify only the name of the processed image such as dest.jpg without specifying the local path, the processed image is saved to the local path of the project to which the sample program belongs. 
$download_file = "D:\\dest.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);

// Crop an area of 200 × 200 pixels from the center of the maximum face in the image. 
$image = "image/crop,g_face,w_200,h_200";

$options = array(
    OssClient::OSS_FILE_DOWNLOAD => $download_file,
    OssClient::OSS_PROCESS => $image);

// Save the processed image to your local computer. 
$ossClient->getObject($bucket, $object, $options);                           

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 source image is stored in the root directory of the bucket, you can specify only the image name. Example: source-example.jpg. If the source image is not stored in the root directory of the bucket, you must specify the full path of the source image. Example: exampledir/source-example.jpg. 
key = 'source-example.jpg'

# Specify the full path of the processed image. Example: D:\\target-example.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
local_file_name = 'D:\\target-example.jpg'

# Crop an area of 200 × 200 pixels from the center of the maximum face in the image.
process = 'image/crop,g_face,w_200,h_200'

# Use the get_object method and pass the processing instruction by using the process parameter. 
result = bucket.get_object_to_file(key, local_file_name, process=process)

Go

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

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. 
	// 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. 
	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 in which the source image is stored. Example: examplebucket. 
	bucketName := "examplebucket"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		HandleError(err)
	}

	// Specify the name of the source image. If the source image is not stored in the root directory of the bucket, you must specify the full path of the source image. Example: exampledir/example.jpg. 
	sourceImageName := "example.jpg"
	// Specify the name of the processed image. 
	targetImageName := "D://dest.jpg"
	// Crop an area of 200 × 200 pixels from the center of the maximum face in the image. 
	image := "image/crop,g_face,w_200,h_200"
	err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(image))
	if err != nil {
		HandleError(err)
	}
}

サンプル効果

次の例では、image/crop,g_face,w_200,h_200を使用して、画像内の最大顔の中心から200 × 200ピクセルの領域をトリミングする方法を説明します。

ソースイメージ

処理されたイメージ

原图

image

画像内の最大の顔の中心から領域を切り取り、切り取った領域を最大の顔のサイズの2倍に拡大します。

次のパラメーターを設定します。

  • アクション: cropを指定します。

  • 画像内の最大の顔の中心から領域をトリミングします: g_face

  • トリミングされた領域を最大面の2倍のサイズ (p_200) に拡大します。

OSS SDKを使用してイメージを処理するには、バケットをIMMプロジェクトにバインドする必要があります。

サンプルコード

Java

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

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 {
        // Specify the endpoint of the region. In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the region of the endpoint. 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. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the source image. Do not include the bucket name in the full path. 
        String objectName = "example.jpg";
        // Specify the full path of the processed image. Example: D:\\dest.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
        String pathName = "D:\\dest.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 {
            // Crop an area of 200 × 200 pixels from the center of the maximum face in the image. 
            String image = "image/crop,g_face,w_200,h_200";
            GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
            request.setProcess(image);
            // Save the processed image to your local computer. 
            // If you specify only the name of the processed image such as dest.jpg without specifying the local path, the processed image is saved to the local path of the project to which the sample program belongs. 
            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

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;

// 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";
// Specify the full path of the source image. Do not include the bucket name in the full path. 
$object = "src.jpg";
// Specify the full path of the processed image. Example: D:\\dest.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
// If you specify only the name of the processed image such as dest.jpg without specifying the local path, the processed image is saved to the local path of the project to which the sample program belongs. 
$download_file = "D:\\dest.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);

// Crop an area of 200 × 200 pixels from the center of the maximum face in the image. 
$image = "image/crop,g_face,w_200,h_200";

$options = array(
    OssClient::OSS_FILE_DOWNLOAD => $download_file,
    OssClient::OSS_PROCESS => $image);

// Save the processed image to your local computer. 
$ossClient->getObject($bucket, $object, $options);                           

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 source image is stored in the root directory of the bucket, you can specify only the image name. Example: source-example.jpg. If the source image is not stored in the root directory of the bucket, you must specify the full path of the source image. Example: exampledir/source-example.jpg. 
key = 'source-example.jpg'

# Specify the full path of the processed image. Example: D:\\target-example.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
local_file_name = 'D:\\target-example.jpg'

# Crop an area of 200 × 200 pixels from the center of the maximum face in the image.
process = 'image/crop,g_face,w_200,h_200'

# Use the get_object method and pass the processing instruction by using the process parameter. 
result = bucket.get_object_to_file(key, local_file_name, process=process)

Go

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

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. 
	// 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. 
	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 in which the source image is stored. Example: examplebucket. 
	bucketName := "examplebucket"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		HandleError(err)
	}

	// Specify the name of the source image. If the source image is not stored in the root directory of the bucket, you must specify the full path of the source image. Example: exampledir/example.jpg. 
	sourceImageName := "example.jpg"
	// Specify the name of the processed image. 
	targetImageName := "D://dest.jpg"
	// Crop an area of 200 × 200 pixels from the center of the maximum face in the image. 
	image := "image/crop,g_face,w_200,h_200"
	err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(image))
	if err != nil {
		HandleError(err)
	}
}

サンプル効果

次の表は、image/crop,g_face,p_200パラメーターを使用して処理されたソースイメージとイメージを示しています。

ソースイメージ

処理されたイメージ

原图

image