GetObject
リクエストに画像サイズ変更パラメーターを追加して、画像のサイズを変更できます。
シナリオ
Webページのデザイン: webページのデザインとモバイルアプリの開発中に、さまざまな画面サイズと解像度のデバイスに表示するように画像を自動的に調整する必要があります。
ソーシャルメディア: ユーザーがソーシャルメディアプラットフォームにアップロードした画像のサイズはさまざまです。 より良いプレビュー体験を提供するために、プラットフォームは画像のサイズを変更する必要があります。
画像認識と分析: コンピュータビジョンと機械学習では、処理効率を高めるために画像のサイズを変更する必要があります。
制限事項
制限事項 | 項目 | 説明 |
ソース画像 | イメージ形式 | JPG、PNG、BMP、GIF、WebP、TIFF、およびHEIC形式のみがサポートされています。 |
画像サイズ | ソースイメージのサイズは20 MBを超えることはできません。 クォータセンターでソースイメージのサイズの制限を変更することができます。 制限の変更を申請するには、次の手順を実行します。Object Storage Service (OSS) コンソールに移動します。 左側のナビゲーションウィンドウで、 を選択の制限を変更します。 | |
画像の幅と高さ | ソースイメージの幅または高さは30,000ピクセルを超えることはできません。 ソースイメージのピクセルの総数は250万を超えることはできません。 説明 GIF画像などの動画像の総画素数は、 | |
サイズ変更された画像 | 画像のサイズ変更 | サイズ変更された画像の幅または高さは16,384ピクセルを超えることはできません。 サイズ変更画像の総ピクセル数は16,777,216を超えることはできません。 |
課金
画像のサイズ変更機能を使用すると、次の請求可能なアイテムに対して課金されます。
API操作呼び出し料金: OSSのイメージサイズ変更機能は、GetObject操作を呼び出すことによって実装されます。 GETリクエストの数に基づいて、API操作呼び出し料金が請求されます。 詳細については、「API 操作呼び出し料金」をご参照ください。
トラフィック料金: 処理された画像のサイズに基づいて、インターネット経由のアウトバウンドトラフィックに対して課金されます。 詳細については、「トラフィック料金」をご参照ください。
ソースイメージのストレージクラスが標準でない場合、ソースイメージのサイズに基づいてイメージ処理料金も請求されます。 詳細については、「データ処理料金」をご参照ください。
演算方法
OSSでは、イメージURLに? x-oss-process=image/resize,parame_value
パラメーターを指定すると、OSSはイメージをリアルタイムで処理し、処理されたイメージを返します。 パラメーターで、image/resize
は画像のサイズ変更を指定し、parame
はサイズ変更するパラメーターを指定し、value
はサイズ変更するパラメーターの値を指定します。 パラメーターのサイズ変更の詳細については、「パラメーターの説明」をご参照ください。 複数のパラメータを組み合わせて使用できます。
イメージのアクセス制御リスト (ACL) が公開されている場合は、イメージのURLにイメージのサイズ変更パラメーターを追加して、匿名ユーザーが処理されたイメージにアクセスできるようにすることができます。 イメージのACLがプライベートイメージの場合、リクエストに署名を含めて、OSS SDKを使用するか、API操作を呼び出してイメージを処理する必要があります。
パブリック読み取りイメージ
次の表では、? x-oss-process=image/resize,parame_value
パラメーターをパブリック読み取りイメージのURLの末尾に設定します。 parame_value
を実際のパラメーターと値に置き換えるだけです。
ソースイメージのURL | ソースイメージの処理に使用されるURL |
https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg |
プライベート画像
OSS SDKの使用
OSS SDKを使用して、画像のサイズ変更パラメーターを含む署名付きURLを生成し、署名付きURLを取得したユーザーが処理された画像に一時的にアクセスできるようにすることができます。 次のサンプルコードは、OSS SDKを使用して、? x-oss-process=image/parame_value
プライベートイメージのパラメータ:
Java
package com.aliyun.oss.demo;
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import java.net.URL;
import java.util.Date;
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";
// 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 image that you want to process. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/exampleobject.jpg.
String objectName = "exampledir/exampleobject.png";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// 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 {
// Specify the image resizing parameters. Replace parame_value with the actual parameter values. For example, if you replace parame_value with p_50, the image is proportionally scaled down to 50% of the original size.
String style = "image/resize,parame_value";
// Set the validity period of the signed URL to 3600 seconds.
Date expiration = new Date(new Date().getTime() + 3600 );
GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
req.setExpiration(expiration);
req.setProcess(style);
URL signedUrl = ossClient.generatePresignedUrl(req);
System.out.println(signedUrl);
} 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();
}
}
}
}
Python
# -*- 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 name of the bucket.
bucket = 'examplebucket'
# Specify the endpoint of the region in which the bucket is located. In this example, the endpoint of the China (Hangzhou) region is used.
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, bucket, region=region)
# Specify the name of the image that you want to process. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/exampleobject.jpg.
key = 'exampledir/exampleobject.png'
# Specify the expiration time. Unit: seconds.
expire_time = 3600
# Specify the image resizing parameters. Replace parame_value with the actual parameter values. For example, if you replace parame_value with p_50, the image is proportionally scaled down to 50% of the original size.
image_process = 'image/resize,parame_value'
# Generate a signed URL that includes Image Processing (IMG) parameters.
url = bucket.sign_url('GET', key, expire_time, params={'x-oss-process': image_process}, slash_safe=True)
# Print the signed URL.
print(url)
PHP
<?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 = "yourEndpoint";
// Specify the name of the bucket. Example: examplebucket.
$bucket= "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.jpg. Do not include the bucket name in the full path.
$object = "exampledir/exampleobject.jpg";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
// Generate a signed URL that includes IMG parameters. The validity period of the URL is 3,600 seconds. The signed URL can be directly used to access the image by using a browser.
$timeout = 3600;
$options = array(
// Specify the image resizing parameters. Replace parame_value with the actual parameter values. For example, if you replace parame_value with p_50, the image is proportionally scaled down to 50% of the original size.
OssClient::OSS_PROCESS => "image/resize,parame_value");
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
print("rtmp url: \n" . $signedUrl);
Go
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.
// Specify the region of the bucket. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify your actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the signature version.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
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 image. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/exampleobject.jpg.
ossImageName := "exampledir/exampleobject.png"
// Generate a signed URL that includes IMG parameters. Set the validity period of the URL to 3,600 seconds. The maximum validity period of a signed URL is 32,400 seconds.
// Specify the image resizing parameters. Replace parame_value with the actual parameter values. For example, if you replace parame_value with p_50, the image is proportionally scaled down to 50% of the original size.
signedURL, err := bucket.SignURL(ossImageName, oss.HTTPGet, 3600, oss.Process("image/resize,parame_value"))
if err != nil {
HandleError(err)
} else {
fmt.Println(signedURL)
}
}
次のサンプルコードは、署名付きURLを生成する方法の例を示しています。
https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampledir/exampleobject.png?x-oss-process=image%2Fresize%2Cp_50&x-oss-date=20241111T113707Z&x-oss-expires=3600&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI********************%2F20241111%2Fcn-hangzhou%2Foss%2Faliyun_v4_request&x-oss-signature=6fd07a2ba50bf6891474dc56aed976b556b6fbcd901cfd01bcde5399bf4802cb
他のプログラミング言語のOSS SDKを使用して画像のサイズを変更する方法については、「概要」をご参照ください。
OSS APIの使用
ビジネスで高度なカスタマイズが必要な場合は、OSS APIを直接呼び出すことができます。 API操作を直接呼び出すには、コードに署名計算を含める必要があります。 承認ヘッダーの計算方法については、「 (推奨) 承認ヘッダーにV4署名を含める」をご参照ください。
GetObject操作に画像のサイズ変更パラメーターを追加して、画像のサイズを変更できます。 詳細については、「GetObject」をご参照ください。
GET /oss.jpg?x-oss-process=image/resize,p_50 HTTP/1.1
Host: oss-example.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: SignatureValue
パラメータ説明
アクション: resize
比例スケーリング
p
パラメーターを使用して、画像の比例スケーリングを指定できます。
パラメーター | 説明 | 値 |
p | 画像のサイズを変更する割合を指定します。 | 1から1000。 100より小さい値は、イメージが縮小されることを指定します。 100より大きい値は、イメージが拡大されることを指定します。 |
指定した幅と高さに基づいて画像のサイズを変更する
w
パラメーターとh
パラメーターを使用して、画像のサイズを変更する幅と高さを指定し、m
パラメーターを使用してサイズ変更アクションのタイプを指定できます。 これにより、さまざまなレイアウト要件を満たすことができます。 サイズを変更した画像の長辺または短辺の長さを制限する場合は、l
またはs
パラメーターを使用します。 イメージをスケールアップする場合は、limit_0
パラメーターを追加する必要があります。
パラメーター | 説明 | 値 |
w | 画像のサイズを変更する幅を指定します。 | 1から16384。 |
h | 画像のサイズを変更する高さを指定します。 | 1から16384。 |
m | サイズ変更アクションのタイプを指定します。 |
サイズ変更画像の説明については、「サイズ変更画像のサイズを計算する方法」をご参照ください。 説明
|
l | 画像のサイズを変更する長辺の長さを指定します。 説明 長辺とは、元のサイズと目標サイズとの比が大きい辺を指す。 例えば、ソース画像が100 × 200ピクセルから100 × 100ピクセルにサイズ変更される場合、オリジナル対ターゲット比は2 (200/100) 及び1 (100/100) である。 2が1より大きいとすると、元々200ピクセルであった辺が長辺であり、元々100ピクセルであった辺が短辺である。 | 1から16384。 |
s | 画像のサイズを変更する短辺の長さを指定します。 | 1から16384。 |
制限 | ターゲットイメージの解像度がソースイメージの解像度よりも高い場合にイメージのサイズを変更するかどうかを指定します。 重要 サイズ変更されたイメージのサイズがソースイメージのサイズより大きい場合、ソースイメージが返されます。 イメージをスケールアップする場合は、 |
説明 GIFイメージのサイズは、指定された幅と高さに基づいてのみ縮小できます。 |
カラー | サイズ変更タイプをpadに設定した場合、空のスペースを塗りつぶす色を選択できます。 | RGBカラー値。 例えば、000000は黒を指定し、FFFFFFは白を指定する。 デフォルト値: FFFFFF |
サイズ変更後の画像の幅または高さのみを指定する場合は、次の項目に注意してください。
サイズ変更タイプをlfit、mfit、またはfixedに設定すると、OSSはソースイメージのサイズを比例的に変更します。 たとえば、ソースイメージの高さを256 × 144ピクセルから100ピクセルにサイズ変更すると、ソースイメージの幅は178ピクセルにサイズ変更されます。
サイズ変更タイプをpadまたはfillに設定した場合、OSSは指定された値に基づいてソースイメージのサイズを変更します。 たとえば、ソースイメージの高さを256 × 144ピクセルから100ピクセルにサイズ変更すると、ソースイメージの幅も100ピクセルにサイズ変更されます。
l
パラメーターとs
パラメーターのいずれか一方のみを指定した場合、OSSは指定された値に基づいてソースイメージの指定された辺のサイズを変更し、もう一方の辺を元のアスペクト比に基づいて自動的に調整します。 この場合、m
パラメーターの設定は有効になりません。l
パラメーターとs
パラメーターを同時に指定すると、ソースイメージのサイズ変更中に元のアスペクト比が維持されます。 この場合、m
パラメーターの設定が有効になります。 サイズ変更タイプを指定しない場合、デフォルトでlfit
が使用されます。
サイズ変更画像のサイズを計算する方法
ソースイメージのサイズ | 指定されたイメージサイズ変更パラメーター | サイズ変更タイプ | サイズ変更された画像のサイズ |
200 × 100ピクセル | 150 × 80ピクセル | lfit (デフォルト) OSSは、指定された幅と高さに基づいて、長方形の最大サイズに比例してソースイメージのサイズを変更します。 | 150 × 75ピクセル |
mfit OSSは、指定された幅と高さの長方形を超えた最小サイズにソースイメージのサイズを比例的に変更します。 | 160 × 80ピクセル | ||
fill OSSは、指定された幅と長さの長方形を超えて広がる可能な最小サイズにソース画像を比例的にサイズ変更し、中央から指定された幅と高さまで画像をトリミングします。 | 150 × 80ピクセル | ||
パッド OSSは、指定された幅と長さの長方形に収まる最大サイズにソースイメージのサイズを比例的に変更し、指定された幅と高さに基づいて長方形の空きスペースを埋めて、必要なサイズの最終イメージを生成します。 | 150 × 80ピクセル | ||
固定 OSSは、指定された幅と高さに基づいてソースイメージのサイズを強制的に変更します。 サイズ変更された画像のアスペクト比がソース画像のアスペクト比と異なる場合、画像は歪んでいる。 | 150 × 80ピクセル |
mパラメーターをlfitまたはmfitに設定すると、比率が小数の場合、ソースイメージのアスペクト比は整数に丸められます。