By default, Image Processing (IMG) does not save processed images. You must add the saveas parameter to an IMG request to save a processed image to a specified bucket as an object.
Usage notes
- Required permissions
To save a processed image, you must have the
oss:PostProcessTask
permission on the source bucket in which the source image is stored, theoss:PutBucket
permission on the destination bucket to which you want to save the processed image, and theoss:PutObject
permission on the object as which you want to store the processed image. - Region
You can save the processed image to the same bucket in which the source image is stored or to a different bucket. However, the source bucket and the destination bucket must belong to the same Alibaba Cloud account and must be in the same region.
- Storage method
- If you add the saveas parameter to an IMG request, you can save images that are processed by using Object Storage Service (OSS) SDKs to a specified bucket. For more information about how to save processed images by using OSS SDKs, see Use OSS SDKs.
- Images that are processed by using object URLs cannot be directly saved to a specified bucket. You can save the processed images to your computer and then upload them to the specified bucket.
- ACL
The access control list (ACL) of the processed image is the same as that of the bucket to which you want to save the image and cannot be customized.
- Storage duration
If you want to store the processed image for a specific duration, configure a lifecycle rule for the image object to specify the time when the object expires. For more information, see Lifecycle rules based on the last modified time.
Use OSS SDKs
The following code provides examples on how to save processed images by using OSS SDKs for common programming languages. For more information about how to save processed images by using OSS SDKs for other programming languages, see Overview.
import com.aliyun.oss.*;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.GenericResult;
import com.aliyun.oss.model.ProcessObjectRequest;
import java.util.Formatter;
public class Demo {
public static void main(String[] args) throws Throwable {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify the actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to access OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. The full path cannot contain the name of the bucket.
String sourceImage = "exampleimage.png";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// Resize the image to a height and width of 100 pixels.
StringBuilder sbStyle = new StringBuilder();
Formatter styleFormatter = new Formatter(sbStyle);
String styleType = "image/resize,m_fixed,w_100,h_100";
// Name the processed image example-resize.png and save the image to the bucket in which the source image is stored.
// Specify the full path of the object. The full path cannot contain the name of the bucket.
String targetImage = "example-resize.png";
styleFormatter.format("%s|sys/saveas,o_%s,b_%s", styleType,
BinaryUtil.toBase64String(targetImage.getBytes()),
BinaryUtil.toBase64String(bucketName.getBytes()));
System.out.println(sbStyle.toString());
ProcessObjectRequest request = new ProcessObjectRequest(bucketName, sourceImage, sbStyle.toString());
GenericResult processResult = ossClient.processObject(request);
String json = IOUtils.readStreamAsString(processResult.getResponse().getContent(), "UTF-8");
processResult.getResponse().getContent().close();
System.out.println(json);
} 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\OssClient;
// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
$accessKeyId = "yourAccessKeyId";
$accessKeySecret = "yourAccessKeySecret";
// Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set yourEndpoint 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 source object. Example: exampledir/exampleobject.jpg. The full path of the object cannot contain the bucket name.
$object = "exampledir/exampleobject.jpg";
// Specify the full path that is used to store the processed image. Example: example-new.jpg.
$save_object = "example-new.jpg";
function base64url_encode($data)
{
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);
// If the image does not exist in the required bucket, you must upload the image to the required bucket.
// $ossClient->uploadFile($bucket, $object, "D:\\localpath\\exampleobject.jpg");
// After you resize the image to the height and width of 100 pixels, rotate the image 90 degrees.
$style = "image/resize,m_fixed,w_100,h_100/rotate,90";
$process = $style.
'|sys/saveas'.
',o_'.base64url_encode($save_object).
',b_'.base64url_encode($bucket);
// Name the processed image example-new.png and save the image to the current bucket.
$result = $ossClient->processObject($bucket, $object, $process);
// Display the processed result.
print($result);
const OSS = require('ali-oss');
const client = new OSS({
bucket: '<Your BucketName>',
// 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: '<Your Region>',
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
accessKeyId: '<Your AccessKeyId>',
accessKeySecret: '<Your AccessKeySecret>',
});
const sourceImage = 'sourceObject.png';
const targetImage = 'targetObject.jpg';
async function processImage(processStr, targetBucket) {
const result = await client.processObjectSave(
sourceImage,
targetImage,
processStr,
targetBucket
);
console.log(result.res.status);
}
// Resize the image.
processImage("image/resize,m_fixed,w_100,h_100")
// Crop the image.
processImage("image/crop,w_100,h_100,x_100,y_100,r_1")
// Rotate the image.
processImage("image/rotate,90")
// Sharpen the image.
processImage("image/sharpen,100")
// Add watermarks to the image.
processImage("image/watermark,text_SGVsbG8g5Zu-54mH5pyN5YqhIQ")
// Convert the format of the image.
processImage("image/format,jpg")
// Convert the format of the image and configure the destination bucket that is used to save the processed image.
processImage("image/format,jpg", "<target bucket>")
# -*- coding: utf-8 -*-
import os
import base64
import oss2
# 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'
# The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to access OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
access_key_id = 'yourAccessKeyId'
access_key_secret = 'yourAccessKeySecret'
# Specify the name of the bucket in which the source image is stored.
source_bucket_name = 'srcbucket'
# Specify the name of the bucket to which the processed image is saved. The bucket must be within the same region as the bucket that stores the source image.
taget_bucket_name = 'destbucket'
# Specify the name of the source image. If the image is not stored in the root directory of the bucket, you must add the full path of the image. Example: example/example.jpg.
source_image_name = 'example/example.jpg'
# Specify the bucket instance. You must use the bucket instance to call all object-related methods.
bucket = oss2.Bucket(oss2.Auth(access_key_id, access_key_secret), endpoint, source_bucket_name)
# Resize the image to a height and width of 100 pixels.
style = 'image/resize,m_fixed,w_100,h_100'
# Specify the name of the processed image. If the image is not stored in the root directory of the bucket, you must add the full path of the image. Example: exampledir/example.jpg.
target_image_name = 'exampledir/example.jpg'
process = "{0}|sys/saveas,o_{1},b_{2}".format(style,
oss2.compat.to_string(base64.urlsafe_b64encode(oss2.compat.to_bytes(target_image_name))),
oss2.compat.to_string(base64.urlsafe_b64encode(oss2.compat.to_bytes(taget_bucket_name))))
result = bucket.process_object(source_image_name, process)
print(result)
// fromBucket indicates the name of the source bucket. toBucket indicates the name of the destination bucket.
// fromObjectKey indicates the names of the source object. toObjectkey indicates the destination object. Their names must be a complete path including the file suffix. Example: abc/efg/123.jpg.
// action indicates the IMG operation.
ImagePersistRequest request = new ImagePersistRequest(fromBucket,fromObjectKey,toBucket,toObjectkey,action);
OSSAsyncTask task = mOss.asyncImagePersist(request, new OSSCompletedCallback<ImagePersistRequest, ImagePersistResult>() {
@Override
public void onSuccess(ImagePersistRequest request, ImagePersistResult result) {
// sucess callback
}
@Override
public void onFailure(ImagePersistRequest request, ClientException clientException, ServiceException serviceException) {
// errror callback
}
});
package main
import (
"fmt"
"os"
"encoding/base64"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func HandleError(err error) {
fmt.Println("Error:", err)
os.Exit(-1)
}
func main() {
// Create an OSSClient instance.
// Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify the actual endpoint.
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to access OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
if err != nil {
HandleError(err)
}
// Specify the name of the bucket in which the source image is stored. Example: srcbucket.
bucketName := "srcbucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
HandleError(err)
}
// 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: example/example.jpg.
sourceImageName := "example/example.jpg"
// Specify the bucket that stores the processed image. The bucket must be within the same region as the bucket in which the source image is stored.
targetBucketName := "destbucket"
// Specify the name of the processed 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.
targetImageName = "exampledir/example.jpg"
// Resize the image to a height and width of 100 pixels and save the image to the specified bucket.
style = "image/resize,m_fixed,w_100,h_100"
process = fmt.Sprintf("%s|sys/saveas,o_%v,b_%v", style, base64.URLEncoding.EncodeToString([]byte(targetImageName)), base64.URLEncoding.EncodeToString([]byte(targetBucketName)))
result, err = bucket.ProcessObject(sourceImageName, process)
if err != nil {
HandleError(err)
} else {
fmt.Println(result)
}
}
OSSImagePersistRequest *request = [OSSImagePersistRequest new];
request.fromBucket = _privateBucketName;
request.fromObject = OSS_IMAGE_KEY;
request.toBucket = _privateBucketName;
request.toObject = @"image_persist_key";
request.action = @"image/resize,w_100";
//request.action = @"resize,w_100";
[[[ossClient imageActionPersist:request] continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
return nil;
}] waitUntilFinished];
#include <alibabacloud/oss/OssClient.h>
#include <sstream>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize OSS account information. */
/* The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. */
std::string AccessKeyId = "yourAccessKeyId";
std::string AccessKeySecret = "yourAccessKeySecret";
/* 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 name of the bucket. 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: example/example.jpg. */
std::string SourceObjectName = "example/example.jpg";
/* Specify the name of the processed 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 TargetObjectName = "exampledir/example.jpg";
/* Initialize resources such as network resources. */
InitializeSdk();
ClientConfiguration conf;
OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);
/* Resize the image to a height and width of 100 pixels and save the image to the bucket in which the source image is stored. */
std::string Process = "image/resize,m_fixed,w_100,h_100";
std::stringstream ss;
ss << Process
<<"|sys/saveas"
<< ",o_" << Base64EncodeUrlSafe(TargetObjectName)
<< ",b_" << Base64EncodeUrlSafe(BucketName);
ProcessObjectRequest request(BucketName, SourceObjectName, ss.str());
auto outcome = client.ProcessObject(request);
/* Release resources such as network resources. */
ShutdownSdk();
return 0;
}
Use the RESTful API
If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code.
To process an image, you can call PostObject and pass x-oss-process in the message body of the PostObject request. Then, add the saveas parameter to the request to save the processed image to a specified bucket. For more information, see PostObject.
Option | Description |
---|---|
o | The name of the object as which you want to store the processed image. The value of this option must be URL-safe Base64-encoded. For more information, see Encode watermarks. |
b | The name of the bucket to which you want to save the processed image. The value of this option must be URL-safe Base64-encoded. If this option is not specified, the processed image is saved to the current bucket. |
You can use the following methods to process an image and save the processed image to a specified bucket:
- The following code provides an example on how to configure IMG parameters to process
an image and save the processed mage to a specified bucket:
POST /ObjectName?x-oss-process HTTP/1.1 Host: oss-example.oss.aliyuncs.com Content-Length: 247 Date: Fri, 04 May 2012 03:21:12 GMT Authorization: OSS qn6qrrqxo2oawuk53otf****:KU5h8YMUC78M30dXqf3JxrT****= // Proportionally resize the source image named test.jpg to a width of100 pixels and then save the processed image to a bucket named test. x-oss-process=image/resize,w_100|sys/saveas,o_dGVzdC5qcGc,b_dGVzdA
- The following code provides an example on how to use an image style to process an
image and save the processed image to a specified bucket:
POST /ObjectName?x-oss-process HTTP/1.1 Host: oss-example.oss.aliyuncs.com Content-Length: 247 Date: Fri, 04 May 2012 03:22:13 GMT Authorization: OSS qn6qrrqxo2oawuk53otf****:KU5h8YMUC78M30dXqf3JxrT****= // Use an image style named examplestyle to process the source image named test.jpg and then save the processed image to a bucket named test. x-oss-process=style/examplestyle|sys/saveas,o_dGVzdC5qcGc,b_dGVzdA