Updated on 2024-03-04 GMT+08:00

Image Persistency

With image persistency, images are asynchronously stored in the specified OBS bucket, so that you can access the processed images directly for a better experience.

Currently, this function can be used only by coding or calling the API. In the image processing request interface, the image processing persistency request is sent in the format of parameter name = parameter value. Table 1 describes the parameters.

Table 1 Persistency

Parameter

Value

Description

x-image-save-object

objectName

This parameter is mandatory.

Specifies the name of the target object, that is, the name of the processed image that will be stored in the bucket.

Object naming requirements are as follows:

  • The value cannot contain the following special characters: \:*?"<>|
  • The value ranges from 1 to 1023 characters.

x-image-save-bucket

bucketName

This parameter is optional.

Specifies the target bucket. The processed images are stored in the bucket. If this parameter is not specified, the images are saved to the current bucket by default.

The bucket name ranges from 1 to 64 characters and must an existing bucket in OBS.

Java Sample Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
ObsClient obsClient = null;
String endPoint = "obs-endpoint";  // Current region
// Hard-coded or plaintext AK and SK are risky. For security purposes, encrypt your AK and SK and store them in the configuration file or environment variables.
// In this example, the AK and SK are stored in environment variables for identity authentication. Before running this example, configure environment variables ACCESS_KEY_ID and SECRET_ACCESS_KEY.
// Obtain an AK and SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
String ak = System.getenv("ACCESS_KEY_ID");
String sk = System.getenv("SECRET_ACCESS_KEY");
try {    
    ObsConfiguration config = new ObsConfiguration();    
    config.setEndPoint(endPoint);   
    obsClient = new ObsClient(ak,sk ,config);    
    TemporarySignatureRequest request = new TemporarySignatureRequest(); 
    request.setObjectKey("test.jpeg");  // Original object name before processing
    Map<String, Object> queryParams = new HashMap<>();    
    queryParams.put("x-image-process", "image/resize,w_100");   
    String objectName = "your saves objectName";  // Name of the processed object
    //Optional parameters
    String bucketName = "your saves Bucket";  // Bucket that stores the processed object
    queryParams.put("x-image-save-object", ServiceUtils.toBase64(objectName.getBytes("UTF-8")));     
    queryParams.put("x-image-save-bucket", ServiceUtils.toBase64(bucketName.getBytes("UTF-8")));     
    request.setQueryParams(queryParams);    
    request.setBucketName("your bucket");  // Bucket that stores the original object
    TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
    //URL to access
    response.getSignedUrl();
 } catch (Exception e) {
...//Handle exceptions.
 } finally {
     if (obsClient != null) {
         obsClient.close();   
      }
 }

Python Sample Code
from obs import ObsClient
import os
import traceback
import requests

# Obtain an AK and SK pair using environment variables or import the AK and SK pair in other ways. Using hard coding may result in leakage.
# Obtain an AK and SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# (Optional) If you use a temporary AK and SK pair and a security token to access OBS, obtain them from environment variables.
security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. CN-Hong Kong (ap-southeast-1) is used here as an example. Replace it with the one in use.
server = "https://obs.ap-southeast-1.myhuaweicloud.com"
# Create an obsClient instance.
# If you use a temporary AK and SK pair and a security token to access OBS, you must specify security_token when creating an instance.
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    # Generate a signed URL for image persistency.
    # Name of the bucket that stores the original object
    bucketName = 'originBucketName'; 
    # Original object name
    objectKey = 'test.png';

    # Name of the object after processing
    targetObjectName ="save.png"
    # (Optional) Name of the bucket that stores the new object
    targetBucketName ="saveBucketName"
    queryParams={}
    queryParams["x-image-process"]="image/resize,w_100"
    queryParams["x-image-save-object"]=base64.b64encode(targetObjectName .encode("utf-8")).decode()
    # Optional parameter
    queryParams["x-image-save-bucket"]=base64.b64encode(targetBucketName .encode("utf-8")).decode()

    res = obsClient.createSignedUrl(method='GET', bucketName=bucketName, objectKey=objectKey, queryParams=queryParams, expires=3600)
    print('signedUrl:', res.signedUrl)
    print('actualSignedRequestHeaders:', res.actualSignedRequestHeaders)
    // Make a GET request for image persistency.
    r = requests.get(resp.signedUrl)
    print(r)
except:
    print(traceback.format_exc())

Node.js Sample Code

// Import the OBS library.
const ObsClient = require('esdk-obs-nodejs');
const https = require('https');
const http = require('http');
const urlLib = require('url');

// Hard-coded or plaintext AK and SK are risky. For security purposes, encrypt your AK and SK and store them in the configuration file or environment variables.
// In this example, the AK and SK are stored in environment variables for identity authentication. Before running this example, configure environment variables ACCESS_KEY_ID and SECRET_ACCESS_KEY.
// Obtain an AK and SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
const ak = process.env.ACCESS_KEY_ID; 
const sk = process.env.SECRET_ACCESS_KEY;
const server = "obs-endpoint";  // Current region

// Create an ObsClient instance.
const obsClient = new ObsClient({
    access_key_id: ak,
    secret_access_key: sk,
    server: server
});

// Name of the bucket that stores the original object
const bucketName = 'originBucketName';
// Original object name
const objectKey = 'test.png';
const method = 'GET';

// Name of the object after processing
const targetObjectName = "save.png"; 
// (Optional) Name of the bucket that stores the new object
const targetBucketName = 'saveBucketName';

const queryParams = {
    "x-image-process": "image/resize,w_100",
    "x-image-save-object": Buffer.from(targetObjectName, 'utf8').toString('base64'),
    // Optional parameter
    "x-image-save-bucket": Buffer.from(targetBucketName, 'utf8').toString('base64')
}

const res = obsClient.createSignedUrlSync({
    Method: method,
    Bucket: bucketName,
    Key: objectKey,
    QueryParams: queryParams
});

// Make a GET request for image persistency.
const url = urlLib.parse(res.SignedUrl);
const request = server.startsWith('http://') ? http : https;
const req = request.request({
    method: method,
    host: url.hostname,
    port: url.port,
    path: url.path,
    rejectUnauthorized: false,
    headers: res.ActualSignedRequestHeaders || {}
});
  • The object name and bucket name must be Base64 encoded and URL safe. The format is encodedObject = url_safe_base64_encode(name). For example, object panda.png will be encoded as cGFuZGEucG5n. After Base64 encoding, if the name contains plus signs (+) and slashes (/), replace them with hyphens (-) and underscores (_), respectively.
  • If a signature matching error is reported, check whether the AK and SK pair is correct and whether the accessed URL is the same as the signature URL generated by the code.
  • Currently, image persistency with the range header is not supported.