Updated on 2024-11-05 GMT+08:00

Image Processing Persistency

Image processing persistency allows the images after processing to be synchronously stored in a specified OBS bucket, so that you can directly access the stored images to save time.

You can use image processing persistency only by making API calls. In an image processing request, the persistency should be configured in the Parameter name=Parameter value format. Table 1 describes the parameters.

Table 1 Image processing persistency parameters

Parameter

Value

Description

x-image-save-object

objectName

Mandatory

It specifies the name of the processed image that will be stored in the bucket.

An object name:

  • cannot contain the following special characters: \ : * ? " < > |
  • must be 1 to 1023 characters long.

x-image-save-bucket

bucketName

Optional

It specifies the bucket that will store the processed image. If this parameter is not specified, the processed image will be saved in the bucket where the original image is processed.

The bucket must be an existing one in OBS and its name must be 1 to 64 characters long.

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", Base64.getUrlEncoder().encodeToString(objectName.getBytes(StandardCharsets.UTF_8)));     
    queryParams.put("x-image-save-bucket", Base64.getUrlEncoder().encodeToString(bucketName.getBytes(StandardCharsets.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
import base64

# 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.urlsafe_b64encode(targetObjectName.encode()).decode()
    # Optional parameter
    queryParams["x-image-save-bucket"]=base64.urlsafe_b64encode(targetBucketName.encode()).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';

// Base64 encoding
function encodeBase64Url(str) {
  return Buffer.from(str, 'utf8')
    .toString('base64')
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=+$/g, '')
}

const queryParams = {
    "x-image-process": "image/resize,w_100",
    "x-image-save-object": encodeBase64Url(targetObjectName),
    // Optional parameter
    "x-image-save-bucket": encodeBase64Url(targetBucketName)
}

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 || {}
});
  • Object and bucket names must be URL-safe Base64 encoded in the encodedObject = url_safe_base64_encode(name) format. 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.