Skip to main content

Image Processing

Image Processing provides multiple image processing functions, including intelligent cropping, lossless compression, watermarking, format conversion, etc. You can easily manage files through the extended SDK.

Features

For applications with a large number of user image uploads, the image processing extension can provide users with convenient services such as cropping, compression, watermarking, etc., to adapt to various business scenarios.

TypeDescription
ScalingProportional scaling, target width/height scaling, and various other methods
CroppingRegular cropping, scaled cropping, inscribed circle, intelligent face cropping
RotationRegular rotation, adaptive rotation
Format conversionjpg, bmp, gif, png, webp, yjpeg format conversion, GIF format optimization, progressive display
Quality adjustmentAdjusts the quality for JPG and WEBP images
Gaussian blurApplies blur processing to images
SharpeningApplies sharpening processing to images
Image watermarkingProvides image watermarking processing functionality
Text watermarkingProvides real-time text watermarking processing functionality
Get basic image informationQueries basic image information including format, height, width, etc.
Get image EXIFQueries image EXIF information, such as photo shooting parameters, thumbnails, etc.
Get image dominant colorObtains the dominant color information of images
Remove metadataRemoves image metadata to reduce image size
Quick thumbnail templateQuickly implements image format conversion, thumbnail generation, cropping, and other functions to generate thumbnails
Pipeline operatorApplies multiple processing steps to images sequentially

!You can use this extension capability not only in Cloud Functions but also on the client side. The file read-write permission policies are consistent with Cloud Storage, reducing your additional permission management efforts.

Prerequisites

CloudBase has been provisioned.

Extension Configuration Information

You can configure the following parameters:

  • Environment ID: Select the environment to deploy to, specifying where it will be used.

Billing

This extension uses CloudBase or other Tencent Cloud services, which may incur relevant fees:

When using CloudBase extensions, you only pay for the cloud resources you consume; CloudBase is billed separately from other cloud resources. You can view detailed information in the Billing Center.

Enabled APIs and Created Resources

  • Type: Cloud Infinite Description: Provides developers with intelligent processing services for images, videos, and other types of data.
  • Type: Cloud Storage Description: Storing images and improving their loading speed via CDN.
  • Type: Cloud Function Description: Detects image processing parameters and generates signatures for image processing to ensure the legitimacy of operations.

Permission Granting

Primary Account

Role NameAuthorization Policy NameRole TypeDescription
CI_QCSRoleQcloudAccessForCIRole, QcloudCOSDataFullControlService RoleCloud Infinite (CI) will access your Tencent Cloud resources, including reading, modifying, deleting, listing, etc. of COS data.
TCB_QcsRoleQcloudCIFullAccessService RoleCloudBase (TCB) will operate on your Cloud Infinite (CI) resources to facilitate your use of this service in extension capabilities.

Sub-account

If you want a sub-account to be able to use this extension, you need to grant the following permissions to the sub-account:

  • Policy: QcloudAccessForTCBRole Description: Access permissions for CloudBase (TCB) to cloud resources.
  • Policy: QcloudCIFullAccess Description: Full read-write access permissions for Cloud Infinite (CI).

Install Extension

You can install and manage extensions via the CloudBase Console.

Use Extension

! If you use this extension on a web website, first add the website domain as a security domain for the current environment in the CloudBase Console.

Process During Image Retrieval

If your images are already uploaded to cloud storage, you can process them by adding parameters to the url and automatically obtain the processed results. For example, to scale the image to 50% of its original dimensions:

https://${your CloudBase file access domain, format: xxx.tcb.qcloud.la}/sample.jpeg?imageMogr2/thumbnail/!50p

The supported image processing features and parameter concatenation formats are as follows:

TypeParameter Concatenation Guide
ScalingParameter Concatenation Rules
CroppingParameter Concatenation Rules
RotationParameter Concatenation Rules
Format ConversionParameter Concatenation Rules
Quality TransformationParameter Concatenation Rules
Gaussian BlurParameter Concatenation Rules
SharpeningParameter Concatenation Rules
Image WatermarkParameter Concatenation Rules
Text WatermarkParameter Concatenation Rules
Get Image Basic InformationParameter Concatenation Rules
Get Image EXIFParameter Concatenation Rules
Get Image Dominant ColorParameter Concatenation Rules
Strip MetadataParameter Concatenation Rules
Quick Thumbnail TemplateParameter Concatenation Rules
Pipe OperatorParameter Concatenation Rules

Persistent Image Processing

1. Install the extension SDK to your project

npm install --save @cloudbase/extension-ci@latest

2. Invoke the extension SDK

Invocation Parameters

NameTypeRequiredDescription
actionStringYesOperation type, pass: ImageProcess
cloudPathStringYesAbsolute path of the file, same as in tcb.uploadFile
fileContentUint8Array or BufferNoFile content. If provided, processes the image during upload; if empty, processes an already uploaded image.
operationsObjectNoImage processing parameters

operations node content

NameTypeRequiredDescription
rulesArray.<Rule object>YesProcessing style

Rule node content

NameTypeRequiredDescription
fileidStringYesFile path of the processed result. If starting with '/', saves to specified folder; otherwise saves to same directory as original image file.
ruleStringYesProcessing style parameter, consistent with the parameters concatenated in the url for image processing during download.

Response

Parameter NameTypeDescription
UploadResultObjectOriginal image information

UploadResult node content:

Parameter NameTypeDescription
ProcessResultsObjectImage processing results

ProcessResults node content:

Node NameTypeDescription
ObjectObjectEach image processing result

Object node content:

Node NameTypeDescription
KeyStringFile name
LocationStringImage path
FormatStringImage format
WidthIntImage width
HeightIntImage height
SizeIntImage size
QualityIntImage quality

Invoke Example

Client Usage:

const extCi = require("@cloudbase/extension-ci");
const tcb = require("@cloudbase/js-sdk");
const readFile = async function (file) {
let reader = new FileReader();
let res = await new Promise((resolve) => {
reader.onload = function (e) {
let arrayBuffer = new Uint8Array(e.target.result);
resolve(arrayBuffer);
};
reader.readAsArrayBuffer(file);
});
return res;
};
let file = document.getElementById("selectFile").files[0];
let fileContent = await readFile(file);

Usage in Cloud Functions:

const extCi = require("@cloudbase/extension-ci");
const tcb = require("@cloudbase/node-sdk");
let fileContent = imageBuffer; // Uint8Array|Buffer format image content

You can choose to use it in [client] or [cloud functions] as needed, and then invoke it with the following code:

const app = tcb.init({
env: "Your Environment ID"
});
app.registerExtension(extCi);

async function process() {
try {
const opts = {
rules: [
{
// File path of the processed result. If starting with '/', saves to specified folder; otherwise saves to same directory as original image file.
fileid: "/image_process/demo.jpeg",
rule: "imageView2/format/png" // Processing style parameter, consistent with the parameters concatenated in the url for image processing during download.
}
]
};
const res = await app.invokeExtension("CloudInfinite", {
action: "ImageProcess",
cloudPath: "demo.jpeg", // Absolute path of the stored image, same as in tcb.uploadFile
fileContent, // This field is optional. File content: Uint8Array|Buffer. If provided, processes the image during upload; if empty, processes an already uploaded image.
operations: opts
});
console.log(JSON.stringify(res.data, null, 4));
} catch (err) {
console.log(JSON.stringify(err, null, 4));
}
}