このトピックでは、オブジェクトURL、OSS SDK、またはAPI操作を使用して、Object Storage Service (OSS) に保存されているイメージオブジェクトを処理する方法について説明します。
オブジェクトURLを使用して画像を処理する
URLを使用して画像オブジェクトを処理するには、画像処理 (IMG) パラメーターまたは画像スタイルパラメーターをURLの末尾に追加します。
処理するイメージオブジェクトのアクセス制御リスト (ACL) がパブリック読み取りまたはパブリック読み取り /書き込みの場合、イメージを処理するオブジェクトのURLにIMGパラメーターまたはイメージスタイルパラメーターを追加できます。
処理するイメージオブジェクトのACLが非公開の場合、OSS SDKを使用して、イメージを処理するためのIMG操作をオブジェクトのURLに追加できます。
デフォルトでは、URLを使用してバケット内のイメージオブジェクトにアクセスすると、イメージがダウンロードされます。 イメージオブジェクトにアクセスするときにイメージオブジェクトがプレビューされるようにするには、カスタムドメイン名をバケットにマップし、CNAMEレコードを追加する必要があります。 詳細については、「カスタムドメイン名のマップ」をご参照ください。
ACLがpublic readまたはpublic read/writeであるイメージオブジェクト
次の表に、イメージオブジェクトのURLに追加できるパラメーターを示します。
画像処理モード | IMGパラメーターの設定 | 画像スタイルパラメータの追加 |
IMG URL |
|
|
パラメーター |
|
カスタム区切り文字が指定されている場合、その区切り文字を使用して |
例 | https://image-demo.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=style/panda_style |
ACLがプライベートのイメージオブジェクト
次のコードは、一般的なプログラミング言語のOSS SDKを使用して、IMGパラメーターを使用して署名付きURLを生成する方法の例を示しています。 他のプログラミング言語のOSS SDKを使用して、IMGパラメーターを使用して署名付きURLを生成する方法の詳細については、「概要」をご参照ください。
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
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 {
// 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 object. Do not include the bucket name in the full path.
String objectName = "exampleobject.jpg";
// 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 {
// Resize the image to a height and width of 100 pixels, and rotate the image 90 degrees.
String style = "image/resize,m_fixed,w_100,h_100/rotate,90";
// Set the validity period of the signed URL to 10 minutes. (The maximum validity period is 32400 seconds.)
Date expiration = new Date(new Date().getTime() + 1000 * 60 * 10 );
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();
}
}
}
}
<?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(
// Resize the image to 100 x 100 pixels.
OssClient::OSS_PROCESS => "image/resize,m_fixed,h_100,w_100" );
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
print("rtmp url: \n" . $signedUrl);
const OSS = require("ali-oss");
const client = new OSS({
// 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 oss-cn-hangzhou.
region: "oss-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.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: "examplebucket",
});
// Set the validity period of the URL to 10 minutes and the image style to image/resize,w_300.
const signUrl = client.signatureUrl("example.png", {
expires: 600,
process: "image/resize,w_300",
});
console.log("signUrl=" + signUrl);
# -*- 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 region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
# Specify the name of the bucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# Specify the name of the bucket. Example: examplebucket.
bucket_name = 'examplebucket'
# Specify the name of the bucket in which the image is stored. 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 = 'exampledir/example.jpg'
# If the image is not stored in the specified bucket, you must upload the image to the bucket.
# bucket.put_object_from_file(key, 'D:\\localpath\\example.jpg')
# Resize the image to 100 × 100 pixels and rotate the image 90 degrees.
style = 'image/resize,m_fixed,w_100,h_100/rotate,90'
# Generate a signed object URL that includes IMG parameters. Set the validity period of the URL to 600. Unit: seconds.
url = bucket.sign_url('GET', key, 10 * 60, params={'x-oss-process': style})
print(url)
using Aliyun.OSS;
using Aliyun.OSS.Common;
// 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.
var endpoint = "yourEndpoint";
// 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.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket in which the source image is stored. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the name of the source 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/example.jpg.
var objectName = "exampledir/exampledir.jpg";
// 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.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();
// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
c.SetRegion(region);
try
{
// Resize the image to 100 × 100 pixels.
var process = "image/resize,m_fixed,w_100,h_100";
var req = new GeneratePresignedUriRequest(bucketName, objectName, SignHttpMethod.Get)
{
Expiration = DateTime.Now.AddHours(1),
Process = process
};
// Generate a signed URL.
var uri = client.GeneratePresignedUri(req);
Console.WriteLine("Generate Presigned Uri:{0} with process:{1} succeeded ", uri, process);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}
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 in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the version of the signature algorithm.
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/example.jpg.
ossImageName := "exampledir/example.jpg"
// Generate a signed URL that includes IMG parameters. Set the validity period of the signed URL to 600 seconds. (The maximum validity period is 32400 seconds.)
signedURL, err := bucket.SignURL(ossImageName, oss.HTTPGet, 600, oss.Process("image/format,png"))
if err != nil {
HandleError(err)
} else {
fmt.Println(signedURL)
}
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize information about the account that is used to access OSS. */
/* 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. */
std::string Endpoint = "yourEndpoint";
/* 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. */
std::string Region = "yourRegion";
/* Specify the name of the bucket in which the image is located. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the name of the image. If the image is not stored in the root directory of the bucket, precede the image name with the path to the image. Example: exampledir/example.jpg. */
std::string ObjectName = "exampledir/example.jpg";
/* Initialize resources such as network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* 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. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Generate a signed URL that includes IMG parameters for the object. */
std::string Process = "image/resize,m_fixed,w_100,h_100";
GeneratePresignedUrlRequest request(BucketName, ObjectName, Http::Get);
request.setProcess(Process);
/* The maximun validity period of the URL is 32400s. */
auto outcome = client.GeneratePresignedUrl(request);
if (outcome.isSuccess()) {
std::cout << "Generated presigned URL: " << outcome.result() << std::endl;
} else {
std::cout << "Failed to generate presigned URL. Error code: " << outcome.error().Code()
<< ", Message: " << outcome.error().Message()
<< ", RequestId: " << outcome.error().RequestId() << std::endl;
}
/* Release resources such as network resources. */
ShutdownSdk();
return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* 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. */
const char *endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
/* 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. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Use a char* string to initialize data of the aos_string_t type. */
aos_str_set(&options->config->endpoint, endpoint);
/* 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. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
// Specify two additional parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
options->config->is_cname = 0;
/* Configure network parameters, such as the timeout period. */
options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
/* Call the aos_http_io_initialize method in main() to initialize global resources, such as network resources and memory resources. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* Create a memory pool to manage memory. aos_pool_t is equivalent to apr_pool_t. The code used to create a memory pool is included in the APR library. */
aos_pool_t *pool;
/* Create a memory pool. The value of the second parameter is NULL. This value indicates that the pool does not inherit other memory pools. */
aos_pool_create(&pool, NULL);
/* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate the memory resources in the memory pool to the options. */
oss_client_options = oss_request_options_create(pool);
/* Initialize oss_client_options. */
init_options(oss_client_options);
/* Initialize the parameters. */
aos_string_t bucket;
aos_string_t object;
aos_table_t *params = NULL;
aos_http_request_t *req;
char *url_str;
apr_time_t now;
int64_t expire_time;
aos_str_set(&bucket, bucket_name);
aos_str_set(&object, object_name);
/* Resize the image to 100 × 100 pixels. */
params = aos_table_make(pool, 1);
apr_table_set(params, OSS_PROCESS, "image/resize,m_fixed,w_100,h_100");
req = aos_http_request_create(pool);
req->method = HTTP_GET;
req->query_params = params;
/* Specify the validity period (expire_time) in seconds. */
now = apr_time_now();
expire_time = now / 1000000 + 10 * 60;
/* Generate a signed URL. */
url_str = oss_gen_signed_url(oss_client_options, &bucket, &object, expire_time, req);
printf("url: %s\n", url_str);
/* Release the memory pool. This operation releases memory resources allocated for the request. */
aos_pool_destroy(pool);
/* Release the allocated global resources. */
aos_http_io_deinitialize();
return 0;
}
OSS SDKを使用したイメージの処理
OSS SDKでIMGパラメーターまたはイメージスタイルパラメーターを設定して、イメージを処理できます。
IMGパラメーターの設定
IMGパラメーターを使用してイメージを処理する場合は、複数のIMGパラメーターをスラッシュ (/) で区切ります。 次のコードは、一般的なプログラミング言語のOSS SDKを使用してIMGパラメーターを設定する方法の例を示しています。 他のプログラミング言語のOSS SDKを使用してIMGパラメーターを設定する方法の詳細については、「概要」をご参照ください。
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.model.GetObjectRequest;
import java.io.File;
public class Demo {
public static void main(String[] args) throws Throwable {
// 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 object. Do not include the bucket name in the full path.
String objectName = "exampleobject.jpg";
// Specify the full path to which you want to save the processed image. Example: D:\\localpath\\example-new.jpg. If a file with the same name already exists in the path, the processed image overwrites the file. Otherwise, the processed image is saved in the path.
String pathName = "D:\\localpath\\example-new.jpg";
// 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 {
// Resize the image to a height and width of 100 pixels, and rotate the image 90 degrees.
String style = "image/resize,m_fixed,w_100,h_100/rotate,90";
GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
request.setProcess(style);
// Name the processed image example-new.jpg and save the image to your local computer.
// If you specify only the name of a local file such as example-new.jpg without specifying the local path of the file, the processed image is saved to the local path of the project to which the sample program belongs.
ossClient.getObject(request, new File("D:\\localpath\\example-new.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
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";
// Specify the full path to which you want to save the processed image. Example: D:\\localpath\\example-new.jpg. If a file that has the same name already exists, the downloaded object overwrites the file. Otherwise, the downloaded object is saved in the path.
// If you specify only the name of the file such as example-new.jpg but do not specify the local path, the file is saved to the path of the project to which the sample program belongs.
$download_file = "D:\\localpath\\example-new.jpg";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
// If the image that you want to process does not exist in the specified bucket, you must upload the image to the specified bucket.
// $ossClient->uploadFile($bucket, $object, "D:\\localpath\\exampleobject.jpg");
// Resize the image to 100 × 100 pixels and rotate the image 90 degrees.
$style = "image/resize,m_fixed,w_100,h_100/rotate,90";
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => $style);
// Save the processed image as example-new.jpg to your local computer.
$ossClient->getObject($bucket, $object, $options);
// After the image is processed, you can delete the source image from the bucket if you no longer need the image.
// $ossClient->deleteObject($bucket, $object);
# -*- coding: utf-8 -*-
import os
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 region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
# Specify the name of the bucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# Specify the name of the bucket in which the source image is stored. Example: examplebucket.
bucket_name = 'examplebucket'
# Specify the name of the source image. If the image is not stored in the root directory of the bucket, you must specify the path of the image. Example: example/example.jpg.
key = 'exampledir/example.jpg'
# Specify the name of the processed image.
new_pic = 'exampledir/newexample.jpg'
# If the image that you want to process does not exist in the specified bucket, you must upload the image that is stored in the local path of the bucket.
# bucket.put_object_from_file(key, 'D:\\localpath\\example.jpg')
# Resize the image to 100 × 100 pixels, rotate the image 90 degrees, and then save the processed image to your local computer.
style = 'image/resize,m_fixed,w_100,h_100/rotate,90'
bucket.get_object_to_file(key, new_pic, process=style)
# After the image is processed, you can delete the source image from the bucket if you no longer need the image.
# bucket.delete_object(key)
# If you no longer need the processed image, you can delete the image.
# os.remove(new_pic)
;
System.IOを使用する。Aliyun.OSSを使用します。Aliyun.OSS.Common; を使用
Aliyun.OSS.Utilを使用します。名前空間ImageProcessCascade
{
class Program
{
static void Main(string[] args)
{
Program.ImageProcessCascade();
Console.ReadKey();
}
public static void ImageProcessCascade()
{
// バケットが配置されているリージョンのエンドポイントを指定します。 たとえば、バケットが中国 (杭州) リージョンにある場合、エンドポイントをhttps://oss-cn-hangzhou.aliyuncs.comに設定します。
var endpoint = "yourEndpoint";
// 環境変数からアクセス資格情報を取得します。 サンプルコードを実行する前に、OSS_ACCESS_KEY_IDおよびOSS_ACCESS_KEY_SECRET環境変数が設定されていることを確認してください。
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// ソースイメージが保存されているバケットの名前を指定します。 例: examplebucket.
var bucketName = "examplebucket";
// ソースイメージの名前を指定します。 ソースイメージがバケットのルートディレクトリに保存されていない場合は、イメージオブジェクトのフルパスを指定する必要があります。 例: exampledir/example.jpg
var objectName = "exampledir/example.jpg";
// ソースイメージのローカルのフルパスを指定します。
// var localImageFilename = "D :\\ localpath\\example.jpg";
// 処理した画像を保存するローカルディレクトリを指定します。
var downloadDir = "yourDownloadDir";
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
// ソースイメージが指定されたバケットに存在しない場合は、イメージをバケットにアップロードします。
// client.PutObject(bucketName, objectName, localImageFilename);
// 画像のサイズを100 × 100ピクセルに変更した後、画像を90度回転させます。
var process = "image/resize,m_fixed,w_100,h_100/rotate,90";
var ossObject = client.GetObject(new GetObjectRequest(bucketName, objectName, process));
// 処理されたイメージの名前を指定します。
WriteToFile(downloadDir + "/yourLocalFilename", ossObject.Content);
Console.WriteLine("Get Object:{0} with process:{1} succeeded ", objectName, process);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; エラー情報: {1} 。 \nRequestID:{2}\tHostID:{3}"、
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}
}
private static void WriteToFile(string filePath, Stream stream)
{
using (var requestStream = stream)
{
using (var fs = File.Open(filePath, FileMode.OpenOrCreate))
{
IoUtils.WriteTo(stream, fs);
}
}
}
}
}
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 in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the version of the signature algorithm.
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 source image. If the source image is not stored in the root directory of the bucket, you must specify the path of the image. Example: example/example.jpg.
sourceImageName := "exampledir/example.jpg"
// Specify the name of the processed image.
targetImageName := "exampledir/newexample.jpg"
// Resize the image to 100 × 100 pixels, rotate the image 90 degrees, and then save the image to your local computer.
style := "image/resize,m_fixed,w_100,h_100/rotate,90"
err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(style))
if err != nil {
HandleError(err)
}
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize information about the account that is used to access OSS. */
/* 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. */
std::string Endpoint = "yourEndpoint";
/* 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. */
std::string Region = "yourRegion";
/* Specify the name of the bucket in which the source image is stored. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the name of the source 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/example.jpg. */
std::string ObjectName = "exampledir/example.jpg";
/* Initialize resources such as network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* 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. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Resize the image to a height and width of 100 pixels, rotate the image 90 degrees, and save the image to your local computer. */
std::string Process = "image/resize,m_fixed,w_100,h_100/rotate,90";
GetObjectRequest request(BucketName, ObjectName);
request.setProcess(Process);
auto outcome = client.GetObject(request);
if (outcome.isSuccess()) {
std::cout << "Image processed successfully." << std::endl;
} else {
std::cout << "Failed to process image. Error code: " << outcome.error().Code()
<< ", Message: " << outcome.error().Message()
<< ", RequestId: " << outcome.error().RequestId() << std::endl;
}
/* Release resources such as network resources. */
ShutdownSdk();
return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* 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. */
const char *endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
/* 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. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Use a char* string to initialize data of the aos_string_t type. */
aos_str_set(&options->config->endpoint, endpoint);
/* 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. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
// Specify two additional parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
options->config->is_cname = 0;
/* Specify network parameters, such as the timeout period. */
options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
/* Call the aos_http_io_initialize method in main() to initialize global resources, such as network resources and memory resources. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* Create a memory pool to manage memory. aos_pool_t is equivalent to apr_pool_t. The code used to create a memory pool is included in the APR library. */
aos_pool_t *pool;
/* Create a memory pool. The value of the second parameter is NULL. This value indicates that the pool does not inherit other memory pools. */
aos_pool_create(&pool, NULL);
/* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate the memory resources in the memory pool to the options. */
oss_client_options = oss_request_options_create(pool);
/* Initialize oss_client_options. */
init_options(oss_client_options);
/* Initialize the parameters. */
aos_string_t bucket;
aos_string_t object;
aos_string_t file;
aos_table_t *headers = NULL;
aos_table_t *params = NULL;
aos_table_t *resp_headers = NULL;
aos_status_t *resp_status = NULL;
aos_str_set(&bucket, bucket_name);
aos_str_set(&object, object_name);
/* Resize the image to 100 × 100 pixels and rotate the image 90 degrees. */
params = aos_table_make(pool, 1);
apr_table_set(params, OSS_PROCESS, "image/resize,m_fixed,w_100,h_100/rotate,90");
/* Save the processed image to your local computer. */
aos_str_set(&file, "yourLocalFileName");
resp_status = oss_get_object_to_file(oss_client_options, &bucket, &object, headers, params, &file, &resp_headers);
if (aos_status_is_ok(resp_status)) {
printf("get object to file succeeded\n");
} else {
printf("get object to file failed\n");
}
/* Release the memory pool. This operation releases the memory resources allocated for the request. */
aos_pool_destroy(pool);
/* Release the allocated global resources. */
aos_http_io_deinitialize();
return 0;
}
画像スタイルを追加
イメージスタイルを指定して、指定したスタイル内にさまざまなIMGパラメーターをカプセル化し、そのスタイルを使用して複数のイメージを同時に処理できます。 次のコードは、一般的なプログラミング言語のOSS SDKを使用してイメージスタイルを使用してイメージを処理する方法の例を示しています。 他のプログラミング言語のOSS SDKを使用してイメージスタイルを使用してイメージを処理する方法の詳細については、「概要」をご参照ください。
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.model.GetObjectRequest;
import java.io.File;
public class Demo {
public static void main(String[] args) throws Throwable {
// 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 object. Do not include the bucket name in the full path.
String objectName = "exampleobject.jpg";
// Specify the full path to which you want to save the processed image. Example: D:\\localpath\\example-new.jpg. If a file with the same name already exists in the path, the processed image overwrites the file. Otherwise, the processed image is saved in the path.
String pathName = "D:\\localpath\\example-new.jpg";
// 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 {
// Use a custom image style to process the image.
// In this example, replace yourCustomStyleName with the name of the image style that you created in the OSS console.
String style = "style/yourCustomStyleName";
GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
request.setProcess(style);
// Name the processed image example-new.jpg and save the image to your local computer.
// If you specify only the name of a local file such as example-new.jpg without specifying the local path of the file, the processed image is saved to the local path of the project to which the sample program belongs.
ossClient.getObject(request, new File(pathName));
} 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
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";
// Specify the full path to which you want to save the processed image. Example: D:\\localpath\\example-new.jpg. If a file that has the same name already exists, the downloaded object overwrites the file. Otherwise, the downloaded object is saved in the path.
// If you specify only the name of the file such as example-new.jpg but do not specify the local path, the file is saved to the path of the project to which the sample program belongs.
$download_file = "D:\\localpath\\example-new.jpg";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
// If the image that you want to process does not exist in the specified bucket, you must upload the image to the specified bucket.
// $ossClient->uploadFile($bucket, $object, "D:\\localpath\\exampleobject.jpg");
// Use the custom image style to process the image.
// Set yourCustomStyleName to the name of the image style that you created in the OSS console.
$style = "style/yourCustomStyleName";
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => $style);
// Save the processed image as example-new.jpg to your local computer.
$ossClient->getObject($bucket, $object, $options);
// After the image is processed, you can delete the source image from the bucket if you no longer need the image.
// $ossClient->deleteObject($bucket, $object);
const OSS = require('ali-oss');
const client = new OSS({
// 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 oss-cn-hangzhou.
region: 'yourregion',
// 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.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: 'yourbucketname'
});
// Resize the image to 100 × 100 pixels.
async function scale() {
try {
const result = await client.get('example.jpg', './example-resize.jpg', { process: 'image/resize,m_fixed,w_100,h_100'});
} catch (e) {
console.log(e);
}
}
scale()
// Crop the image to 100 x 100 pixels starting from the position specified by the coordinate pair (100, 100).
async function cut() {
try {
const result = await client.get('example.jpg', './example-crop.jpg', { process: 'image/crop,w_100,h_100,x_100,y_100,r_1'});
} catch (e) {
console.log(e)
}
}
cut()
// Rotate the image 90 degrees.
async function rotate() {
try {
const result = await client.get('example.jpg', './example-rotate.jpg', { process: 'image/rotate,90'});
} catch (e) {
console.log(e);
}
}
rotate()
// Sharpen the image. Set the parameter to 100.
async function sharpen() {
try {
const result = await client.get('example.jpg', './example-sharpen.jpg', { process: 'image/sharpen,100'});
} catch (e) {
console.log(e);
}
}
sharpen()
// Add watermarks to the image.
async function watermark() {
try {
const result = await client.get('example.jpg', './example-watermark.jpg', { process: 'image/watermark,text_SGVsbG8g5Zu-54mH5pyN5YqhIQ'});
} catch (e) {
console.log(e);
}
}
watermark()
// Convert the format of the image.
async function format() {
try {
const result = await client.get('example.jpg', './example-format.jpg', { process: 'image/format,png'});
} catch (e) {
console.log(e);
}
}
format()
// Obtain the image information.
async function info() {
try {
const result = await client.get('example.jpg', './example-info.txt', {process: 'image/info'});
} catch (e) {
console.log(e);
}
}
info()
# -*- coding: utf-8 -*-
import os
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 region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
# Specify the name of the bucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# Specify the name of the bucket in which the source image is stored. Example: examplebucket.
bucket_name = 'examplebucket'
# Specify the name of the source image. If the image is not stored in the root directory of the bucket, you must specify the path of the image. Example: example/example.jpg.
key = 'exampledir/example.jpg'
# Specify the name of the processed image.
new_pic = 'exampledir/newexample.jpg'
# If the image that you want to process does not exist in the specified bucket, you must upload the image that is stored in the local path of the bucket.
# bucket.put_object_from_file(key, 'D:\\localpath\\example.jpg')
# Use a custom image style to process the image. Set yourCustomStyleName to the name of the image style that you created in the OSS console.
style = 'style/yourCustomStyleName'
# Save the processed image to your local computer.
bucket.get_object_to_file(key, new_pic, process=style)
# After the image is processed, you can delete the source image from the bucket if you no longer need the image.
# bucket.delete_object(key)
# If you no longer need the processed image, you can delete the image.
# os.remove(new_pic)
;
System.IOを使用する。Aliyun.OSSを使用します。Aliyun.OSS.Common; を使用
Aliyun.OSS.Utilを使用します。名前空間ImageProcessCustom
{
class Program
{
static void Main(string[] args)
{
Program.ImageProcessCustomStyle();
Console.ReadKey();
}
public static void ImageProcessCustomStyle()
{
// バケットが配置されているリージョンのエンドポイントを指定します。 たとえば、バケットが中国 (杭州) リージョンにある場合、エンドポイントをhttps://oss-cn-hangzhou.aliyuncs.comに設定します。
var endpoint = "yourEndpoint";
// 環境変数からアクセス資格情報を取得します。 サンプルコードを実行する前に、OSS_ACCESS_KEY_IDおよびOSS_ACCESS_KEY_SECRET環境変数が設定されていることを確認してください。
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// ソースイメージが保存されているバケットの名前を指定します。 例: examplebucket.
var bucketName = "examplebucket";
// ソースイメージの名前を指定します。 ソースイメージがバケットのルートディレクトリに保存されていない場合は、イメージオブジェクトのフルパスを指定する必要があります。 例: exampledir/example.jpg
var objectName = "exampledir/example.jpg";
// ソースイメージのローカルのフルパスを指定します。
// var localImageFilename = "D :\\ localpath\\example.jpg";
// 処理した画像を保存するローカルディレクトリを指定します。
var downloadDir = "yourDownloadDir";
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
// ソースイメージが指定されたバケットに存在しない場合は、イメージをバケットにアップロードします。
// client.PutObject(bucketName, objectName, localImageFilename);
// イメージスタイルを使用してイメージを処理します。 この例では、yourCustomStyleNameをOSSコンソールで作成したイメージスタイルの名前に置き換えます。
var process = "style/yourCustomStyleName";
var ossObject = client.GetObject(new GetObjectRequest(bucketName, objectName, process));
// 処理されたイメージの名前を指定します。
WriteToFile(downloadDir + "/yourLocalFilename", ossObject.Content);
Console.WriteLine("Get Object:{0} with process:{1} succeeded ", objectName, process);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; エラー情報: {1} 。 \nRequestID:{2}\tHostID:{3}"、
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}
}
private static void WriteToFile(string filePath, Stream stream)
{
using (var requestStream = stream)
{
using (var fs = File.Open(filePath, FileMode.OpenOrCreate))
{
IoUtils.WriteTo(stream, fs);
}
}
}
}
}
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 in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the version of the signature algorithm.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// 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 image. Example: example/example.jpg.
sourceImageName := "example/example.jpg"
// Save the processed image as newexample.jpg to your local computer.
targetImageName := "D:\\localpath\\newexample.jpg"
// Use an image style to process the image. Set yourCustomStyleName to the name of the image style that you created in the OSS console.
style := "style/yourCustomStyleName"
// Save the processed image to your local computer.
err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(style))
if err != nil {
HandleError(err)
}
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize information about the account that is used to access OSS. */
/* 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. */
std::string Endpoint = "yourEndpoint";
/* 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. */
std::string Region = "yourRegion";
/* Specify the name of the bucket in which the source image is stored. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the name of the source 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/example.jpg. */
std::string ObjectName = "exampledir/example.jpg";
/* Initialize resources such as network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* 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. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Use the image style to process the image. Replace yourCustomStyleName with the name of the image style that you created in Step 1. */
std::string Process = "style/yourCustomStyleName";
GetObjectRequest request(BucketName, ObjectName);
request.setProcess(Process);
auto outcome = client.GetObject(request);
if (outcome.isSuccess()) {
std::cout << "Image processed successfully." << std::endl;
} else {
std::cout << "Failed to process image. Error code: " << outcome.error().Code()
<< ", Message: " << outcome.error().Message()
<< ", RequestId: " << outcome.error().RequestId() << std::endl;
}
/* Release resources such as network resources. */
ShutdownSdk();
return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* 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. */
const char *endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
/* 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. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Use a char* string to initialize data of the aos_string_t type. */
aos_str_set(&options->config->endpoint, endpoint);
/* 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. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
// Specify two additional parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
options->config->is_cname = 0;
/* Specify network parameters, such as the timeout period. */
options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
/* Call the aos_http_io_initialize method in main() to initialize global resources, such as network resources and memory resources. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* Create a memory pool to manage memory. aos_pool_t is equivalent to apr_pool_t. The code used to create a memory pool is included in the APR library. */
aos_pool_t *pool;
/* Create a memory pool. The value of the second parameter is NULL. This value indicates that the pool does not inherit other memory pools. */
aos_pool_create(&pool, NULL);
/* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate the memory resources in the memory pool to the options. */
oss_client_options = oss_request_options_create(pool);
/* Initialize oss_client_options. */
init_options(oss_client_options);
/* Initialize the parameters. */
aos_string_t bucket;
aos_string_t object;
aos_string_t file;
aos_table_t *headers = NULL;
aos_table_t *params = NULL;
aos_table_t *resp_headers = NULL;
aos_status_t *resp_status = NULL;
aos_str_set(&bucket, bucket_name);
aos_str_set(&object, object_name);
/* Specify the image style. */
params = aos_table_make(pool, 1);
/* Set yourCustomStyleName to the name of the image style that you created in Step 1. */
apr_table_set(params, OSS_PROCESS, "style/yourCustomStyleName");
/* Save the processed image to your local computer. */
aos_str_set(&file, "yourLocalFileName");
resp_status = oss_get_object_to_file(oss_client_options, &bucket, &object, headers, params, &file, &resp_headers);
if (aos_status_is_ok(resp_status)) {
printf("get object to file succeeded\n");
} else {
printf("get object to file failed\n");
}
/* Release the memory pool. This operation releases the memory resources allocated for the request. */
aos_pool_destroy(pool);
/* Release the allocated global resources. */
aos_http_io_deinitialize();
return 0;
}
RESTful APIの使用
ビジネスで高度なカスタマイズが必要な場合は、RESTful APIを直接呼び出すことができます。 APIを直接呼び出すには、コードに署名計算を含める必要があります。
GetObjectリクエストにIMGパラメーターまたはイメージスタイルパラメーターを追加して、イメージを処理できます。 詳細については、「GetObject」をご参照ください。
IMGパラメーターの設定
サンプルリクエスト:
GET /oss.jpg?x-oss-process=image/resize,w_100 HTTP/1.1 Host: oss-example.oss-cn-hangzhou.aliyuncs.com Date: Fri, 28 Oct 2022 06:40:10 GMT Authorization: OSS qn6qrrqxo2oawuk53otf****:UNQDb7GapEgJkcde6OhZ9J****
画像スタイルパラメータの追加
サンプルリクエスト:
GET /oss.jpg?x-oss-process=style/styleexample HTTP/1.1 Host: oss-example.oss-cn-hangzhou.aliyuncs.com Date: Fri, 28 Oct 2022 06:40:10 GMT Authorization: OSS qn6qrrawuk53oqxo2otf****:UNapEgQDb7GJkcde6OhZ9J****
参考資料
デフォルトでは、IMGは処理済み画像を保存しません。 ただし、OSSでは、saveasパラメーターをIMGリクエストに追加して、処理されたイメージをオブジェクトとして指定されたバケットに保存できます。 詳細については、「処理済みイメージの保存」をご参照ください。