Cloud Infinite

Cloud Infinite
SDK Documentation
Product Documentation©2013-2022 Tencent Cloud. All rights reserved.

Page 1 of 1869

Cloud Infinite

Copyright Notice©2013-2024 Tencent Cloud. All rights reserved.
Copyright in this document is exclusively owned by Tencent Cloud. You must not reproduce, modify, copy or distributein any way, in whole or in part, the contents of this document without Tencent Cloud's the prior written consent.
Trademark Notice

All trademarks associated with Tencent Cloud and its services are owned by Tencent Cloud Computing (Beijing)
Company Limited and its affiliated companies. Trademarks of third parties referred to in this document are owned bytheir respective proprietors.
Service Statement
This document is intended to provide users with general information about Tencent Cloud's products and services
only and does not form part of Tencent Cloud's terms and conditions. Tencent Cloud's products or services are
subject to change. Specific products and services and the standards applicable to them are exclusively provided for in
Tencent Cloud's applicable terms and conditions.

©2013-2022 Tencent Cloud. All rights reserved.

Page 2 of 1869

Cloud Infinite

Contents
SDK Documentation
SDK Overview
Android SDK
Getting Started
Basic Image Processing
Image Processing
Loading Image with Glide
Loading TPG Image
Loading AVIF ImageiOS SDK
Getting Started
Loading TPG Image
Basic Image Processing
Image Processing
COS Android SDK
Content Moderation
Image Moderation
Video Moderation
Audio Moderation
Text Moderation
File Moderation
C SDK
Getting Started
Image Processing
Persistent Image Processing
Basic Image Processing
Image Advanced Compression
Media Processing
Media Bucket APIsMedia Information APIsMedia Screenshot APIs
Content Moderation
Video Moderation
Content Recognition
QR Code Recognition©2013-2022 Tencent Cloud. All rights reserved.

Page 3 of 1869

Cloud Infinite

C++ SDK
Getting Started
Image Processing
Persistent Image Processing
Basic Image Processing
Blind Watermark
Media Processing
Media Bucket APIsMedia Information APIsMedia Screenshot APIs
Content Moderation
Image Moderation
Video Moderation
Audio Moderation
Text Moderation
File Moderation
Webpage Moderation.NET(C#) SDK
Getting Started
Image Processing
Basic Image Processing
Blind Watermark
Media Processing
Media Bucket APIsMedia Information APIsMedia Screenshot APIs
Content Moderation
Image Moderation
Video Moderation
Audio Moderation
File Moderation
Text Moderation
Go SDK
Getting Started
Image Processing
Persistent Image Processing
Basic Image Processing
Image Advanced Compression©2013-2022 Tencent Cloud. All rights reserved.

Page 4 of 1869

Cloud Infinite

Guetzli Compression
Blind Watermark
CI Service
Original Image Protection
Media Processing
Media Bucket APIsMedia Information APIsMedia Screenshot APIs
File Preview
Querying Document Preview Feature Status
Sync Request API
Async Processing Queue APIs
Async Processing Job APIs
File-to-HTML Conversion
Content Moderation
Image Moderation
Video Moderation
Audio Moderation
Text Moderation
AI-Based Content Recognition
Image QR CodeFile Processing
File Decompression
Multi-File Zipping
Hash Calculation
COS iOS SDKContent Moderation
Image Moderation
Video Moderation
Audio Moderation
Text Moderation
File Moderation
Webpage Moderation
Java SDK
Getting Started
FAQs
Image Processing
Basic Image Processing©2013-2022 Tencent Cloud. All rights reserved.

Page 5 of 1869

Cloud Infinite

Persistent Image Processing
Image Advanced Compression
Blind Watermark
AI-Based Content Recognition
Image Tagging
Vehicle Recognition
Media Processing
Template Operations
Workflow Operations
Video Frame Capturing
File Preview
Generating Sync Preview URL
Content Moderation
Image Moderation
Video Moderation
Audio Moderation
File Moderation
Text Moderation
Callback Information Processing
Troubleshooting
File Processing
Hash Calculation
JavaScript SDK
Getting Started
Image Processing
Basic Image Processing
Blind Watermark
Media Processing
Media Bucket APIsMedia Information APIsMedia Screenshot APIs
Content Moderation
Image Moderation
Video Moderation
Audio Moderation
Text Moderation
Webpage Moderation
File Processing©2013-2022 Tencent Cloud. All rights reserved.

Page 6 of 1869

Cloud Infinite

File Decompression
Multi-File Zipping
Hash Calculation
Node.js SDK
Getting Started
Image Processing
Basic Image Processing
Blind Watermark
Media Processing
Media Bucket APIsMedia Information APIsMedia Screenshot APIsPHP SDK
Getting Started
Image Processing
Basic Image Processing
Image Style
Persistent Image Processing
Blind Watermark
Image Advanced Compression
Guetzli Compression
Media Processing
Media Bucket APIsMedia Information APIsMedia Screenshot APIs
Private M3U8 APIs
Queue APIs
File Processing
Querying File Preview Feature Status
File Transcoding
Sync Request API
Async Processing Job APIs
Async Processing Queue APIs
File-to-HTML Conversion
Content Recognition
Image Tagging
Image QR CodeJob APIs©2013-2022 Tencent Cloud. All rights reserved.

Page 7 of 1869

Cloud Infinite

Animated Image Job APIs
Screenshot Job APIs
Transcoding Job APIs
Splicing Job APIsIntelligent Thumbnail Job APIs
Multi-Job APIs
Video Enhancement Job APIs
Video Montage Job APIs
Voice/Sound Separation Job APIs
SDR-to-HDR Job APIs
Digital Watermark Job APIs
Super Resolution Job APIs
Video Tagging Job APIs
Image Processing Job APIs
Remuxing Job APIs
Template APIs
Template Search API
File Processing
Multi-File Zipping
Hash Calculation
File Decompression
Python SDK
Getting Started
Image Processing
Persistent Image Processing
Image Advanced Compression
Blind Watermark
Media Processing
Media Information APIsMedia Screenshot APIs
Content Moderation
Image Moderation
Video Moderation
Audio Moderation
Text Moderation
File Moderation
Webpage Moderation
Content Recognition©2013-2022 Tencent Cloud. All rights reserved.

Page 8 of 1869

Cloud Infinite

Speech Recognition
Job APIs
Speech Recognition Bucket APIs
Queue APIs
Image QR CodeFile Processing
File Transcoding
Sync Request API
Async Processing Job APIs
Async Processing Queue APIs
File-to-HTML Conversion
Querying File Preview Feature Status
Template APIs
Speech Recognition
File Processing
File Decompression
Querying File Decompression Result
Submitting File Decompression Job
Mini Program SDK
Getting Started
Image Processing
Basic Image Processing
Blind Watermark
Media Processing
Media Bucket APIsMedia Information APIsMedia Screenshot APIs
Content Moderation
Live Stream Moderation
Personal Information Protection Policy for SDK
Personal Information Protection Policy for CI SDK©2013-2022 Tencent Cloud. All rights reserved.

Page 9 of 1869

Cloud Infinite

SDK Documentation
SDK Overview：

Last updated 2022-08-19 10:26:05
To make it easier and faster for you to use CI's basic image processing and media processing features and CDN's
image delivery features, we provide the following SDKs for your choice as needed. For more information, see theirrespective quick start documentation. COS SDKs also integrate CI's data processing features. If you need to use
SDKs for other languages such as C++ and JavaScript, see SDK Overview.
SDK

Quick Start Documentation

Android SDK

Getting Started

C SDK

Getting Started

C++ SDK

Getting Started.NET (C#) SDK

Getting Started

Go SDK

Getting Started

iOS SDK

Getting Started

Java SDK

Getting Started

JavaScript SDK

Getting Started

Node.js SDK

Getting Started

PHP SDK

Getting Started

Python SDK

Getting Started

Mini program SDK

Getting Started

：

Note

For more information on TPG, see TPG Compression.

©2013-2022 Tencent Cloud. All rights reserved.

Page 10 of 1869

Cloud Infinite

Android SDK
Getting Started：

Last updated 2022-05-17 15:58:23

Overview
To make it easier and faster for you to use CI's basic image processing features and CDN's image delivery features,
we provide the following five modules for your choice as needed:
ModuleFeaturecloud-infinite(default module)This module contains CI's basic image processing operations and supports freely
combining various operations to build URLs for network requests.

cloud-infinite-This module uses the CIImageLoadRequest instance to request online images andloaderreturn image data.

TPG

This module decodes and displays general images and TPG images.

AVIF

This module decodes and displays general images and AVIF images.

cloud-infinite-This module depends on the glide and cloud-infinite modules to provide CI's

glide

basic image processing features.

：

Note

For more information on TPG, see TPG Compression.

Resources
For the SDK source code and demo, see here.
For SDK APIs and parameters, see Scaling.
For SDK release notes, see Changelog.

Prerequisites©2013-2022 Tencent Cloud. All rights reserved.

Page 11 of 1869

Cloud Infinite

1. You need an Android app, which can be one of your existing projects or a new one.
2. Make sure that the application is built by using an SDK running on Android 4.0.3 or later.

Step 1. Install the cloud-infinite SDK
The cloud-infinite module has the following main features:
It contains CI's basic image processing operations, such as image scaling, cropping, rotation, format conversion,quality change, Gaussian blur, sharpening, watermarking, and image theme color acquisition.
It encapsulates each operation as a CITransform and supports freely combining basic operations to build URLs for
direct network requests.
Use Gradle for integration

：

Note

As the Bintray repository is no longer available, CI's SDKs have been migrated to Maven Central. The import
path is different, so you need to use the new import path during the update.

Add the following code to the project-level build.gradle file (usually in the root directory):
repositories {google()// Add the following line
mavenCentral()}

Add the following to the build.gradle of your app or other class libraries:
implementation 'com.qcloud.cos:cloud-infinite:1.2.1'

Step 2. Start using
Build the CIImageLoadRequest instance
1. When using CloudInfinite to build a CI-enabled image URL, you first need to instantiate the CloudInfinite class.

©2013-2022 Tencent Cloud. All rights reserved.

Page 12 of 1869

Cloud Infinite

CloudInfinite cloudInfinite = new CloudInfinite();

2. Instantiate the image transformation class CITransformation and set related operations. The following takes
TPG as an example. For more features, see Basic Image Processing.
CITransformation transform = new CITransformation();transform.format(CIImageFormat.TPG, CIImageLoadOptions.LoadTypeUrlFooter)

3. Use the CloudInfinite instance to build a CI-enabled image URL.
Build synchronously
CIImageLoadRequest request = cloudInfinite.requestWithBaseUrlSync(objectUrl, tr
ansform);// Image URL
URL imageURL = request.getUrl();// Header parameter
Map<String, List<String>> heaers = request.getHeaders();

Build asynchronously
cloudInfinite.requestWithBaseUrl(objectUrl, transform, new CloudInfiniteCallback() {@Override
public void onImageLoadRequest(@NonNull final CIImageLoadRequest request) {// Image URL
URL imageURL = request.getUrl();// Header parameter
Map<String, List<String>> heaers = request.getHeaders();
}
});

：

Note

The header parameter of CIImageLoadRequest is valid only when image format conversion is performed andoptions is set to LoadTypeAcceptHeader .

©2013-2022 Tencent Cloud. All rights reserved.

Page 13 of 1869

Cloud Infinite

Step 3. Load an image
After successfully building the CIImageLoadRequest instance, use the cloud-infinite-loader SDK to load an image.
1. Integrate the cloud-infinite-loader SDK.
implementation 'com.qcloud.cos:cloud-infinite-loader:1.2.1'

2. Add the INTERNET permission.
<uses-permission android:name="android.permission.INTERNET" />3. Load the image.
Directly load ImageView
CIImageLoader ciImageLoader = new CIImageLoader();ciImageLoader.display(request, imageview);

Request image data
CIImageLoader ciImageLoader = new CIImageLoader();ciImageLoader.loadData(request, new CIImageLoadDataCallBack() {@Override
public void onLoadData(byte[] bytes) {// Use the pseudocode to set bytes data for the imageview//imageview.setBytes(bytes);}@Override
public void onFailure(QCloudClientException clientException, QCloudServiceExcep
tion serviceException) {}});©2013-2022 Tencent Cloud. All rights reserved.

Page 14 of 1869

Cloud Infinite

Basic Image Processing
Image Processing：

Last updated 2023-06-09 16:48:39

Overview
CI provides the ResponsiveTransformation (auto processing) and CITransformation (custom processing) image
processing methods.

：

Note

Format: Currently, JPG, BMP, GIF, PNG, and WebP images can be processed, and HEIF images can be
decoded and processed.
Size: The input image cannot be larger than 32 MB, with its width and height not exceeding 30,000 pixels,
and the total number of pixels not exceeding 250 million. The width and height of the output image cannot
exceed 9,999 pixels. For an input animated image, the total number of pixels (Width x Height x Number offrames) cannot exceed 250 million pixels.
Number of frames (for animated images): For GIF, the number of frames cannot exceed 300.

ResponsiveTransformation
ResponsiveTransformation includes format conversion (converting formats according to OS versions) and scaling(scaling images according to the imageView control sizes and ScaleType) and is described as follows:
1. ResponsiveTransformation refers to processing images automatically.
2. Image sizes are automatically adjusted according to the imageView control sizes and ScaleType.
3. Images are automatically converted to the format most suitable for the OS version. For an OS earlier than Android
4.3, the original format is used. For Android 4.3 to 10.0, WebP is used. For Android 10.0 and later, HEIC is used.
ResponsiveTransformation transformation = new ResponsiveTransformation(imageview);

CITransformation
The CITransformation class in the cloud-infinite SDK has encapsulated the following basic image processing featuresof CI:
Scaling©2013-2022 Tencent Cloud. All rights reserved.

Page 15 of 1869

Cloud Infinite

Cropping
Rotating
Format Conversion
Quality Change
Gaussian Blurring
Sharpening
Watermarking
Removing Image Metadata
Combined Operations
Before using the basic image processing features of CI, instantiate the CITransformation class first as follows. Notethat instantiation is required for all the operations described below.
CITransformation transform = new CITransformation();

Scaling：

Note

For the API documentation, please see Scaling.

Scaling by percentage// Scale the image’s width to 50% without changing the height.
transform.thumbnailByWidthScale(50);// Scale the image’s height to 50% without changing the width.
transform.thumbnailByHeightScale(50);// Scale both the image’s width and height to 50%.
transform.thumbnailByScale(50);

Scaling with specified width and height// Scale the image’s width to 50 with the height scaled automatically.
transform.thumbnailByWidth(50);// Scale the image’s height to 50 with the width scaled automatically.
transform.thumbnailByHeight(50);// Set both the minimum width and height of the output image to 50 to scale the image.
transform.thumbnailByMinWH(50, 50);

©2013-2022 Tencent Cloud. All rights reserved.

Page 16 of 1869

Cloud Infinite// Set both the maximum width and height of the output image to 50 to scale the image.
transform.thumbnailByMaxWH(50, 50);// Scale both the image’s width and height to 50 with the original aspect ratio ignored. Note that the image might be distorted.
transform.thumbnailByWH(50, 50);

Proportional scaling
This feature scales images by limiting the resolution of the output image (the total number of pixels cannot exceed thespecified value).
// Scale the image proportionally by limiting the total number of pixels of the output image to 1,000.
transform.thumbnailByPixel(1000);

Cropping：

Note

For the API documentation, please see Cropping.

Regular cropping// Crop the image to the specified width and height (vertical and horizontal offs
ets relative to the upper-left vertex).
transform.cut(100, 300, 30, 30);

Inscribed circle cropping
radius specifies the radius of the inscribed circle. The value of radius should be an integer greater than 0 but
smaller than half the length of the input image’s shorter side. The center of the inscribed circle is the center of the input
image. This operation is not available for GIF images.
// Set the radius to 100.
transform.iradius(100);Rounded corner cropping©2013-2022 Tencent Cloud. All rights reserved.

Page 17 of 1869

Cloud Infinite

radius specifies the radius of the rounded corners of an image. The value of radius should be an integer
greater than 0 but smaller than half the length of the input image’s shorter side. The two sides of the input image are
the tangent lines of the rounded corner. This operation is not available for GIF images.
// Set the corner radius to 100.
transform.rradius(100);

Scaling and cropping

：

Note

For more information about the 3x3 grid position diagram, please see gravity.

// Scale and crop the input image to the target width and height.
transform.cropByWH(100, 100);// Scale and crop the input image to the target width and height with the referen
ce point (CIGravity) specified.
transform.cropByWH(100, 100, CIGravity.CENTER);// Scale and crop the input image to the target width.
transform.cropByWidth(100);// Scale and crop the input image to the target width with the reference point (CIGravity) specified.
transform.cropByWidth(100, CIGravity.CENTER);// Scale and crop the input image to the target height.
transform.cropByHeight(100);// Scale and crop the input image to the target height with the reference point(CIGravity) specified.
transform.cropByHeight(100, CIGravity.CENTER);

Smart cropping
Scale and crop an image based on the face position in the image. The width and height of the target image are
specified by Width and Height respectively.
// Crop the face from the image and scale both the width and height to 100.
transform.scrop(100, 100);

Rotating©2013-2022 Tencent Cloud. All rights reserved.

Page 18 of 1869

Cloud Infinite

：

Note

For the API documentation, please see Rotating.

Rotating an image by a specified angle
Rotate an image clockwise by a specified angle (0−360 degrees). By default, the image is not rotated.
// Rotate the image by 45 degrees.
transform.rotate(45);Rotating an image automatically
Rotate an image automatically according to the EXIF data of the input image.
transform.rotate();Format Conversion

：

Note

For the API documentation, please see Converting Format.

The target format can be TPG, JPG, BMP, GIF, PNG, HEIC, YJPEG (optimized by CI based on JPEG and isessentially JPG), and more. By default, the image format is not converted.
// Convert an image into JPEG.
transform.format(CIImageFormat.JPEG, CIImageLoadOptions.LoadTypeUrlFooter);
CIImageLoadOptions// Loading option 1: Include the accept header (accept:image/xxx).
LoadTypeAcceptHeader,// Loading option 2: Append imageMogr2/format/xxx to the URL.
LoadTypeUrlFooter,

：

Note

©2013-2022 Tencent Cloud. All rights reserved.

Page 19 of 1869

Cloud Infinite

To use the WebP format, ensure the version is Android 4.3 or later.
To use the HEIC format, ensure the version is Android 10 or later.
Converting GIF into HEIF is not supported.
If you pass in parameters using LoadTypeAcceptHeader and have specified other image processing
rules, the header will not take effect. Instead, the SDK will use footer automatically.

To convert an image into TPG format, the TPG SDK is needed as follows:
implementation 'com.tencent.qcloud:tpg:1.3.1'
When installing TPG, the .so libraries will be included automatically. You are advised to use the “abiFilter”
configuration of the NDK in the module’s build.gradle file to set the .so library frameworks that are supported.
defaultConfig {ndk {// Set the .so library frameworks that are supported.
abiFilters 'armeabi' //, 'x86', 'armeabi-v7a', 'x86_64', 'arm64-v8a'}}

GIF optimization
This feature only optimizes GIF images to reduce frames and image colors.
FrameNumber=1: cuts the input GIF to the default number of frames (30). If the original number of frames is greaterthan 30, the exceeded frames will be cut.
FrameNumber=(1,100]: compresses the image to the specified number of frames ( FrameNumber ).
transform.gifOptimization(50);Progressive mode of the output JPG image
This operation is only available if the output format is JPG. Otherwise, this operation will be ignored.
transform.jpegInterlaceMode(true);

Quality Change
CI supports three modes (absolute, relative, and lowest quality) to change the quality of an image. For the API
documentation, please see Quality Change.

©2013-2022 Tencent Cloud. All rights reserved.

Page 20 of 1869

Cloud Infinite// Set the absolute quality of the image. Value range: 0−100. By default, the smaller value between the original image quality and the specified quality will be u
sed.
transform.quality(90);// Set the lowest quality of the output image. Value range: 0−100.
// If the input image quality is 85 and `lquality` is set to 80, the quality of t
he output image is 85.
// If the input image quality is 60 and `lquality` is set to 80, the quality of t
he output image will be improved to 80.
transform.lowestQuality(90);// Set the relative quality of the image, relative to that of the input image. Va
lue range: 0−100. For example, if the input image quality is 80 and `rquality` is
set to `80`, the quality of the output image is 64 (that is, 80 x 80%).
transform.relativelyQuality(80);

：

Note

This operation is only available for JPG and WebP images.

Gaussian Blurring
Gaussian blurring supports a blur radius ranging from 1 to 50, and the standard deviation of the normal distribution
must be greater than 0. For the API documentation, please see Gaussian Blurring.
// Set the blur radius to 20 and the standard deviation of the normal distribution to 20.
transform.blur(20, 20);

：

Note

This operation is not available for GIF images.

Sharpening
The sharpening value can be an integer ranging from 10 to 300 (70 is recommended). The greater the value, the more
obvious the sharpening. For the API documentation, please see Sharpening.

©2013-2022 Tencent Cloud. All rights reserved.

Page 21 of 1869

Cloud Infinite// Set the sharpening value to 70.
transform.sharpen(70);

Watermarking

：

Note

For the API documentation, plesae see Image Watermarking and Text Watermarking.
For more information about the 3x3 grid position diagram, please see gravity.

Image watermark
WatermarkImageTransform watermarkImageTransform = new WatermarkImageTransform// Set the URL of the image watermark.
.Builder(imageurl)// Set the reference point in the 3x3 grid position diagram.
.setGravity(CIGravity.CENTER)// Set the adaptation mode for an image watermark that is larger than the input i
mage.
.setBlogo(1)// Set the horizontal offset.
.setDistanceX(10)// Set the vertical offset.
.setDistanceY(10).builder();transform.watermarkImage(watermarkImageTransform);

：

Note

An image watermark must:
1. Be stored in the same bucket as the input image.
2. Have a URL containing a COS domain name (a CDN acceleration domain name such as
examplebucket-1250000000.file.myqcloud.com/shuiyin_2.png is unsupported) and beaccessible. If the image watermark is set to private-read, it must carry a signature.
3. Have a URL starting with http:// . Note that "http://" cannot be omitted or changed to "https://". For
example, examplebucket-1250000000.cos.ap-shanghai.myqcloud.com/shuiyin_2.png©2013-2022 Tencent Cloud. All rights reserved.

Page 22 of 1869

Cloud Infinite

and https://examplebucket-1250000000.cos.apshanghai.myqcloud.com/shuiyin_2.png are invalid watermark URLs.

Text watermark
WatermarkTextTransform watermarkImageTransform = new WatermarkTextTransform// Set the watermark text.
.Builder("Watermark")// Set the reference point in the 3x3 grid position diagram.
.setGravity(CIGravity.CENTER)// Set the font.
.setFont("tahoma.ttf")// Set the font size.
.setFontSize(13)// Set the text color.
.setFill("#FF0000")// Set the opacity of the watermark.
.setDissolve(80)// Set the horizontal offset.
.setDistanceX(10)// Set the vertical offset.
.setDistanceY(10)// Enable text watermark tiling to tile the watermark across the image.
.openBatch()// Rotate the watermark.
.rotate(45).builder();transform.watermarkText(watermarkImageTransform);

Removing Image Metadata
CI uses the imageMogr2 API to remove image metadata, including the EXIF data. For the API documentation,please see Removing Image Metadata.
transform.strip();

Combined Operations
Transform can be used to perform multiple operations in order.

©2013-2022 Tencent Cloud. All rights reserved.

Page 23 of 1869

Cloud Infinite

transform.thumbnailByScale(80).iradius(100).blur(20,20).strip();©2013-2022 Tencent Cloud. All rights reserved.

Page 24 of 1869

Cloud Infinite

Loading Image with Glide：

Last updated 2022-09-23 14:30:05
This document describes how to load images with Glide.

Installing Glide
implementation 'com.github.bumptech.glide:glide:version'

Basic Image Processing
Use Glide and CI together to perform basic image processing operations (except TPG and AVIF features).
1. Construct a CIImageLoadRequest by using CloudInfinite and CITransformation .
CloudInfinite cloudInfinite = new CloudInfinite();CITransformation transform = new CITransformation();transform.thumbnailByScale(50).iradius(60);
CIImageLoadRequest request = cloudInfinite.requestWithBaseUrlSync(url, transform);

2. Get the URL through the obtained CIImageLoadRequest and use Glide to load it.

Glide.with(activity).load(request.getUrl().toString()).into(imageview);

Using CI's Glide Feature
Install the cloud-infinite-glide SDK and glide:compiler.
implementation 'com.qcloud.cos:cloud-infinite-glide:1.2.1'
annotationProcessor 'com.github.bumptech.glide:compiler:version'
Register relevant decoders and loaders through AppGlideModule to implement corresponding features.

©2013-2022 Tencent Cloud. All rights reserved.

Page 25 of 1869

Cloud Infinite// Register the custom `GlideModule`// You should create this class to register `CIImageRequestModelLoader` and `Imag
eAveDecoder`.<br>// If you develop class libraries, you can inherit `LibraryGlideModule` to createa similar registration class.
@GlideModule
public class MyAppGlideModule extends AppGlideModule {@Override
public void registerComponents(@NonNull Context context, @NonNull Glide glide, Re
gistry registry) {// Register a loader that supports `CIImageLoadRequest`
registry.prepend(CIImageLoadRequest.class, InputStream.class, new CIImageRequestM
odelLoader.Factory());// Register the main color decoder
registry.prepend(InputStream.class, Bitmap.class, new ImageAveDecoder(glide.getBi
tmapPool()));}}

Preloading with image main color// Register the main color decoder in `AppGlideModule` firstregistry.prepend(InputStream.class, Bitmap.class, new ImageAveDecoder(glide.getBi
tmapPool()));// Use Glide's thumbnail to preload the main color
Glide.with(context).load(imageUrl).thumbnail(CloudInfiniteGlide.getImageAveThumbnail(context, imageUrl)).into(imageview);

Directly loading CIImageLoadRequest
Currently, this method is only used for the case where the header transfers the target image format during format
conversion.
registry.prepend(CIImageLoadRequest.class, InputStream.class, new CIImageRequestM
odelLoader.Factory());

Using CI's TPG Feature
Install the TPG SDK and glide:compiler.

©2013-2022 Tencent Cloud. All rights reserved.

Page 26 of 1869

Cloud Infinite

implementation 'com.qcloud.cos:tpg:1.3.2'
annotationProcessor 'com.github.bumptech.glide:compiler:version'
Register relevant decoders through AppGlideModule to implement corresponding features.

// Register the custom `GlideModule`// You should create this class to register `TpgDecoder` and `ByteBufferTpgGifDec
oder`.<br>// If you develop class libraries, you can inherit `LibraryGlideModule` to createa similar registration class.
@GlideModule
public class MyAppGlideModule extends AppGlideModule {@Override
public void registerComponents(@NonNull Context context, @NonNull Glide glide, Re
gistry registry) {/*------------------Decoder start-------------------------*/// Register the static TPG image decoder
registry.prepend(InputStream.class, Bitmap.class, new TpgDecoder(glide.getBitmapP
ool()));// Register the animated TPG image decoder
ByteBufferTpgGifDecoder byteBufferTpgGifDecoder = new ByteBufferTpgGifDecoder(context, glide.getBitmapPool(), glide.getArrayPool());
registry.prepend(InputStream.class, GifDrawable.class, new StreamTpgGifDecoder(byteBufferTpgGifDecoder));registry.prepend(ByteBuffer.class, GifDrawable.class, byteBufferTpgGifDecoder);/*------------------Decoder end-------------------------*/}}

Loading static TPG image
registry.prepend(InputStream.class, Bitmap.class, new TpgDecoder(glide.getBitmapP
ool()));

Loading animated TPG image
ByteBufferTpgGifDecoder byteBufferTpgGifDecoder = new ByteBufferTpgGifDecoder(context, glide.getBitmapPool(), glide.getArrayPool());
registry.prepend(InputStream.class, GifDrawable.class, new StreamTpgGifDecoder(byteBufferTpgGifDecoder));registry.prepend(ByteBuffer.class, GifDrawable.class, byteBufferTpgGifDecoder);©2013-2022 Tencent Cloud. All rights reserved.

Page 27 of 1869

Cloud Infinite

Using CI's AVIF Feature
Install the AVIF SDK and glide:compiler.
implementation 'com.qcloud.cos:avif:1.0.0'
annotationProcessor 'com.github.bumptech.glide:compiler:version'
Register relevant decoders through AppGlideModule to implement corresponding features.

// Register the custom `GlideModule`// You should create this class to register relevant decoders.<br>// If you develop class libraries, you can inherit `LibraryGlideModule` to createa similar registration class.
@GlideModule
public class MyAppGlideModule extends AppGlideModule {@Override
public void registerComponents(@NonNull Context context, @NonNull Glide glide, Re
gistry registry) {/*------------------Decoder start-------------------------*/// Register the static AVIF image decoder
registry.prepend(Registry.BUCKET_BITMAP, InputStream.class, Bitmap.class, new Str
eamAvifDecoder(glide.getBitmapPool(), glide.getArrayPool()));
registry.prepend(Registry.BUCKET_BITMAP, ByteBuffer.class, Bitmap.class, new Byte
BufferAvifDecoder(glide.getBitmapPool()));// Register the animated AVIF image decoder
registry.prepend(InputStream.class, AvifSequenceDrawable.class, new StreamAvifSeq
uenceDecoder(glide.getBitmapPool(), glide.getArrayPool()));
registry.prepend(ByteBuffer.class, AvifSequenceDrawable.class, new ByteBufferAvif
SequenceDecoder(glide.getBitmapPool()));/*------------------Decoder end-------------------------*/}}

Loading static AVIF image
registry.prepend(Registry.BUCKET_BITMAP, InputStream.class, Bitmap.class, new Str
eamAvifDecoder(glide.getBitmapPool(), glide.getArrayPool()));
registry.prepend(Registry.BUCKET_BITMAP, ByteBuffer.class, Bitmap.class, new Byte
BufferAvifDecoder(glide.getBitmapPool()));

Loading animated AVIF image
registry.prepend(InputStream.class, AvifSequenceDrawable.class, new StreamAvifSeq
uenceDecoder(glide.getBitmapPool(), glide.getArrayPool()));©2013-2022 Tencent Cloud. All rights reserved.

Page 28 of 1869

Cloud Infinite

registry.prepend(ByteBuffer.class, AvifSequenceDrawable.class, new ByteBufferAvif
SequenceDecoder(glide.getBitmapPool()));©2013-2022 Tencent Cloud. All rights reserved.

Page 29 of 1869

Cloud Infinite

Loading TPG Image：

Last updated 2022-09-01 14:46:39
This document describes how to load online and local TPG images.

Installing TPG SDK
implementation 'com.qcloud.cos:tpg:1.3.2'
The .so libraries will be included automatically. We recommend you use the "abiFilter" configuration of the NDK in themodule's build.gradle file to set the .so library frameworks that are supported.

defaultConfig {ndk {// Set the .so library frameworks that are supported
abiFilters 'armeabi' //, 'x86', 'armeabi-v7a', 'x86_64', 'arm64-v8a'}}

Option 1. Loading online TPG image
1. Integrate the CI SDK.
implementation 'com.qcloud.cos:cloud-infinite:1.2.1'

2. Build a link requesting TPG images in the CI SDK, and then use it with Glide to load online TPG images.
// Instantiate `CloudInfinite` to build an image request link;
CloudInfinite cloudInfinite = new CloudInfinite();// Perform transformation according to the basic feature options of CI you sele
ct;
CITransformation transform = new CITransformation();transform.format(CIImageFormat.TPG, CIImageLoadOptions.LoadTypeUrlFooter);// Build the image `CIImageLoadRequest`
CIImageLoadRequest request = cloudInfinite.requestWithBaseUrlSync(url, transform);

Option 2. Loading local TPG image©2013-2022 Tencent Cloud. All rights reserved.

Page 30 of 1869

Cloud Infinite

You can use the TPG format for the application's built-in resources, such as assets, drawable, and raw can reduce thesize of the installation package.
// Load TPG images in `Assets`
TpgImageLoader.displayWithAssets(imageview, assetsName);// Load TPG images in `Resource`
TpgImageLoader.displayWithResource(imageview, R.drawable.tpg);// Load TPG images in local files
TpgImageLoader.displayWithFileUri(imageview, fileUri);©2013-2022 Tencent Cloud. All rights reserved.

Page 31 of 1869

Cloud Infinite

Loading AVIF Image：

Last updated 2022-09-23 14:30:05
This document describes how to load online and local AVIF images.

Installing AVIF SDK
implementation 'com.qcloud.cos:avif:1.0.0'
The .so libraries will be included automatically. We recommend you use the "abiFilter" configuration of the NDK in themodule's build.gradle file to set the .so library frameworks that are supported.

defaultConfig {ndk {// Set the .so library frameworks that are supported
abiFilters 'armeabi' //, 'x86', 'armeabi-v7a', 'x86_64', 'arm64-v8a'}}

Option 1. Loading online AVIF image
1. Integrate the CI SDK.
implementation 'com.qcloud.cos:cloud-infinite:1.2.1'

2. Build a link requesting AVIF images in the CI SDK, and then use it with Glide to load online AVIF images as
instructed in Loading Image with Glide.

// Instantiate `CloudInfinite` to build an image request link;
CloudInfinite cloudInfinite = new CloudInfinite();// Perform transformation according to the basic feature options of CI you sele
ct;
CITransformation transform = new CITransformation();transform.format(CIImageFormat.AVIF, CIImageLoadOptions.LoadTypeUrlFooter);// Build the image `CIImageLoadRequest`
CIImageLoadRequest request = cloudInfinite.requestWithBaseUrlSync(url, transform);

Option 2. Loading local AVIF image©2013-2022 Tencent Cloud. All rights reserved.

Page 32 of 1869

Cloud Infinite

You can use the AVIF format for the application's built-in resources, such as assets, drawable, and raw can reduce
the size of the installation package.
// Load AVIF images in `Assets`
AVIFImageLoader.displayWithAssets(imageview, assetsName);// Load AVIF images in `Resource`
AVIFImageLoader.displayWithResource(imageview, R.drawable.avif);// Load AVIF images in local files
AVIFImageLoader.displayWithFileUri(imageview, fileUri);©2013-2022 Tencent Cloud. All rights reserved.

Page 33 of 1869

Cloud Infinite

iOS SDK
Getting Started：

Last updated 2023-02-22 10:44:23

Overview
To make it easier and faster for you to use CI's basic image processing features and CDN's image delivery features,
we provide the following five modules for your choice as needed:
ModuleFeatureCloudInfinite(default module)This module contains CI's basic image processing operations and supports freely
combining various operations to build URLs for network requests.

LoaderThis module uses the CIImageLoadRequest instance to request online images andreturn image data.

TPG

This module decodes and displays general images and TPG images.

AVIF

This module decodes and displays general images and AVIF images (on v1.3.8 or later).

SDWebImageCloudInfinite

This module provides CI's basic image processing features based on the SDWebImage andCloudInfinite modules.

：

Note

For more information on TPG, see TPG Compression.
For more information on AVIF, see AVIF Compression.

Resources
For SDK source codes and demos, see CI iOS SDK.
For SDK APIs and parameters, see SDK API.
For the SDK changelog, see Changelog.

©2013-2022 Tencent Cloud. All rights reserved.

Page 34 of 1869

Cloud Infinite

Preparations
1. Prepare an iOS application; this can be an existing project or a new empty project.
2. Make sure that the application is built using an SDK running on iOS 8.0 or above.

Step 1. Install the SDK CloudInfinite module
Main features of the CloudInfinite module:
It contains CI's basic image processing operations, such as image scaling, cropping, rotation, format conversion,quality change, Gaussian blur, sharpening, watermarking, and image theme color acquisition.
It encapsulates each operation as a TransformItem and supports freely combining basic operations to build URLs
for direct network requests.
Integration via CocoaPods

：

Note

We recommend you use the CocoaPods method. The steps for integrating related modules are the same andwill not be repeated.

1. Add the module to your project's Podfile:
pod 'CloudInfinite'

2. Run the installation command in the terminal:
pod install

Step 2. Start using
Importing header files
Objective-C#import <CloudInfinite.h>©2013-2022 Tencent Cloud. All rights reserved.

Page 35 of 1869

Cloud Infinite

swift
Add project name-Bridging-Header in the bridging file.
#import <CloudInfinite.h>

Build the CIImageLoadRequest instance
1. When using CloudInfinite to build a CI-enabled image URL, you first need to instantiate the CloudInfinite class.
Objective-C
CloudInfinite * cloudInfinite = [CloudInfinite new];swift

let cloudInfinite = CloudInfinite();
2. Instantiate the image transformation class CITransformation and set related operations. The following takes
TPG as an example.
Objective-C
CITransformation * transform = [CITransformation new];[transform setFormatWith:CIImageTypeTPG options:CILoadTypeUrlFooter];swift
let transform = CITransformation();transform.setFormatWith(CIImageFormat.typeTPG, options: CILoadTypeEnum.urlFooter);
3. Use the CloudInfinite instance to construct a CI-enabled image URL.
Build synchronously
Objective-C

CIImageLoadRequest * imageloadRequest = [cloudInfinite requestWithBaseUrl:@"Image
URL" transform:transform];// Image URL
NSURL * imageURL = imageloadRequest.url;©2013-2022 Tencent Cloud. All rights reserved.

Page 36 of 1869

Cloud Infinite// Header parameter
NSString * heaer = imageloadRequest.header;swift
let imageloadRequest = cloudInfinite.request(withBaseUrl: "Image URL", transform:
transform);// Image URL
let imageURL = imageloadRequest.url;// Header parameter
let heaer = imageloadRequest.header;
Build asynchronously
Objective-C[cloudInfinite requestWithBaseUrl:@"image link" transform:transform request:^(CII
mageLoadRequest * _Nonnull request) {// Image URL
request.url;// Header parameterrequest.header;
}];
swift
cloudInfinite.request(withBaseUrl: "", transform: transform) { (request) in// Image URL
request.url;// Header parameterrequest.header;
};

：

Note

The header parameter of CIImageLoadRequest is valid only when image format conversion is performed andoptions is set to loadtypeacceptheader .
When using a custom loader to request an image, if the header needs to be used, concatenate it as follows:

NSDictionary * header = @{@"accept":[NSString stringWithFormat:@"image/%@",request.header]};©2013-2022 Tencent Cloud. All rights reserved.

Page 37 of 1869

Cloud Infinite

Step 3. Load an image
After successfully constructing a CIImageLoadRequest instance, use the CloudInfinite/Loader module to load
images. Integrate the CloudInfinite/Loader module as follows:
pod 'CloudInfinite/Loader'

Requesting image data
Request the image NSData , which is suitable for requesting TPG images (with the TPG decoding module
required) or images that require additional processing of binary data.
Objective-C// `request` is the `CIImageLoadRequest` instance successfully constructed in theprevious step.
[[CIImageLoader shareLoader] loadData:request loadComplete:^(NSData * _Nullable data, NSError * _Nullable error) {// `data` is the obtained image data.
}];
swift
// `request` is the `CIImageLoadRequest` instance successfully constructed in theprevious step.
CIImageLoader.share().loadData(request) { (data, error) in// `data` is the obtained image data.
};

Loading general image
Objective-C// Pass in the image control `imageView` and the successfully constructed `CIImag
eLoadRequest` instance[[CIImageLoader shareLoader]display:imageView loadRequest:request placeHolder:nil
loadComplete:^(NSData * _Nullable data, NSError * _Nullable error) {// `data` is the obtained image data.
}];
swift

©2013-2022 Tencent Cloud. All rights reserved.

Page 38 of 1869

Cloud Infinite// Pass in the image control `imageView` and the successfully constructed `CIImag
eLoadRequest` instance
CIImageLoader.share().display(imageView, loadRequest: request, placeHolder: nil)
{ (data, error) in// `data` is the obtained image data.
};©2013-2022 Tencent Cloud. All rights reserved.

Page 39 of 1869

Cloud Infinite

Loading TPG Image：

Last updated 2022-07-06 16:04:29
This document provides two ways to load TPG images: loading online and using the TPG module.

Option 1. Loading online TPG image
1. Integrate CloudInfinite .

pod 'CloudInfinite'

2. Build a link requesting TPG images in the CloudInfinite module, and then use it with SDWebImage to load
online TPG images.
Objective-C// Instantiate `CloudInfinite` to build an image request link;
CloudInfinite * cloudInfinite = [CloudInfinite new];// Build `CIImageLoadRequest` according to the basic feature options of CI you
select;CITransformation * transform = [CITransformation new];[transform setFormatWith:CIImageTypeTPG options:CILoadTypeUrlFooter];// Build the image `CIImageLoadRequest`[cloudInfinite requestWithBaseUrl:@"image link" transform:transform request:^(CIImageLoadRequest * _Nonnull request) {// Request the successfully built `CIImageLoadRequest` instance.
}];**swift**<pre><code><span class="hljs-comment">// Instantiate `CloudInfinite` to build an
image request link;</span>let cloudInfinite = CloudInfinite();// Build CIImageLoadRequest according to the basic feature options of CI you select;
let transform = CITransformation();transform.setFormatWith(CIImageFormat.typeTPG, options: CILoadTypeEnum.urlFooter);// Build the image CIImageLoadRequest
cloudInfinite.request(withBaseUrl: "image link", transform: transform) { (request) in// Request the successfully built CIImageLoadRequest instance.
}©2013-2022 Tencent Cloud. All rights reserved.

Page 40 of 1869

Cloud Infinite

Option 2. Using TPG module to load TPG image
You can use the TPG module to load TPG image data, which supports TPG animated images with no additional
processing needed.
1. Integrate the TPG module.

pod 'CloudInfinite/TPG'

2. If the TPG image data has been obtained, directly use the UIImageView+TPG class of the TPG module to decodeand display the image.
Objective-C[self.tpgImageView setTpgImageWithData:data loadComplete:^(NSData * _Nullable data, UIImage * _Nullable image, NSError * _Nullable error) {
}];

swift

imageView.setTpgImageWith(data) { (data, image, error) in}©2013-2022 Tencent Cloud. All rights reserved.

Page 41 of 1869

Cloud Infinite

Basic Image Processing
Image Processing：

Last updated 2023-06-09 16:50:54

Overview
CI provides the CIResponsiveTransformation (auto processing) and CITransformation (custom processing) image
processing methods.
Note:
Format: Currently, JPG, BMP, GIF, PNG, and WEBP images can be processed, and HEIF images can be decodedand processed.
Size: The input image cannot be larger than 32 MB, with its width and height not exceeding 30,000 pixels respectively,
and the total number of pixels not exceeding 250 million. The width and height of the output image cannot exceed
9,999 pixels respectively. For an animated input image, the total number of pixels (width height number of frames)
cannot exceed 250 million.
Frames (for animated images): For GIF images, the number of frames cannot exceed 300.

Resources
For SDK APIs and parameters, see Scaling.
CIResponsiveTransformation
ResponsiveTransformation includes format conversion (converting formats according to OS versions) and scaling(scaling images according to the imageView control sizes and ScaleType) and is described as follows:

1. CIResponsiveTransformation refers to processing images automatically.
2. It automatically adjusts the size of the image according to the size of the current imageView control.
3. It automatically selects the optimal image format according to the system version (HEIC for iOS 11 and later or theoriginal format for earlier versions).

Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 42 of 1869

Cloud Infinite

CIResponsiveTransformation * sTransform = [[CIResponsiveTransformation alloc]initWi
swift©2013-2022 Tencent Cloud. All rights reserved.

Page 43 of 1869

Cloud Infinite

let sTransform = CIResponsiveTransformation(view: nil, scale: ScaleType.autoFit)

CITransformation
The CITransformation class in the CI SDK has encapsulated the following basic image processing features of CI:

Scaling
Cropping
Rotation©2013-2022 Tencent Cloud. All rights reserved.

Page 44 of 1869

Cloud Infinite

Format conversion
Quality change
Gaussian blurring
Sharpening
Watermark
Image average hue acquisition
Image metadata removal
Combined operations

Before using the basic image processing features of CI, instantiate the CITransformation class first as follows. Notethat instantiation is required for all the operations described below.
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 45 of 1869

Cloud Infinite

CITransformation * transform = [CITransformation new];swift©2013-2022 Tencent Cloud. All rights reserved.

Page 46 of 1869

Cloud Infinite

let transform = CITransformation();

Scaling
Note:
For the API documentation, see Scaling.
Scaling by percentage©2013-2022 Tencent Cloud. All rights reserved.

Page 47 of 1869

Cloud Infinite

Objective-C// Scale to 50%[transform setZoomWithPercent:50 scaleType:ScalePercentTypeALL];// `scaleType` can be specified as the following types:// Scale the width without changing the height
ScalePercentTypeOnlyWidth = 1,// Scale the height without changing the width
ScalePercentTypeOnlyHeight,// Scale both the width and height©2013-2022 Tencent Cloud. All rights reserved.

Page 48 of 1869

Cloud Infinite

ScalePercentTypeALL,
swifttransform.setZoomWithPercent(50, scale: ScalePercentType.ALL)

Scaling with specified width and height
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 49 of 1869

Cloud Infinite// Specify both the width and height as 100 and the scaling type as `ScaleTypeAUTOF[transform setZoomWithWidth:100 height:100 scaleType:ScaleTypeAUTOFit];// `scaleType` can be specified as the following types in case of scaling by fixed// Specify both the height and width. The output image may be distorted.
ScaleTypeAUTOFill = 1,// Specify the maximum width and height of a thumbnail as `Width` and `Height`
ScaleTypeAUTOFit,// Specify the minimum width and height of a thumbnail as `Width` and `Height`©2013-2022 Tencent Cloud. All rights reserved.

Page 50 of 1869

Cloud Infinite

ScaleTypeAUTOFITWithMin,// Specify the target image width as `Width` and pass in `0` for the height to
ScaleTypeOnlyWidth,// Specify the target image height as `Height` and pass in `0` for the width to
ScaleTypeOnlyHeight
swift

transform.setZoomWithWidth(10, height: 100, scaleType: ScaleType.autoFit)©2013-2022 Tencent Cloud. All rights reserved.

Page 51 of 1869

Cloud Infinite

Proportional scaling
This feature scales images by limiting the resolution of the output image (the total number of pixels cannot exceed thespecified value).
Objective-C// Scale an image so that the total number of its pixels does not exceed 1,000[transform setZoomWithArea:1000];
swift©2013-2022 Tencent Cloud. All rights reserved.

Page 52 of 1869

Cloud Infinite

transform.setZoomWithArea(1000)

Cropping
Note:
For the API documentation, see Cropping.
Regular cropping©2013-2022 Tencent Cloud. All rights reserved.

Page 53 of 1869

Cloud Infinite

Objective-C// Perform cropping based on the specified target width, height, and horizontal off[transform setCutWithWidth:100 height:100 dx:30 dy:30];
swift©2013-2022 Tencent Cloud. All rights reserved.

Page 54 of 1869

Cloud Infinite

transform.setCutWithWidth(100, height: 100, dx: 30, dy: 30)

Inscribed circle cropping
radius specifies the radius of the inscribed circle, which should be an integer greater than zero and less than halfof the shorter side of the input image. The center of the inscribed circle is the center of the image. This parameter is
not supported for GIF images.
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 55 of 1869

Cloud Infinite// Set the radius to 100.
[transform setCutWithIRadius:100];swift©2013-2022 Tencent Cloud. All rights reserved.

Page 56 of 1869

Cloud Infinite

transform.setCutWithIRadius(100)Rounded corner cropping
radius specifies the radius of the rounded corner of the image, which should be an integer greater than zero andless than half of the shorter side of the input image. The two sides of the image are the tangent lines of the rounded
corner. This parameter is not supported for GIF images.
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 57 of 1869

Cloud Infinite// Set the corner radius to 100.
[transform setCutWithRRadius:100];swift©2013-2022 Tencent Cloud. All rights reserved.

Page 58 of 1869

Cloud Infinite

transform.setCutWithRRadius(100)

Scaling and cropping
Note:
For more information on the 3x3 grid position diagram, see Cropping.
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 59 of 1869

Cloud Infinite// Specify the width and height for scaling and cropping and change nothing in case[transform setCutWithCrop:100 height:100];// Specify width, height, and gravity for scaling and cropping[transform setCutWithCrop:100 height:100 gravity:CIGravityCenter];swift©2013-2022 Tencent Cloud. All rights reserved.

Page 60 of 1869

Cloud Infinite

transform.setCutWithCrop(100, height: 100)transform.setCutWithCrop(100, height: 100, gravity: CloudInfiniteGravity.CIGravityC

Smart cropping
Scale and crop an image based on the face position in the image. The width and height of the target image are
specified by Width and Height respectively.
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 61 of 1869

Cloud Infinite// Crop the face from the image and scale both the width and height to 100.
[transform setCutWithScrop:100 height:100];swift©2013-2022 Tencent Cloud. All rights reserved.

Page 62 of 1869

Cloud Infinite

transform.setCutWithScrop(100, height: 100)

Rotating
Note:
For the API documentation, see Rotation.
Rotating an image by a specified angle©2013-2022 Tencent Cloud. All rights reserved.

Page 63 of 1869

Cloud Infinite

Rotate an image clockwise by a specified angle (0−360 degrees). By default, the image is not rotated.
Objective-C// Rotate the image by 45 degrees.
[transform setRotateWith:45];
swift©2013-2022 Tencent Cloud. All rights reserved.

Page 64 of 1869

Cloud Infinite

transform.setRotateWith(45)Rotating an image automatically
Rotate an image automatically according to the EXIF data of the input image.
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 65 of 1869

Cloud Infinite[transform setRotateAutoOrient];swift©2013-2022 Tencent Cloud. All rights reserved.

Page 66 of 1869

Cloud Infinite

transform.setRotateAutoOrient()

Format Conversion
Note:
For the API documentation, see Converting Format.
Format conversion©2013-2022 Tencent Cloud. All rights reserved.

Page 67 of 1869

Cloud Infinite

The target format can be TPG, JPG, BMP, GIF, PNG, HEIC, WEBP, YJPEG (which is optimized based on JPEG andis essentially JPG), or AVIF. The default format is the format of the input image.
Objective-C// Convert an image into JPG.
[transform setFormatWith:CIImageTypeJPG];// Specify input parameters:[transform setFormatWith:CIImageTypeTPG options:CILoadTypeUrlFooter];swift©2013-2022 Tencent Cloud. All rights reserved.

Page 68 of 1869

Cloud Infinite

transform.setFormatWith(CIImageFormat.typeJPG);
transform.setFormatWith(CIImageFormat.typeJPG, options: CILoadTypeEnum.urlFooter);
CILoadTypeEnum©2013-2022 Tencent Cloud. All rights reserved.

Page 69 of 1869

Cloud Infinite// Loading type option 1: Include the accept header accept:image/ ***CILoadTypeAcceptHeader = 0,// Loading type option 2: Add imageMogr2/format/ *** after the URL// If option 2 is needed, use this value. If this parameter is not specified, optio
CILoadTypeUrlFooter,
Note:
To use the HEIC format, iOS 11 or later is required. GIF images cannot be converted to HEIC.

©2013-2022 Tencent Cloud. All rights reserved.

Page 70 of 1869

Cloud Infinite

If you pass in parameters using CILoadTypeAcceptHeader and have specified other image processing rules,
the header will not take effect. Instead, the SDK will use footer automatically.
When using format conversion to convert an image to TPG format, you need to depend on the
CloudInfinite/TPG module.
When using format conversion to convert an image to AVIF format, you need to depend on the
CloudInfinite/AVIF module.
When using format conversion to convert an image to WEBP format, you need to depend on the
SDWebImageWebPCoder library.

©2013-2022 Tencent Cloud. All rights reserved.

Page 71 of 1869

Cloud Infinite

pod 'CloudInfinite/TPG'

pod 'CloudInfinite/AVIF'GIF optimization
This feature only optimizes GIF images to reduce frames and image colors.

©2013-2022 Tencent Cloud. All rights reserved.

Page 72 of 1869

Cloud Infinite

FrameNumber=1: Cuts the input GIF to the default number of frames (30). If the orig
FrameNumber=(1,100]: Compresses the image to the specified number of frames (`Frame
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 73 of 1869

Cloud Infinite[transform setCgif:50];
swift©2013-2022 Tencent Cloud. All rights reserved.

Page 74 of 1869

Cloud Infinite

transform.setCgif(50)Progressive mode of the output JPG image
Mode can be 0 or 1 . 0 (default value): Disables the progressive mode; 1 : Enables the progressive mode.
This parameter takes effect only when the output image is in JPG format.
Objective©2013-2022 Tencent Cloud. All rights reserved.

Page 75 of 1869

Cloud Infinite[transform setInterlace:YES];
swift©2013-2022 Tencent Cloud. All rights reserved.

Page 76 of 1869

Cloud Infinite

transform.setInterlace(true)

Quality Change
CI allows you to change the quality of an image. For the API documentation, see Quality Change.
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 77 of 1869

Cloud Infinite// Change the absolute quality of the image to 60// `type` is the change type as detailed below:[transform setQualityWithQuality:60 type:CIQualityChangeAbsolute];
swift©2013-2022 Tencent Cloud. All rights reserved.

Page 78 of 1869

Cloud Infinite

transform.setQualityWithQuality(60, type: CIQualityChangeEnum.absolute)
CI supports change to three types of image quality: absolute, relative, and lowest. The absolute quality change
supports forcibly specifying or not specifying the quality as follows:©2013-2022 Tencent Cloud. All rights reserved.

Page 79 of 1869

Cloud Infinite// The absolute quality of the image. The value can be 0–100. The default value is
CIQualityChangeAbsolute = 1,// The absolute quality of the image. The value can be 0–100. The specified quality
CIQualityChangeAbsoluteFix,// The image quality relative to that of the input image. The value can be 0−100. F
CIQualityChangeRelative,// Set the lowest quality of the output image. Value range: 0−100.
// If the input image quality is 85 and `lquality` is set to 80, the quality of the©2013-2022 Tencent Cloud. All rights reserved.

Page 80 of 1869

Cloud Infinite// If the input image quality is 60 and `lquality` is set to 80, the quality of the
CIQualityChangeLowest,
Note:
This operation is only available for JPG and WEBP images.

Gaussian Blurring
Gaussian blurring supports a blur radius ranging from 1 to 50, and the standard deviation of the normal distribution
must be greater than 0. For the API documentation, see Gaussian Blurring.
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 81 of 1869

Cloud Infinite// Set the blur radius to 20 and the standard deviation of the normal distribution[transform setBlurRadius:20 sigma:20];
swift©2013-2022 Tencent Cloud. All rights reserved.

Page 82 of 1869

Cloud Infinite

transform.setBlurRadius(20, sigma: 20)
Note:
This operation is not available for GIF images.

Sharpening©2013-2022 Tencent Cloud. All rights reserved.

Page 83 of 1869

Cloud Infinite

The sharpening value can be an integer ranging from 10 to 300 (70 is recommended). The greater the value, the more
obvious the sharpening. For the API documentation, see Sharpening.
Objective-C// Set the sharpening value to 100.
[transform setSharpenWith:100];swift©2013-2022 Tencent Cloud. All rights reserved.

Page 84 of 1869

Cloud Infinite

transform.setSharpenWith(100)Watermarking
Note:
For the API documentation, see Image Watermarking and Text Watermarking.
For more information on the 3x3 grid position diagram, see Text Watermarking.

©2013-2022 Tencent Cloud. All rights reserved.

Page 85 of 1869

Cloud Infinite

Image watermark
Objective-C// imageUrl: Watermark image address.
// gravity: Position of the text watermark in the 3x3 grid position diagram. Defaul// dx: Horizontal offset in px. Default value: `0`.
// dy: Vertical offset in px. Default value: `0`.
// blogo: Adaptation mode for an image watermark that is larger than the input imag///
`1`: Scales the image watermark to the size of the input image.
///`2`: Crops the image watermark to the size of the input image.
[tran setWaterMarkWithImageUrl:@"http://tpg-1253653367.cos.ap-guangzhou.myqcloud.co©2013-2022 Tencent Cloud. All rights reserved.

Page 86 of 1869

Cloud Infinite

swift

transform.setWaterMarkWithImageUrl("", gravity: CloudInfiniteGravity.CIGravityCente

Text watermark
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 87 of 1869

Cloud Infinite// text: Watermark content// font: Watermark font// color: Font color. Default value: #3D3D3D.
// dissolve: Text opacity. Value range: 1−100. Default value: `90`.
// gravity: Position of the text watermark. Default value: `SouthEast`.
// dx: Horizontal offset in px. Default value: `0`.
// dy: Vertical offset in px. Default value: `0`.
// batch: Whether to tile the text watermark. If this parameter is set to `1`, the// degree: The angle to rotate the text watermark. Value range: 0−360. Default valu
[transform setWaterMarkText:@"Tencent Cloud CI" font:nil textColor:nil dissolve:90©2013-2022 Tencent Cloud. All rights reserved.

Page 88 of 1869

Cloud Infinite

swift

transform.setWaterMarkText("Tencent Cloud CI", font: nil, textColor: nil, dissolve:

Obtaining Image Average Hue
CI uses the imageAve API to obtain the average hue of an image. For more information on the API, see Obtaining
Image's Average Hue.

©2013-2022 Tencent Cloud. All rights reserved.

Page 89 of 1869

Cloud Infinite

Objective-C[transform setViewBackgroudColorWithImageAveColor:YES]
swift©2013-2022 Tencent Cloud. All rights reserved.

Page 90 of 1869

Cloud Infinite

transform.setViewBackgroudColorWithImageAveColor(true)

Removing Image Metadata
CI uses the imageMogr2 API to remove image metadata, including the EXIF data. For the API documentation, seeRemoving Image Metadata.
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 91 of 1869

Cloud Infinite[transform setImageStrip];
swift©2013-2022 Tencent Cloud. All rights reserved.

Page 92 of 1869

Cloud Infinite

transform.setImageStrip()

Combined Operations©2013-2022 Tencent Cloud. All rights reserved.

Page 93 of 1869

Cloud Infinite

CITransformation * tran = [CITransformation new];//***************Scaling*************// Scale to 50%[transform setZoomWithPercent:50 scaleType:ScalePercentTypeALL];//**Format conversion// Convert to TPG format[tran setFormatWith:CIImageTypeTPG];//**Cropping©2013-2022 Tencent Cloud. All rights reserved.

Page 94 of 1869

Cloud Infinite// Crop the image. Width and height: 100; top left and left: 30 30[tran setCutWithWidth:100 height:100 dx:30 dy:30];©2013-2022 Tencent Cloud. All rights reserved.

Page 95 of 1869

Cloud Infinite

COS Android SDK
Content Moderation
Image Moderation：

Last updated 2023-02-06 15:59:30

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.

：

Note

To use the content moderation service, you need to have the permission to use CI:

For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for image moderation.
API
SensitiveContentRecognition
PostImagesAudit
GetImageAudit

Operation
Moderating an image
synchronously

Description
Moderates an image synchronously.

Batch moderating images

Batch moderates images.

Querying the image moderation

Queries the result of the specified image

job resultmoderation job.

SDK API References
For the parameters and method descriptions of all the APIs in the SDK, see SDK API Reference.

Single Image Moderation©2013-2022 Tencent Cloud. All rights reserved.

Page 96 of 1869

Cloud Infinite

Feature description
This API is used to moderate an image synchronously.
Sample code// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.
String bucket = "examplebucket-1250000000";
String key = "exampleobject"; // Object key
SensitiveContentRecognitionRequest sensitiveContentRecognitionRequest = new Sensi
tiveContentRecognitionRequest(bucket, key);
sensitiveContentRecognitionRequest.addType("ads");// `CIService` is a subclass of `CosXmlService` and has the same initialization m
ethod as it.
ciService.sensitiveContentRecognitionAsync(sensitiveContentRecognitionRequest, ne
w CosXmlResultListener() {@Override
public void onSuccess(CosXmlRequest request, CosXmlResult result) {SensitiveContentRecognitionResult sensitiveContentRecognitionResult = (SensitiveC
ontentRecognitionResult) result;}@Override
public void onFail(CosXmlRequest request, CosXmlClientException clientException,
CosXmlServiceException serviceException) {if (clientException != null) {clientException.printStackTrace();} else {serviceException.printStackTrace();
}
}
});

：

Note

For more samples, please visit GitHub.

Batch Image Moderation
Feature description
This API is used to batch moderate images.

©2013-2022 Tencent Cloud. All rights reserved.

Page 97 of 1869

Cloud Infinite

：

Note

The COS Android SDK version should not be earlier than v5.8.7.

Sample code// Bucket name in the format of BucketName-APPID
String bucket = "examplebucket-1250000000";// Object key, i.e., the full path of a COS object. If the object is in a directo
ry, the path should be "dir1/object1".
String cosPath1 = "dir1/exampleobject1.jpg";
String cosPath2 = "dir1/exampleobject2.jpg";// URL of the image. Either `Object` or `Url` can be selected at a time.
String imageUrl = "https://myqcloud.com/%205image.jpg";
PostImagesAuditRequest request = new PostImagesAuditRequest(bucket);
PostImagesAudit.ImagesAuditInput image1 = new PostImagesAudit.ImagesAuditInput();
image1.object = cosPath1;// Set the original content, which can contain up to 512 bytes. This field will be returned in the response as-is.
image1.dataId = "DataId1";// Frame capturing frequency, which takes effect for GIF images only. The default
value is `5`, indicating to capture a frame every five frames starting from the first frame (included).
image1.interval = 2;// The maximum number of frames to be captured, which takes effect for GIF images
only. The default value is `5`, indicating to capture only five frames of the GIF
image for moderation. The parameter value must be greater than 0.
image1.maxFrames = 5;
PostImagesAudit.ImagesAuditInput image2 = new PostImagesAudit.ImagesAuditInput();
image2.object = cosPath2;
image2.dataId = "DataId2";
image2.interval = 2;
image2.maxFrames = 5;
PostImagesAudit.ImagesAuditInput image3 = new PostImagesAudit.ImagesAuditInput();
image3.url = imageUrl;image3.dataId = "DataId3";
image3.interval = 2;
image3.maxFrames = 5;
request.addImage(image1);
request.addImage(image2);
request.addImage(image3);// The scene to be moderated, such as `Porn` (pornography) and `Ads` (advertising). You can pass in multiple types and separate them by comma, such as `Porn,Ads`.
request.setDetectType("Porn,Ads");©2013-2022 Tencent Cloud. All rights reserved.

Page 98 of 1869

Cloud Infinite

ciService.postImagesAuditAsync(request, new CosXmlResultListener() {@Override
public void onSuccess(CosXmlRequest request, CosXmlResult cosResult) {// `result` is the result of the batch image moderation job.
// For detailed fields, see the API documentation or SDK source code.
PostImagesAuditResult result = (PostImagesAuditResult) cosResult;}@Override
public void onFail(CosXmlRequest request, CosXmlClientException clientException,
CosXmlServiceException serviceException) {if (clientException != null) {clientException.printStackTrace();} else {serviceException.printStackTrace();
}
}
});

：

Note

For more complete samples, visit GitHub.

Querying Image Moderation Job Result
Feature description
This API is used to query the result of the specified image moderation job.

：

Note

The COS Android SDK version should not be earlier than v5.8.7.

Sample code// Bucket name in the format of BucketName-APPID
String bucket = "examplebucket-1250000000";// Moderation job ID
String jobId = "iab1ca9fc8a3ed11ea834c525400863904";
GetImageAuditRequest request = new GetImageAuditRequest(bucket, jobId);
ciService.getImageAuditAsync(request, new CosXmlResultListener() {@Override
public void onSuccess(CosXmlRequest request, CosXmlResult cosResult) {©2013-2022 Tencent Cloud. All rights reserved.

Page 99 of 1869

Cloud Infinite// `result` is the result of the image moderation job.
// For detailed fields, see the API documentation or SDK source code.
GetImageAuditResult result = (GetImageAuditResult) cosResult;}@Override
public void onFail(CosXmlRequest request, CosXmlClientException clientException,
CosXmlServiceException serviceException) {if (clientException != null) {clientException.printStackTrace();} else {serviceException.printStackTrace();
}
}
});

：

Note

For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 100 of 1869

Cloud Infinite

Video Moderation：

Last updated 2023-02-06 16:00:25

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.

：

Note

To use the content moderation service, you need to have the permission to use CI:

For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for video moderation.
API

Operation

Description

PostVideoAudit

Submitting a video moderation job

Submits a video moderation job.

Querying the video moderation job

Queries the result of the specified video moderation

resultjob.

GetVideoAudit

SDK API References
For the parameters and method descriptions of all the APIs in the SDK, see SDK API Reference.

Submitting Video Moderation Job
Feature description
This API is used to submit a video moderation job.

：

Note

The COS Android SDK version should not be earlier than v5.8.7.

©2013-2022 Tencent Cloud. All rights reserved.

Page 101 of 1869

Cloud Infinite

Sample code// Bucket name in the format of BucketName-APPID
String bucket = "examplebucket-1250000000";// Object key, i.e., the full path of a COS object. If the object is in a directo
ry, the path should be "dir1/object1".
String cosPath = "dir1/exampleobject.mp4";// URL of the video. Either `Object` or `Url` can be selected at a time.
String url = "https://myqcloud.com/%205video.mp4";
PostVideoAuditRequest request = new PostVideoAuditRequest(bucket);request.setObject(cosPath);request.setUrl(url);// Set the original content, which can contain up to 512 bytes. This field will be returned in the response as-is.
request.setDataId("DataId");// Callback address, which must start with `http://` or `https://`.
request.setCallback("https://github.com");// Structure of the callback content. Valid values: `Simple` (the callback conten
t contains basic information), `Detail` (the callback content contains detailed information). Default value: `Simple`.
request.setCallbackVersion("Detail");// The number of captured frames. Value range: (0, 10000].
request.setCount(3);// Video frame capturing frequency. Value range: (0, 60] seconds. The value suppo
rts the float format, accurate to the millisecond.
request.setTimeInterval(10);// The scene to be moderated, such as `Porn` (pornography) and `Ads` (advertising). You can pass in multiple types and separate them by comma, such as `Porn,Ads`.
request.setDetectType("Porn,Ads");// Specify whether to moderate video sound. Valid values: `0` (moderates the video image only), `1` (moderates both the video image and video sound). Default valu
e: `0`.
request.setDetectContent(1);// `CIService` is a subclass of `CosXmlService` and has the same initialization m
ethod as it.
ciService.postVideoAuditAsync(request, new CosXmlResultListener() {@Override
public void onSuccess(CosXmlRequest request, CosXmlResult cosResult) {// `result` is the result of the submitted video moderation job.
// For detailed fields, see the API documentation or SDK source code.
PostAuditResult result = (PostAuditResult) cosResult;}@Override©2013-2022 Tencent Cloud. All rights reserved.

Page 102 of 1869

Cloud Infinite

public void onFail(CosXmlRequest request, CosXmlClientException clientException,
CosXmlServiceException serviceException) {if (clientException != null) {clientException.printStackTrace();} else {serviceException.printStackTrace();
}
}
});

：

Note

For more complete samples, visit GitHub.

Querying Video Moderation Job Result
Feature description
This API is used to query the result of the specified video moderation job.

：

Note

The COS Android SDK version should not be earlier than v5.8.7.

Sample code// Bucket name in the format of BucketName-APPID
String bucket = "examplebucket-1250000000";// Moderation job ID
String jobId = "iab1ca9fc8a3ed11ea834c525400863904";
GetVideoAuditRequest request = new GetVideoAuditRequest(bucket, jobId);// `CIService` is a subclass of `CosXmlService` and has the same initialization m
ethod as it.
ciService.getVideoAuditAsync(request, new CosXmlResultListener() {@Override
public void onSuccess(CosXmlRequest request, CosXmlResult cosResult) {// `result` is the result of the video moderation job.
// For detailed fields, see the API documentation or SDK source code.
GetVideoAuditResult result = (GetVideoAuditResult) cosResult;}@Override
public void onFail(CosXmlRequest request, CosXmlClientException clientException,©2013-2022 Tencent Cloud. All rights reserved.

Page 103 of 1869

Cloud Infinite

CosXmlServiceException serviceException) {if (clientException != null) {clientException.printStackTrace();} else {serviceException.printStackTrace();
}
}
});

：

Note

For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 104 of 1869

Cloud Infinite

Audio Moderation：

Last updated 2023-02-06 16:01:14

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.

：

Note

To use the content moderation service, you need to have the permission to use CI:

For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for audio moderation.
API

Operation

Description

PostAudioAudit

Submitting an audio moderation job

Submits an audio moderation job.

GetAudioAudit

Querying the audio moderation job
resultQueries the result of the specified audio
moderation job.

SDK API References
For the parameters and method descriptions of all the APIs in the SDK, see SDK API Reference.

Submitting an Audio Moderation Job
Feature description
This API is used to submit an audio moderation job.

：

Note

The COS Android SDK version should not be earlier than v5.8.7.

©2013-2022 Tencent Cloud. All rights reserved.

Page 105 of 1869

Cloud Infinite

Sample code// Bucket name in the format of BucketName-APPID
String bucket = "examplebucket-1250000000";// Object key, i.e., the full path of a COS object. If the object is in a directo
ry, the path should be "dir1/object1".
String cosPath = "dir1/exampleobject.mp3";// URL of the audio. Either `Object` or `Url` can be selected at a time.
String url = "https://myqcloud.com/%205Audio.mp3";
PostAudioAuditRequest request = new PostAudioAuditRequest(bucket);request.setObject(cosPath);request.setUrl(url);// Set the original content, which can contain up to 512 bytes. This field will be returned in the response as-is.
request.setDataId("DataId");// Callback address, which must start with `http://` or `https://`.
request.setCallback("https://github.com");// Structure of the callback content. Valid values: `Simple` (the callback conten
t contains basic information), `Detail` (the callback content contains detailed information). Default value: `Simple`.
request.setCallbackVersion("Detail");// The scene to be moderated, such as `Porn` (pornography) and `Ads` (advertising). You can pass in multiple types and separate them by comma, such as `Porn,Ads`.
request.setDetectType("Porn,Ads");// `CIService` is a subclass of `CosXmlService` and has the same initialization m
ethod as it.
ciService.postAudioAuditAsync(request, new CosXmlResultListener() {@Override
public void onSuccess(CosXmlRequest request, CosXmlResult cosResult) {// `result` is the result of the submitted audio moderation job.
// For detailed fields, see the API documentation or SDK source code.
PostAuditResult result = (PostAuditResult) cosResult;}@Override
public void onFail(CosXmlRequest request, CosXmlClientException clientException,
CosXmlServiceException serviceException) {if (clientException != null) {clientException.printStackTrace();} else {serviceException.printStackTrace();}}});©2013-2022 Tencent Cloud. All rights reserved.

Page 106 of 1869

Cloud Infinite

：

Note

For more complete samples, visit GitHub.

Querying Audio Moderation Job Result
Feature description
This API is used to query the result of an audio moderation job.

：

Note

The COS Android SDK version should not be earlier than v5.8.7.

Sample code// Bucket name in the format of BucketName-APPID
String bucket = "examplebucket-1250000000";// Moderation job ID
String jobId = "iab1ca9fc8a3ed11ea834c525400863904";
GetAudioAuditRequest request = new GetAudioAuditRequest(bucket, jobId);// `CIService` is a subclass of `CosXmlService` and has the same initialization m
ethod as it.
ciService.getAudioAuditAsync(request, new CosXmlResultListener() {@Override
public void onSuccess(CosXmlRequest request, CosXmlResult cosResult) {// `result` is the result of the audio moderation job.
// For detailed fields, see the API documentation or SDK source code.
GetAudioAuditResult result = (GetAudioAuditResult) cosResult;}@Override
public void onFail(CosXmlRequest request, CosXmlClientException clientException,
CosXmlServiceException serviceException) {if (clientException != null) {clientException.printStackTrace();} else {serviceException.printStackTrace();}}});©2013-2022 Tencent Cloud. All rights reserved.

Page 107 of 1869

Cloud Infinite

：

Note

For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 108 of 1869

Cloud Infinite

Text Moderation：

Last updated 2023-02-06 15:59:30

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.

：

Note

To use the content moderation service, you need to have the permission to use CI:

For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for text moderation.
API

Operation

Description

PostTextAudit

Submitting a text moderation job

Submits a text moderation job.

Querying the text moderation job

Queries the result of the specified text moderation

resultjob.

GetTextAudit

SDK API References
For the parameters and method descriptions of all the APIs in the SDK, see SDK API Reference.

Submitting a Text Moderation Job
Feature description
This API is used to submit a text moderation job.

：

Note

The COS Android SDK version should not be earlier than v5.8.7.

©2013-2022 Tencent Cloud. All rights reserved.

Page 109 of 1869

Cloud Infinite

Sample code// Bucket name in the format of BucketName-APPID
String bucket = "examplebucket-1250000000";// Object key, i.e., the full path of a COS object. If the object is in a directo
ry, the path should be "dir1/object1".
String cosPath = "dir1/exampleobject.txt";// URL of the text. Either `Object` or `Url` can be selected at a time.
String url = "https://myqcloud.com/%205text.txt";// When the input content is plain text, it needs to be Base64-encoded first. The
length of the original text before encoding cannot exceed 10,000 UTF-8 characters. If the length limit is exceeded, the API will report an error.
String content = Base64.encodeToString("Test text".getBytes(Charset.forName("UTF8")), Base64.NO_WRAP);
PostTextAuditRequest request = new PostTextAuditRequest(bucket);request.setObject(cosPath);request.setUrl(url);
request.setContent(content);// Set the original content, which can contain up to 512 bytes. This field will be returned in the response as-is.
request.setDataId("DataId");// Callback address, which must start with `http://` or `https://`.
request.setCallback("https://github.com");// Structure of the callback content. Valid values: `Simple` (the callback conten
t contains basic information), `Detail` (the callback content contains detailed information). Default value: `Simple`.
request.setCallbackVersion("Detail");// The scene to be moderated, such as `Porn` (pornography) and `Ads` (advertising). You can pass in multiple types and separate them by comma, such as `Porn,Ads`.
request.setDetectType("Porn,Ads");// `CIService` is a subclass of `CosXmlService` and has the same initialization m
ethod as it.
ciService.postTextAuditAsync(request, new CosXmlResultListener() {@Override
public void onSuccess(CosXmlRequest request, CosXmlResult cosResult) {// `result` is the result of the submitted text moderation job.
// For detailed fields, see the API documentation or SDK source code.
TextAuditResult result = (TextAuditResult) cosResult;}@Override
public void onFail(CosXmlRequest request, CosXmlClientException clientException,
CosXmlServiceException serviceException) {if (clientException != null) {clientException.printStackTrace();©2013-2022 Tencent Cloud. All rights reserved.

Page 110 of 1869

Cloud Infinite} else {serviceException.printStackTrace();
}
}
});

：

Note

For more complete samples, visit GitHub.

Querying Text Moderation Job Result
Feature description
This API is used to query the result of the specified text moderation job.

：

Note

The COS Android SDK version should not be earlier than v5.8.7.

Sample code// Bucket name in the format of BucketName-APPID
String bucket = "examplebucket-1250000000";// Moderation job ID
String jobId = "iab1ca9fc8a3ed11ea834c525400863904";
GetTextAuditRequest request = new GetTextAuditRequest(bucket, jobId);// `CIService` is a subclass of `CosXmlService` and has the same initialization m
ethod as it.
ciService.getTextAuditAsync(request, new CosXmlResultListener() {@Override
public void onSuccess(CosXmlRequest request, CosXmlResult cosResult) {// `result` is the result of the text moderation job.
// For detailed fields, see the API documentation or SDK source code.
TextAuditResult result = (TextAuditResult) cosResult;}@Override
public void onFail(CosXmlRequest request, CosXmlClientException clientException,
CosXmlServiceException serviceException) {if (clientException != null) {clientException.printStackTrace();} else {©2013-2022 Tencent Cloud. All rights reserved.

Page 111 of 1869

Cloud Infinite

serviceException.printStackTrace();
}
}
});

：

Note

For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 112 of 1869

Cloud Infinite

File Moderation：

Last updated 2023-02-06 15:59:30

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.

：

Note

To use the content moderation service, you need to have the permission to use CI:

For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for file moderation.
API

Operation

Description

PostDocumentAudit

Submitting a file moderation job

Submits a file moderation job.

GetDocumentAudit

Querying the file moderation job
resultQueries the result of the specified file moderation
job.

SDK API References
For the parameters and method descriptions of all the APIs in the SDK, see SDK API Reference.

Submitting a File Moderation Job
Feature description
This API is used to submit a file moderation job.

：

Note

The COS Android SDK version should not be earlier than v5.8.7.

©2013-2022 Tencent Cloud. All rights reserved.

Page 113 of 1869

Cloud Infinite

Sample code// Bucket name in the format of BucketName-APPID
String bucket = "examplebucket-1250000000";// Object key, i.e., the full path of a COS object. If the object is in a directo
ry, the path should be "dir1/object1".
String cosPath = "dir1/exampleobject.pdf";// URL of the file. Either `Object` or `Url` can be selected at a time.
String url = "https://myqcloud.com/%205Document.pdf";
PostDocumentAuditRequest request = new PostDocumentAuditRequest(bucket);request.setObject(cosPath);request.setUrl(url);// Set the original content, which can contain up to 512 bytes. This field will be returned in the response as-is.
request.setDataId("DataId");// Callback address, which must start with `http://` or `https://`.
request.setCallback("https://github.com");// The scene to be moderated, such as `Porn` (pornography) and `Ads` (advertising). You can pass in multiple types and separate them by comma, such as `Porn,Ads`.
request.setDetectType("Porn,Ads");// `CIService` is a subclass of `CosXmlService` and has the same initialization m
ethod as it.
ciService.postDocumentAuditAsync(request, new CosXmlResultListener() {@Override
public void onSuccess(CosXmlRequest request, CosXmlResult cosResult) {// `result` is the result of the submitted file moderation job.
// For detailed fields, see the API documentation or SDK source code.
PostAuditResult result = (PostAuditResult) cosResult;}@Override
public void onFail(CosXmlRequest request, CosXmlClientException clientException,
CosXmlServiceException serviceException) {if (clientException != null) {clientException.printStackTrace();} else {serviceException.printStackTrace();
}
}
});

：

Note

For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 114 of 1869

Cloud Infinite

Querying File Moderation Job Result
Feature description
This API is used to query the result of the specified file moderation job.

：

Note

The COS Android SDK version should not be earlier than v5.8.7.

Sample code// Bucket name in the format of BucketName-APPID
String bucket = "examplebucket-1250000000";// Moderation job ID
String jobId = "iab1ca9fc8a3ed11ea834c525400863904";
GetDocumentAuditRequest request = new GetDocumentAuditRequest(bucket, jobId);// `CIService` is a subclass of `CosXmlService` and has the same initialization m
ethod as it.
ciService.getDocumentAuditAsync(request, new CosXmlResultListener() {@Override
public void onSuccess(CosXmlRequest request, CosXmlResult cosResult) {// `result` is the result of the file moderation job.
// For detailed fields, see the API documentation or SDK source code.
GetDocumentAuditResult result = (GetDocumentAuditResult) cosResult;}@Override
public void onFail(CosXmlRequest request, CosXmlClientException clientException,
CosXmlServiceException serviceException) {if (clientException != null) {clientException.printStackTrace();} else {serviceException.printStackTrace();
}
}
});

：

Note

For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 115 of 1869

Cloud Infinite

C SDKGetting Started：

Last updated 2024-02-29 16:06:23

Download and Installation
Relevant resources
Download COS XML C SDK source code: XML C SDK.
Download demo: XML C SDK Demo.
For the SDK changelog, see Changelog.
For SDK FAQs, see C SDK FAQs.
Note:
If you encounter errors such as non-existent functions or methods when using the SDK, you can update the SDK to
the latest version and try again.
Environmental dependencies
Dependent library: libcurl apr apr-util minixml.
Installing SDK
1. Download the CMake tool (v2.6.0 and higher recommended) here and install it as shown below:©2013-2022 Tencent Cloud. All rights reserved.

Page 116 of 1869

Cloud Infinite./configure
makemake install
2. Download libcurl (v7.32.0 or higher recommended) here and install it as shown below:©2013-2022 Tencent Cloud. All rights reserved.

Page 117 of 1869

Cloud Infinite./configure
makemake install
3. Download apr (v1.5.2 or higher recommended) here and install it as shown below:©2013-2022 Tencent Cloud. All rights reserved.

Page 118 of 1869

Cloud Infinite./configure
makemake install
4. Download apr-util (v1.5.4 or higher recommended) here and install it as shown below. You need to specify the -with-apr option during installation.

©2013-2022 Tencent Cloud. All rights reserved.

Page 119 of 1869

Cloud Infinite./configure --with-apr=/your/apr/install/pathmakemake install
5. Download minixml (v2.8 - 2.12 recommended) here and install it as shown below:©2013-2022 Tencent Cloud. All rights reserved.

Page 120 of 1869

Cloud Infinite./configure
makemake install
6. Compile the COS C SDK. Download the XML C SDK source code and run the following compiling commands:©2013-2022 Tencent Cloud. All rights reserved.

Page 121 of 1869

Cloud Infinite

cmake .
make
make install

Getting Started
Below is the general process of using COS XML C SDK.
1. Initialize the SDK.

©2013-2022 Tencent Cloud. All rights reserved.

Page 122 of 1869

Cloud Infinite

2. Set the request option parameters. For the definitions of parameters such as APPID, SecretId, SecretKey, andBucket, see COS Glossary.
APPID is one of the account IDs assigned by the system after you register for a Tencent Cloud account.
access_key_id and access_key_secret are account API keys.
endpoint is the COS access domain name. For more information, see Regions and Access Endpoints. For
example, the endpoint of the Guangzhou region is cos.ap-guangzhou.myqcloud.com , and the endpoint of a
global acceleration domain name is cos.accelerate.myqcloud.com . You can add "http" or "https" to theendpoints. The SDK accesses COS via HTTP by default. For example, the endpoint for accessing the Guangzhou
region via HTTPS is https://cos.ap-guangzhou.myqcloud.com .
is_cname specifies whether an endpoint is a custom domain name. If is_cname is set to 1, the endpoint is acustom domain name.
3. Set the parameters required for APIs.
4. Call the SDK API to initiate a request and get the response.

Initialization
Note:
We recommend you use a temporary key as instructed in Generating and Using Temporary Keys to call the SDK for
security purposes. When you apply for a temporary key, follow the Notes on Principle of Least Privilege to avoid
leaking resources besides your buckets and objects.
If you must use a permanent key, we recommend you follow the Notes on Principle of Least Privilege to limit the scopeof permission on the permanent key.

©2013-2022 Tencent Cloud. All rights reserved.

Page 123 of 1869

Cloud Infinite

int main(int argc, char *argv[]){/* Call the cos_http_io_initialize method at the program entry to perform certa
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {exit(1);}/* Call a COS SDK API to upload/download files *//* ... User logic code, omitted here *//* Call the cos_http_io_deinitialize method to release global resources allocat©2013-2022 Tencent Cloud. All rights reserved.

Page 124 of 1869

Cloud Infinite

cos_http_io_deinitialize();
return 0;}

Initializing request options/* Equivalent to `apr_pool_t`, the memory pool for memory management. The implement
cos_pool_t *pool;cos_request_options_t *options;©2013-2022 Tencent Cloud. All rights reserved.

Page 125 of 1869

Cloud Infinite/* Create a new memory pool. The second parameter is NULL, indicating that it is nocos_pool_create(&pool, NULL);/* Create and initialize `options`. This parameter contains global configuration in* The memory of `options` is allocated by the pool, and will be released upon pool*/
options = cos_request_options_create(pool);
options->config = cos_config_create(options->pool);/* cos_str_set is a cos_string_t type initialized with a char* string */cos_str_set(&options->config->endpoint, "<user's endpoint>");cos_str_set(&options->config->access_key_id, "<user's SecretId>");cos_str_set(&options->config->access_key_secret, "<user's SecretKey>");cos_str_set(&options->config->appid, "<user's AppId>");// Enter// This// This// This/* You can use a temporary key by setting `sts_token`. When you use a temporary key//cos_str_set(&options->config->sts_token, "MyTokenString");/* Whether CNAME is used */options->config->is_cname = 0;/* Use a custom domain name to access COS *//*options->config->is_cname = 1;
cos_str_set(&options->config->endpoint, "<Custom domain name>");*//* Used to set network-related parameters, such as the timeout duration */options->ctl = cos_http_controller_create(options->pool, 0);/* Used to set whether to add Content-MD5 header automatically to the upload requescos_set_content_md5_enable(options->ctl, COS_FALSE);/* Used to set the request routing address and port. Normally, you do not need to s//cos_set_request_route(options->ctl, "192.168.12.34", 80);Note:
For more information about how to generate and use a temporary key, see Generating and Using Temporary Keys.

Creating a bucket©2013-2022 Tencent Cloud. All rights reserved.

Page 126 of 1869

Cloud Infinite

cos_pool_t *p = NULL;
int is_cname = 0;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_acl_e cos_acl = COS_ACL_PRIVATE;
cos_string_t bucket;
cos_table_t *resp_headers = NULL;/* Create a new memory pool. The second parameter is NULL, indicating that it is nocos_pool_create(&p, NULL);©2013-2022 Tencent Cloud. All rights reserved.

Page 127 of 1869

Cloud Infinite/* Create and initialize `options`. This parameter contains global configuration in* The memory of `options` is allocated by the pool, and will be released upon pool*/
options = cos_request_options_create(p);options->config = cos_config_create(options->pool);
init_test_config(options->config, is_cname);/* Set configuration information such as appid, endpoint, access_key_id, acces_key_
cos_str_set(&options->config->endpoint, TEST_COS_ENDPOINT);
cos_str_set(&options->config->access_key_id, TEST_ACCESS_KEY_ID);
cos_str_set(&options->config->access_key_secret, TEST_ACCESS_KEY_SECRET);
cos_str_set(&options->config->appid, TEST_APPID);
options->config->is_cname = is_cname;options->ctl = cos_http_controller_create(options->pool, 0);/* Enter the bucket name in the format of BucketName-APPID. */cos_str_set(&bucket, TEST_BUCKET_NAME);/* Call an API to create a bucket */s = cos_create_bucket(options, &bucket, cos_acl, &resp_headers);
if (cos_status_is_ok(s)) {printf("create bucket succeeded\\n");} else {printf("create bucket failed\\n");}//destroy memory poolcos_pool_destroy(p);Querying objects©2013-2022 Tencent Cloud. All rights reserved.

Page 128 of 1869

Cloud Infinite

cos_pool_t *p = NULL;
int is_cname = 0;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_list_object_params_t *list_params = NULL;
cos_string_t bucket;
cos_table_t *resp_headers = NULL;/* Re-create a new memory pool. The second parameter is NULL, which indicates it iscos_pool_create(&p, NULL);©2013-2022 Tencent Cloud. All rights reserved.

Page 129 of 1869

Cloud Infinite/* Create and initialize `options`. This parameter contains global configuration in* The memory of `options` is allocated by the pool, and will be released upon pool*/
options = cos_request_options_create(p);options->config = cos_config_create(options->pool);
init_test_config(options->config, is_cname);/* Set configuration information such as appid, endpoint, access_key_id, acces_key_
cos_str_set(&options->config->endpoint, TEST_COS_ENDPOINT);
cos_str_set(&options->config->access_key_id, TEST_ACCESS_KEY_ID);
cos_str_set(&options->config->access_key_secret, TEST_ACCESS_KEY_SECRET);
cos_str_set(&options->config->appid, TEST_APPID);
options->config->is_cname = is_cname;options->ctl = cos_http_controller_create(options->pool, 0);/* The bucket name entered here must be in the format of BucketName-APPID. */cos_str_set(&bucket, TEST_BUCKET_NAME);/* Call an API to query object list */list_params = cos_create_list_object_params(p);cos_str_set(&list_params->encoding_type, "url");s = cos_list_object(options, &bucket, list_params, &resp_headers);
if (cos_status_is_ok(s)) {printf("list object succeeded\\n");} else {printf("list object failed\\n");}//destroy memory poolcos_pool_destroy(p);Uploading an object©2013-2022 Tencent Cloud. All rights reserved.

Page 130 of 1869

Cloud Infinite

cos_pool_t *p = NULL;
int is_cname = 0;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_string_t bucket;
cos_string_t object;cos_string_t file;
cos_table_t *resp_headers = NULL;/* Re-create a new memory pool. The second parameter is NULL, which indicates it iscos_pool_create(&p, NULL);©2013-2022 Tencent Cloud. All rights reserved.

Page 131 of 1869

Cloud Infinite/* Create and initialize `options`. This parameter contains global configuration in* The memory of `options` is allocated by the pool, and will be released upon pool*/
options = cos_request_options_create(p);options->config = cos_config_create(options->pool);
init_test_config(options->config, is_cname);/* Set configuration information such as appid, endpoint, access_key_id, acces_key_
cos_str_set(&options->config->endpoint, TEST_COS_ENDPOINT);
cos_str_set(&options->config->access_key_id, TEST_ACCESS_KEY_ID);
cos_str_set(&options->config->access_key_secret, TEST_ACCESS_KEY_SECRET);
cos_str_set(&options->config->appid, TEST_APPID);
options->config->is_cname = is_cname;options->ctl = cos_http_controller_create(options->pool, 0);/* The bucket name entered here must be in the format of BucketName-APPID. */cos_str_set(&bucket, TEST_BUCKET_NAME);/* Call an API to upload an object */cos_str_set(&file, TEST_DOWNLOAD_NAME);
cos_str_set(&object, TEST_OBJECT_NAME);
s = cos_put_object_from_file(options, &bucket, &object, &file, NULL, &resp_headers)if (cos_status_is_ok(s)) {printf("put object succeeded\\n");} else {printf("put object failed\\n");}//destroy memory poolcos_pool_destroy(p);Downloading an object©2013-2022 Tencent Cloud. All rights reserved.

Page 132 of 1869

Cloud Infinite

cos_pool_t *p = NULL;
int is_cname = 0;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_string_t bucket;
cos_string_t object;cos_string_t file;
cos_table_t *resp_headers = NULL;/* Re-create a new memory pool. The second parameter is NULL, which indicates it iscos_pool_create(&p, NULL);©2013-2022 Tencent Cloud. All rights reserved.

Page 133 of 1869

Cloud Infinite/* Create and initialize `options`. This parameter contains global configuration in* The memory of `options` is allocated by the pool, and will be released upon pool*/
options = cos_request_options_create(p);options->config = cos_config_create(options->pool);
init_test_config(options->config, is_cname);/* Set configuration information such as appid, endpoint, access_key_id, acces_key_
cos_str_set(&options->config->endpoint, TEST_COS_ENDPOINT);
cos_str_set(&options->config->access_key_id, TEST_ACCESS_KEY_ID);
cos_str_set(&options->config->access_key_secret, TEST_ACCESS_KEY_SECRET);
cos_str_set(&options->config->appid, TEST_APPID);
options->config->is_cname = is_cname;options->ctl = cos_http_controller_create(options->pool, 0);/* The bucket name entered here must be in the format of BucketName-APPID. */cos_str_set(&bucket, TEST_BUCKET_NAME);/* Call an API to download an object */cos_str_set(&file, TEST_DOWNLOAD_NAME);
cos_str_set(&object, TEST_OBJECT_NAME);
s = cos_get_object_to_file(options, &bucket, &object, NULL, NULL, &file, &resp_head
if (cos_status_is_ok(s)) {printf("get object succeeded\\n");} else {printf("get object failed\\n");}//destroy memory poolcos_pool_destroy(p);Deleting an object©2013-2022 Tencent Cloud. All rights reserved.

Page 134 of 1869

Cloud Infinite

cos_pool_t *p = NULL;
int is_cname = 0;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_string_t bucket;
cos_string_t object;cos_table_t *resp_headers = NULL;/* Create a new memory pool. The second parameter is NULL, indicating that it is nocos_pool_create(&p, NULL);©2013-2022 Tencent Cloud. All rights reserved.

Page 135 of 1869

Cloud Infinite/* Create and initialize `options`. This parameter contains global configuration in* The memory of `options` is allocated by the pool, and will be released upon pool*/
options = cos_request_options_create(p);options->config = cos_config_create(options->pool);
init_test_config(options->config, is_cname);/* Set configuration information such as appid, endpoint, access_key_id, acces_key_
cos_str_set(&options->config->endpoint, TEST_COS_ENDPOINT);
cos_str_set(&options->config->access_key_id, TEST_ACCESS_KEY_ID);
cos_str_set(&options->config->access_key_secret, TEST_ACCESS_KEY_SECRET);
cos_str_set(&options->config->appid, TEST_APPID);
options->config->is_cname = is_cname;options->ctl = cos_http_controller_create(options->pool, 0);/* The bucket name entered here must be in the format of BucketName-APPID. */cos_str_set(&bucket, TEST_BUCKET_NAME);/* Call an API to delete an object */cos_str_set(&object, TEST_OBJECT_NAME);
s = cos_delete_object(options, &bucket, &object, &resp_headers);
if (cos_status_is_ok(s)) {printf("delete object succeeded\\n");} else {printf("delete object failed\\n");}//destroy memory poolcos_pool_destroy(p);©2013-2022 Tencent Cloud. All rights reserved.

Page 136 of 1869

Cloud Infinite

Image Processing
Persistent Image Processing：

Last updated 2024-02-29 16:06:23

Overview
This document provides an overview of APIs and SDK code samples for persistent image processing.
API

Description

Persistent image
processing

Processes an image during upload, or processes an image stored in COS and saves
the processing result to COS.

Processing During Upload
Feature description
COS allows you to process images during upload. To enable this, add Pic-Operations to the request header
and set relevant parameters. You can also save the input images and processing results to COS. Currently, images
within 20 MB can be processed.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 137 of 1869

Cloud Infinite

cos_status_t *ci_put_object_from_file(const cos_request_options_t *options,const cos_string_t *bucket,
const cos_string_t *object,
const cos_string_t *filename,cos_table_t *headers,
cos_table_t **resp_headers,
ci_operation_result_t **results)

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 138 of 1869

Cloud Infinite#include "cos_http_io.h"#include "cos_api.h"#include "cos_log.h"#include <unistd.h>// `endpoint` is the COS access domain name. For more information, visit https://clstatic char TEST_COS_ENDPOINT[] = "cos.ap-guangzhou.myqcloud.com";// A developer-owned secret ID/key used for the project. It can be obtained at httpstatic char *TEST_ACCESS_KEY_ID;//your secret_id
static char *TEST_ACCESS_KEY_SECRET;//your secret_key// A unique user-level resource identifier for COS access. It can be obtained at ht©2013-2022 Tencent Cloud. All rights reserved.

Page 139 of 1869

Cloud Infinite

static char TEST_APPID[] = "<APPID>";//your appid// COS bucket name in the format of [bucket]-[appid], for example, `mybucket-125366
static char TEST_BUCKET_NAME[] = "<bucketname-appid>";void log_status(cos_status_t *s){
cos_warn_log("status->code: %d", s->code);if (s->error_code) cos_warn_log("status->error_code: %s", s->error_code);if (s->error_msg) cos_warn_log("status->error_msg: %s", s->error_msg);
if (s->req_id) cos_warn_log("status->req_id: %s", s->req_id);}void init_test_config(cos_config_t *config, int is_cname){cos_str_set(&config->endpoint, TEST_COS_ENDPOINT);
cos_str_set(&config->access_key_id, TEST_ACCESS_KEY_ID);
cos_str_set(&config->access_key_secret, TEST_ACCESS_KEY_SECRET);
cos_str_set(&config->appid, TEST_APPID);
config->is_cname = is_cname;}void init_test_request_options(cos_request_options_t *options, int is_cname){options->config = cos_config_create(options->pool);
init_test_config(options->config, is_cname);
options->ctl = cos_http_controller_create(options->pool, 0);}
void test_put_image_process(){
cos_pool_t *p = NULL;
int is_cname = 0;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_string_t bucket;
cos_string_t object;cos_string_t file;
cos_table_t *headers = NULL;
cos_table_t *resp_headers;
ci_operation_result_t *results = NULL;
cos_pool_create(&p, NULL);
options = cos_request_options_create(p);init_test_request_options(options, is_cname);
cos_str_set(&bucket, TEST_BUCKET_NAME);// Process during upload©2013-2022 Tencent Cloud. All rights reserved.

Page 140 of 1869

Cloud Infinite

headers = cos_table_make(p, 1);
apr_table_addn(headers, "pic-operations", "{\\"is_pic_info\\":1,\\"rules\\":[{\
cos_str_set(&file, "test.jpg");
cos_str_set(&object, "test.jpg");s = ci_put_object_from_file(options, &bucket, &object, &file, headers, &resp_he
if (!cos_status_is_ok(s)) {printf("put object failed: %s\\n", s->req_id);}
printf("origin key: %s\\n", results->origin.key.data);
printf("process key: %s\\n", results->object.key.data);// Terminate the memory poolcos_pool_destroy(p);}int main(int argc, char *argv[]){// Get `SECRETID` and `SECRETKEY` from environment variables
TEST_ACCESS_KEY_ID= getenv("COS_SECRETID");
TEST_ACCESS_KEY_SECRET = getenv("COS_SECRETKEY");
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {exit(1);}//set log level, default COS_LOG_WARN
cos_log_set_level(COS_LOG_WARN);//set log output, default stderr
cos_log_set_output(NULL);
test_put_image_process();
cos_http_io_deinitialize();
return 0;}

Parameter description
Parameter

Description

Type

options

COS request options

StructbucketBucket name in the format of BucketName-APPID

StringobjectObject name

String©2013-2022 Tencent Cloud. All rights reserved.

Page 141 of 1869

Cloud Infinite

filename

Filename of the local object

Stringheaders

COS request headers

Structresp_headers

Returned HTTP response headers

Structresults

Processing result of the in-cloud data

StructProcessing In-Cloud Data
Feature description
This API is used to process an image stored in COS and save the processing result to COS.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 142 of 1869

Cloud Infinite

cos_status_t *ci_image_process(const cos_request_options_t *options,const cos_string_t *bucket,
const cos_string_t *object,cos_table_t *headers,
cos_table_t **resp_headers,
ci_operation_result_t *results);

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 143 of 1869

Cloud Infinite#include "cos_http_io.h"#include "cos_api.h"#include "cos_log.h"#include <unistd.h>// `endpoint` is the COS access domain name. For more information, visit https://clstatic char TEST_COS_ENDPOINT[] = "cos.ap-guangzhou.myqcloud.com";// A developer-owned secret ID/key used for the project. It can be obtained at httpstatic char *TEST_ACCESS_KEY_ID;//your secret_id
static char *TEST_ACCESS_KEY_SECRET;//your secret_key// A unique user-level resource identifier for COS access. It can be obtained at ht©2013-2022 Tencent Cloud. All rights reserved.

Page 144 of 1869

Cloud Infinite

static char TEST_APPID[] = "<APPID>";//your appid// COS bucket name in the format of [bucket]-[appid], for example, `mybucket-125366
static char TEST_BUCKET_NAME[] = "<bucketname-appid>";void log_status(cos_status_t *s){
cos_warn_log("status->code: %d", s->code);if (s->error_code) cos_warn_log("status->error_code: %s", s->error_code);if (s->error_msg) cos_warn_log("status->error_msg: %s", s->error_msg);
if (s->req_id) cos_warn_log("status->req_id: %s", s->req_id);}void init_test_config(cos_config_t *config, int is_cname){cos_str_set(&config->endpoint, TEST_COS_ENDPOINT);
cos_str_set(&config->access_key_id, TEST_ACCESS_KEY_ID);
cos_str_set(&config->access_key_secret, TEST_ACCESS_KEY_SECRET);
cos_str_set(&config->appid, TEST_APPID);
config->is_cname = is_cname;}void init_test_request_options(cos_request_options_t *options, int is_cname){options->config = cos_config_create(options->pool);
init_test_config(options->config, is_cname);
options->ctl = cos_http_controller_create(options->pool, 0);}
void test_ci_image_process(){
cos_pool_t *p = NULL;
int is_cname = 0;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_string_t bucket;
cos_string_t object;cos_table_t *headers = NULL;
cos_table_t *resp_headers;
ci_operation_result_t *results = NULL;
cos_pool_create(&p, NULL);
options = cos_request_options_create(p);init_test_request_options(options, is_cname);
cos_str_set(&bucket, TEST_BUCKET_NAME);
cos_str_set(&object, "test.jpg");
headers = cos_table_make(p, 1);©2013-2022 Tencent Cloud. All rights reserved.

Page 145 of 1869

Cloud Infinite

apr_table_addn(headers, "pic-operations", "{\\"is_pic_info\\":1,\\"rules\\":[{\
s = ci_image_process(options, &bucket, &object, headers, &resp_headers, &resultif (!cos_status_is_ok(s)) {printf("ci image process fail, req_id:%s\\n", s->req_id);}
printf("origin key: %s\\n", results->origin.key.data);
printf("process key: %s\\n", results->object.key.data);
cos_pool_destroy(p);}int main(int argc, char *argv[]){// Get `SECRETID` and `SECRETKEY` from environment variables
TEST_ACCESS_KEY_ID= getenv("COS_SECRETID");
TEST_ACCESS_KEY_SECRET = getenv("COS_SECRETKEY");
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {exit(1);}//set log level, default COS_LOG_WARN
cos_log_set_level(COS_LOG_WARN);//set log output, default stderr
cos_log_set_output(NULL);
test_ci_image_process();
cos_http_io_deinitialize();
return 0;}

Parameter description
Parameter

Description

Type

options

COS request options

StructbucketBucket name in the format of BucketName-APPID . The bucket nameentered here must be in this format.

stringobjectObject namestringheaders

COS request headers. You need to add the Pic-Operations header.

Struct©2013-2022 Tencent Cloud. All rights reserved.

Page 146 of 1869

Cloud Infinite

resp_headers

Returned HTTP response headers

Structresults

Processing result of the in-cloud data

Struct©2013-2022 Tencent Cloud. All rights reserved.

Page 147 of 1869

Cloud Infinite

Basic Image Processing：

Last updated 2024-02-29 16:06:23

Overview
This document provides an overview of APIs and SDK code samples for basic image processing.
API

Description

Scaling

Scales up/down an image.

Cropping

Crops an image, including regular cropping, scaling and cropping, cropping to circle,
rounded corner cropping, and smart face cropping.

Rotation

Rotates an image, including regular rotation and adaptive rotation.

Format conversion

Converts the format of an image, optimizes the GIF format, and performs progressive
display.

Quality change

Adjusts the quality of an image.

Gaussian blurring

Blurs an image by a Gaussian function.

Sharpening

Sharpens an image.

Image watermark

Adds a watermark to an image.

Text watermark

Adds a real-time text watermark to an image.

Basic image
information

Queries the basic information of an image, such as format, width, and height.

acquisition
Image EXIF dataacquisition

Queries the EXIF data of an image.

Image average hue
acquisition

Queries the average hue of an image.

Metadata removal

Removes the image metadata, including the EXIF data.

Quick thumbnail
template

Generates a thumbnail through an image processing template.

Pipeline operator

Performs multiple operations on an image in sequence.

©2013-2022 Tencent Cloud. All rights reserved.

Page 148 of 1869

Cloud Infinite

ScalingFeature description
CI uses the imageMogr2 API to scale images.
Sample request#include "cos_http_io.h"#include "cos_api.h"#include "cos_log.h"©2013-2022 Tencent Cloud. All rights reserved.

Page 149 of 1869

Cloud Infinite#include <unistd.h>// `endpoint` is the COS access domain name. For more information, visit https://clstatic char TEST_COS_ENDPOINT[] = "cos.ap-guangzhou.myqcloud.com";// A developer-owned secret ID/key used for the project. It can be obtained at httpstatic char *TEST_ACCESS_KEY_ID;//your secret_id
static char *TEST_ACCESS_KEY_SECRET;//your secret_key// A unique user-level resource identifier for COS access. It can be obtained at ht
static char TEST_APPID[] = "<APPID>";//your appid// COS bucket name in the format of [bucket]-[appid], for example, `mybucket-125366
static char TEST_BUCKET_NAME[] = "<bucketname-appid>";void log_status(cos_status_t *s){
cos_warn_log("status->code: %d", s->code);if (s->error_code) cos_warn_log("status->error_code: %s", s->error_code);if (s->error_msg) cos_warn_log("status->error_msg: %s", s->error_msg);
if (s->req_id) cos_warn_log("status->req_id: %s", s->req_id);}void init_test_config(cos_config_t *config, int is_cname){cos_str_set(&config->endpoint, TEST_COS_ENDPOINT);
cos_str_set(&config->access_key_id, TEST_ACCESS_KEY_ID);
cos_str_set(&config->access_key_secret, TEST_ACCESS_KEY_SECRET);
cos_str_set(&config->appid, TEST_APPID);
config->is_cname = is_cname;}void init_test_request_options(cos_request_options_t *options, int is_cname){options->config = cos_config_create(options->pool);
init_test_config(options->config, is_cname);
options->ctl = cos_http_controller_create(options->pool, 0);}
void test_image_scale(){
cos_pool_t *p = NULL;
int is_cname = 0;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_string_t bucket;
cos_string_t object;cos_string_t file;
cos_table_t *resp_headers;
cos_table_t *params = NULL;©2013-2022 Tencent Cloud. All rights reserved.

Page 150 of 1869

Cloud Infinite

cos_pool_create(&p, NULL);
options = cos_request_options_create(p);init_test_request_options(options, is_cname);
cos_str_set(&bucket, TEST_BUCKET_NAME);
params = cos_table_make(p, 1);
apr_table_addn(params, "imageMogr2/thumbnail/!50p", "");
cos_str_set(&file, "test.jpg");
cos_str_set(&object, "test.jpg");s = cos_get_object_to_file(options, &bucket, &object, NULL, params, &file, &res
log_status(s);if (!cos_status_is_ok(s)) {printf("cos_get_object_to_file fail, req_id:%s\\n", s->req_id);}
cos_pool_destroy(p);}int main(int argc, char *argv[]){// Get `SECRETID` and `SECRETKEY` from environment variables
TEST_ACCESS_KEY_ID= getenv("COS_SECRETID");
TEST_ACCESS_KEY_SECRET = getenv("COS_SECRETKEY");
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {exit(1);}//set log level, default COS_LOG_WARN
cos_log_set_level(COS_LOG_WARN);//set log output, default stderr
cos_log_set_output(NULL);
test_image_scale();cos_http_io_deinitialize();
return 0;}

Cropping
Feature description©2013-2022 Tencent Cloud. All rights reserved.

Page 151 of 1869

Cloud Infinite

CI uses the imageMogr2 API to crop images, including regular cropping, scaling and cropping, cropping to circle,
rounded corner cropping, and smart face cropping.
Sample request#include "cos_http_io.h"#include "cos_api.h"#include "cos_log.h"#include <unistd.h>// `endpoint` is the COS access domain name. For more information, visit https://cl©2013-2022 Tencent Cloud. All rights reserved.

Page 152 of 1869

Cloud Infinite

static char TEST_COS_ENDPOINT[] = "cos.ap-guangzhou.myqcloud.com";// A developer-owned secret ID/key used for the project. It can be obtained at httpstatic char *TEST_ACCESS_KEY_ID;//your secret_id
static char *TEST_ACCESS_KEY_SECRET;//your secret_key// A unique user-level resource identifier for COS access. It can be obtained at ht
static char TEST_APPID[] = "<APPID>";//your appid// COS bucket name in the format of [bucket]-[appid], for example, `mybucket-125366
static char TEST_BUCKET_NAME[] = "<bucketname-appid>";void log_status(cos_status_t *s){
cos_warn_log("status->code: %d", s->code);if (s->error_code) cos_warn_log("status->error_code: %s", s->error_code);if (s->error_msg) cos_warn_log("status->error_msg: %s", s->error_msg);
if (s->req_id) cos_warn_log("status->req_id: %s", s->req_id);}void init_test_config(cos_config_t *config, int is_cname){cos_str_set(&config->endpoint, TEST_COS_ENDPOINT);
cos_str_set(&config->access_key_id, TEST_ACCESS_KEY_ID);
cos_str_set(&config->access_key_secret, TEST_ACCESS_KEY_SECRET);
cos_str_set(&config->appid, TEST_APPID);
config->is_cname = is_cname;}void init_test_request_options(cos_request_options_t *options, int is_cname){options->config = cos_config_create(options->pool);
init_test_config(options->config, is_cname);
options->ctl = cos_http_controller_create(options->pool, 0);}
void test_image_cut(){
cos_pool_t *p = NULL;
int is_cname = 0;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_string_t bucket;
cos_string_t object;cos_string_t file;
cos_table_t *resp_headers;
cos_table_t *params = NULL;
cos_pool_create(&p, NULL);
options = cos_request_options_create(p);©2013-2022 Tencent Cloud. All rights reserved.

Page 153 of 1869

Cloud Infinite

init_test_request_options(options, is_cname);
cos_str_set(&bucket, TEST_BUCKET_NAME);
params = cos_table_make(p, 1);
apr_table_addn(params, "imageMogr2/cut/600x600x100x10", "");
cos_str_set(&file, "test.jpg");
cos_str_set(&object, "test.jpg");s = cos_get_object_to_file(options, &bucket, &object, NULL, params, &file, &res
log_status(s);if (!cos_status_is_ok(s)) {printf("cos_get_object_to_file fail, req_id:%s\\n", s->req_id);}
cos_pool_destroy(p);}int main(int argc, char *argv[]){// Get `SECRETID` and `SECRETKEY` from environment variables
TEST_ACCESS_KEY_ID= getenv("COS_SECRETID");
TEST_ACCESS_KEY_SECRET = getenv("COS_SECRETKEY");
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {exit(1);}//set log level, default COS_LOG_WARN
cos_log_set_level(COS_LOG_WARN);//set log output, default stderr
cos_log_set_output(NULL);
test_image_cut();
cos_http_io_deinitialize();
return 0;}

Other basic image processing operations
Feature description
You can perform other basic processing operations on images by changing the value of the operation
parameter. For example, you can rotate the image clockwise by 90 degrees as follows:©2013-2022 Tencent Cloud. All rights reserved.

Page 154 of 1869

Cloud Infinite#include "cos_http_io.h"#include "cos_api.h"#include "cos_log.h"#include <unistd.h>// `endpoint` is the COS access domain name. For more information, visit https://clstatic char TEST_COS_ENDPOINT[] = "cos.ap-guangzhou.myqcloud.com";// A developer-owned secret ID/key used for the project. It can be obtained at httpstatic char *TEST_ACCESS_KEY_ID;//your secret_id
static char *TEST_ACCESS_KEY_SECRET;//your secret_key// A unique user-level resource identifier for COS access. It can be obtained at ht©2013-2022 Tencent Cloud. All rights reserved.

Page 155 of 1869

Cloud Infinite

static char TEST_APPID[] = "<APPID>";//your appid// COS bucket name in the format of [bucket]-[appid], for example, `mybucket-125366
static char TEST_BUCKET_NAME[] = "<bucketname-appid>";void log_status(cos_status_t *s){
cos_warn_log("status->code: %d", s->code);if (s->error_code) cos_warn_log("status->error_code: %s", s->error_code);if (s->error_msg) cos_warn_log("status->error_msg: %s", s->error_msg);
if (s->req_id) cos_warn_log("status->req_id: %s", s->req_id);}void init_test_config(cos_config_t *config, int is_cname){cos_str_set(&config->endpoint, TEST_COS_ENDPOINT);
cos_str_set(&config->access_key_id, TEST_ACCESS_KEY_ID);
cos_str_set(&config->access_key_secret, TEST_ACCESS_KEY_SECRET);
cos_str_set(&config->appid, TEST_APPID);
config->is_cname = is_cname;}void init_test_request_options(cos_request_options_t *options, int is_cname){options->config = cos_config_create(options->pool);
init_test_config(options->config, is_cname);
options->ctl = cos_http_controller_create(options->pool, 0);}
void test_image_rotate(){
cos_pool_t *p = NULL;
int is_cname = 0;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_string_t bucket;
cos_string_t object;cos_string_t file;
cos_table_t *resp_headers;
cos_table_t *params = NULL;
cos_pool_create(&p, NULL);
options = cos_request_options_create(p);init_test_request_options(options, is_cname);
cos_str_set(&bucket, TEST_BUCKET_NAME);
params = cos_table_make(p, 1);
apr_table_addn(params, "imageMogr2/rotate/90", "");

©2013-2022 Tencent Cloud. All rights reserved.

Page 156 of 1869

Cloud Infinite

cos_str_set(&file, "test.jpg");
cos_str_set(&object, "test.jpg");s = cos_get_object_to_file(options, &bucket, &object, NULL, params, &file, &res
log_status(s);if (!cos_status_is_ok(s)) {printf("cos_get_object_to_file fail, req_id:%s\\n", s->req_id);}
cos_pool_destroy(p);}int main(int argc, char *argv[]){// Get `SECRETID` and `SECRETKEY` from environment variables
TEST_ACCESS_KEY_ID= getenv("COS_SECRETID");
TEST_ACCESS_KEY_SECRET = getenv("COS_SECRETKEY");
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {exit(1);}//set log level, default COS_LOG_WARN
cos_log_set_level(COS_LOG_WARN);//set log output, default stderr
cos_log_set_output(NULL);
test_image_rotate();cos_http_io_deinitialize();
return 0;}©2013-2022 Tencent Cloud. All rights reserved.

Page 157 of 1869

Cloud Infinite

Image Advanced Compression：

Last updated 2024-02-29 16:06:22

Overview
This document provides an overview of APIs and SDK code samples for image advanced compression.
API

Description

Imageadvanced

Allows you to easily convert images into formats that provide a high compression ratio, such as
TPG and HEIF. This effectively reduces the transfer time, loading time, and the use ofcompression

bandwidth and traffic.

Method prototype
Image compression is implemented via object download. All you need to do is to add the request parameters in thefollowing syntax:©2013-2022 Tencent Cloud. All rights reserved.

Page 158 of 1869

Cloud Infinite

imageMogr2/format/<Format>
Parameter

Description

formatTarget compression format, which can be TPG or HEIF for thumbnails.

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 159 of 1869

Cloud Infinite#include "cos_http_io.h"#include "cos_api.h"#include "cos_log.h"#include <unistd.h>// `endpoint` is the COS access domain name. For more information, visit https://wwstatic char TEST_COS_ENDPOINT[] = "cos.ap-guangzhou.myqcloud.com";// A developer-owned secret ID/key used for the project. It can be obtained at httpstatic char *TEST_ACCESS_KEY_ID;//your secret_id
static char *TEST_ACCESS_KEY_SECRET;//your secret_key// A unique user-level resource identifier for COS access. It can be obtained at ht©2013-2022 Tencent Cloud. All rights reserved.

Page 160 of 1869

Cloud Infinite

static char TEST_APPID[] = "<APPID>";//your appid// COS bucket name in the format of [bucket]-[appid], for example, `mybucket-125366
static char TEST_BUCKET_NAME[] = "<bucketname-appid>";void log_status(cos_status_t *s){
cos_warn_log("status->code: %d", s->code);if (s->error_code) cos_warn_log("status->error_code: %s", s->error_code);if (s->error_msg) cos_warn_log("status->error_msg: %s", s->error_msg);
if (s->req_id) cos_warn_log("status->req_id: %s", s->req_id);}void init_test_config(cos_config_t *config, int is_cname){cos_str_set(&config->endpoint, TEST_COS_ENDPOINT);
cos_str_set(&config->access_key_id, TEST_ACCESS_KEY_ID);
cos_str_set(&config->access_key_secret, TEST_ACCESS_KEY_SECRET);
cos_str_set(&config->appid, TEST_APPID);
config->is_cname = is_cname;}void init_test_request_options(cos_request_options_t *options, int is_cname){options->config = cos_config_create(options->pool);
init_test_config(options->config, is_cname);
options->ctl = cos_http_controller_create(options->pool, 0);}
void test_image_compress(){
cos_pool_t *p = NULL;
int is_cname = 0;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_string_t bucket;
cos_string_t object;cos_string_t file;
cos_table_t *resp_headers;
cos_table_t *params = NULL;
cos_pool_create(&p, NULL);
options = cos_request_options_create(p);init_test_request_options(options, is_cname);
cos_str_set(&bucket, TEST_BUCKET_NAME);
params = cos_table_make(p, 1);
apr_table_addn(params, "imageMogr2/format/tpg", "");

©2013-2022 Tencent Cloud. All rights reserved.

Page 161 of 1869

Cloud Infinite

cos_str_set(&object, "test.jpg");
cos_str_set(&file, "test.tpg");s = cos_get_object_to_file(options, &bucket, &object, NULL, params, &file, &res
log_status(s);if (!cos_status_is_ok(s)) {printf("cos_get_object_to_file fail, req_id:%s\\n", s->req_id);}
params = cos_table_make(p, 1);
apr_table_addn(params, "imageMogr2/format/heif", "");
cos_str_set(&file, "test.heif");s = cos_get_object_to_file(options, &bucket, &object, NULL, params, &file, &res
log_status(s);if (!cos_status_is_ok(s)) {printf("cos_get_object_to_file fail, req_id:%s\\n", s->req_id);}
cos_pool_destroy(p);}int main(int argc, char *argv[]){// Get `SECRETID` and `SECRETKEY` from environment variables
TEST_ACCESS_KEY_ID= getenv("COS_SECRETID");
TEST_ACCESS_KEY_SECRET = getenv("COS_SECRETKEY");
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {exit(1);}//set log level, default COS_LOG_WARN
cos_log_set_level(COS_LOG_WARN);//set log output, default stderr
cos_log_set_output(NULL);
test_image_compress();
cos_http_io_deinitialize();
return 0;}©2013-2022 Tencent Cloud. All rights reserved.

Page 162 of 1869

Cloud Infinite

Media Processing
Media Bucket APIs：

Last updated 2024-02-29 16:06:22

Overview
This document provides an overview of APIs and SDK code samples for media buckets.
API

Operation

Description

DescribeMediaBuckets

Querying media processing activation
statusQueries buckets with media processing
enabledQuerying Media Processing Activation Status
Feature description
This API is used to query buckets with media processing enabled.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 163 of 1869

Cloud Infinite

cos_status_t *ci_describe_media_buckets(const cos_request_options_t *options,const ci_media_buckets_request_t *media_req
cos_table_t *headers,
cos_table_t **resp_headers,
ci_media_buckets_result_t **media_result);

Parameter description
Parameter

Description©2013-2022 Tencent Cloud. All rights reserved.

Type

Page 164 of 1869

Cloud Infinite

options

COS request options.

Structmedia_request

Request parameters for media bucket query.

Structregionsbucket_names

Region information, such as ap-shanghai and ap-beijing . To
specify multiple regions, separate them with commas.
Bucket name. To specify multiple bucket names, separate them withcommas. Exact search is supported.

StringStringbucket_nameBucket name prefix for prefix search.

Stringpage_number

Page number.

Stringpage_size

Number of entries per page.

Stringheaders

COS request headers.

Structresp_headers

Returned HTTP response headers.

Structmedia_result

Returned information of buckets with media processing enabled.

Structtotal_countTotal number of media buckets.

Int

page_number

page_size

Current page number, which is the same as pageNumber in therequest.
Number of entries per page, which is the same as pageSize in therequest.

Int

Int

media_bucket_list

Media bucket list.

Structbucket_id

Bucket ID.

StringnameBucket name, which is the same as BucketId .

StringregionRegion.

Stringcreate_time

Creation time.

StringResponse description
Response Parameter

Description

Type

code

Error codeInterror_code

Error code

Stringerror_msg

Error message

String©2013-2022 Tencent Cloud. All rights reserved.

Page 165 of 1869

Cloud Infinite

req_idRequest message ID

StringSampleFor the complete code, see the test_ci_media_process_media_bucket() function in cos_demo.c .

#include "cos_http_io.h"#include "cos_api.h"#include "cos_log.h"©2013-2022 Tencent Cloud. All rights reserved.

Page 166 of 1869

Cloud Infinite// CI endpoint. For more information, visit https://www.tencentcloud.com/document/p
static char TEST_CI_ENDPOINT[] = "https://ci.ap-guangzhou.myqcloud.com";// A developer-owned secret ID/key used for the project. It can be obtained at httpstatic char *TEST_ACCESS_KEY_ID;//your secret_id
static char *TEST_ACCESS_KEY_SECRET;//your secret_key// A unique user-level resource identifier for COS access. It can be obtained at ht
static char TEST_APPID[] = "<APPID>";//your appid
void log_status(cos_status_t *s){
cos_warn_log("status->code: %d", s->code);if (s->error_code) cos_warn_log("status->error_code: %s", s->error_code);if (s->error_msg) cos_warn_log("status->error_msg: %s", s->error_msg);
if (s->req_id) cos_warn_log("status->req_id: %s", s->req_id);}
static void log_media_buckets_result(ci_media_buckets_result_t *result){int index = 0;
ci_media_bucket_list_t *media_bucket;
cos_warn_log("total_count: %d", result->total_count);
cos_warn_log("page_number: %d", result->page_number);cos_warn_log("page_size: %d", result->page_size);
cos_list_for_each_entry(ci_media_bucket_list_t, media_bucket, &result->media_bu
cos_warn_log("media_bucket index:%d", ++index);
cos_warn_log("media_bucket->bucket_id: %s", media_bucket->bucket_id.data);
cos_warn_log("media_bucket->name: %s", media_bucket->name.data);
cos_warn_log("media_bucket->region: %s", media_bucket->region.data);
cos_warn_log("media_bucket->create_time: %s", media_bucket->create_time.dat}}
void test_ci_media_process_media_bucket(){cos_pool_t *p = NULL;
int is_cname = 0;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_table_t *resp_headers;
ci_media_buckets_request_t *media_buckets_request;
ci_media_buckets_result_t *media_buckets_result;// Basic configuration
cos_pool_create(&p, NULL);
options = cos_request_options_create(p);©2013-2022 Tencent Cloud. All rights reserved.

Page 167 of 1869

Cloud Infinite

options->config = cos_config_create(options->pool);cos_str_set(&options->config->endpoint, TEST_CI_ENDPOINT);// https://ci.<R

cos_str_set(&options->config->access_key_id, TEST_ACCESS_KEY_ID);
cos_str_set(&options->config->access_key_secret, TEST_ACCESS_KEY_SECRET);
cos_str_set(&options->config->appid, TEST_APPID);
options->config->is_cname = is_cname;options->ctl = cos_http_controller_create(options->pool, 0);// Use your own configuration. For more information, visit https://www.tencentc
media_buckets_request = ci_media_buckets_request_create(p);cos_str_set(&media_buckets_request->regions, "");
cos_str_set(&media_buckets_request->bucket_names, "");
cos_str_set(&media_buckets_request->bucket_name, "");
cos_str_set(&media_buckets_request->page_number, "1");cos_str_set(&media_buckets_request->page_size, "10");s = ci_describe_media_buckets(options, media_buckets_request, NULL, &resp_heade
log_status(s);if (s->code == 200) {log_media_buckets_result(media_buckets_result);}// Terminate the memory poolcos_pool_destroy(p);}int main(int argc, char *argv[]){// Get `SECRETID` and `SECRETKEY` from environment variables
TEST_ACCESS_KEY_ID= getenv("COS_SECRETID");
TEST_ACCESS_KEY_SECRET = getenv("COS_SECRETKEY");
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {exit(1);}//set log level, default COS_LOG_WARN
cos_log_set_level(COS_LOG_WARN);//set log output, default stderr
cos_log_set_output(NULL);
test_ci_media_process_media_bucket();cos_http_io_deinitialize();
return 0;}©2013-2022 Tencent Cloud. All rights reserved.

Page 168 of 1869

Cloud Infinite©2013-2022 Tencent Cloud. All rights reserved.

Page 169 of 1869

Cloud Infinite

Media Information APIs：

Last updated 2024-02-29 16:06:23

Overview
This document provides an overview of APIs and SDK code samples for media information.
API

Operation

Description

GetMediaInfo

Querying file information

Queries media file information

Note:
Before using this API, make sure that the media processing feature has been enabled in the data processing sectionin the console; otherwise, the error media bucket unbinded, bucket's host is unavailable will bereported. For more information, see Enabling Media Processing.

Querying File Information
Feature description
This API is used to get media file information.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 170 of 1869

Cloud Infinite

cos_status_t *ci_get_media_info(const cos_request_options_t *options,const cos_string_t *bucket,
const cos_string_t *object,cos_table_t *headers,
cos_table_t **resp_headers,
ci_media_info_result_t **media_result);

Parameter description
Parameter

Description©2013-2022 Tencent Cloud. All rights reserved.

Type

Page 171 of 1869

Cloud Infinite

options

COS request options.

StructbucketBucket name in the format of BucketName-APPID .

StringobjectObject name.

Stringheaders

COS request headers.

Structresp_headers

Returned HTTP response headers.

Structmedia_result

Returned media file information.

StructformatFormat information.

Structnum_stream

Number of streams (including videos, audios, and subtitles).

Int

num_program

Number of programs.

Intformat_nameContainer format name.

Stringformat_long_name

Detailed name of the container format.

Stringstart_time

Start time in seconds.

Float

duration

Duration in seconds.

Float

bit_rate

Bitrate in Kbps.

Int

size

Size in bytes.

IntstreamStream information.

Structvideo

Video information.

Structaudio

Audio information.

Structsubtitle

Subtitles information.

Structvideo structure description
Parameter

Description

Type

index

Stream number.

Int

codec_name

Codec format name.

Stringcodec_long_name

Detailed name of the codec format.

Stringcodec_time_base

Codec timebase.

String©2013-2022 Tencent Cloud. All rights reserved.

Page 172 of 1869

Cloud Infinite

codec_tag_string

Codec tag name.

Stringcodec_tag

Codec tag.

StringprofileVideo codec profile.

StringheightVideo height in px.

Int

width

Video width in px.

Int

has_b_frame

Whether B-frames exist. 1: yes; 0: no.

Int

ref_frames

Number of reference frames for video codec.

Int

sar

Sample aspect ratio.

Stringdar

Display aspect ratio.

Stringpix_format

Pixel format.

Stringfield_order

Field order.

Stringlevel

Video codec level.

Int

fps

Video frame rate.

Int

avg_fps

Average frame rate.

Stringtimebase

Timebase.

Stringstart_time

Video start time in seconds.

Float

durationVideo duration in seconds.

Float

bit_rate

Bitrate in Kbps.

Float

num_frames

Total number of frames.

Intlanguage

Language.

Stringaudio structure description
Parameter

Description

Type

index

Stream number.

Int

codec_name

Codec format name.

Stringcodec_long_name

Detailed name of the codec format.

String©2013-2022 Tencent Cloud. All rights reserved.

Page 173 of 1869

Cloud Infinite

codec_time_base

Codec timebase.

Stringcodec_tag_string

Codec tag name.

Stringcodec_tag

Codec tag.

Stringsample_fmt

Sample format.

Stringsample_rate

Sample rate.

Int

channelNumber of channels.

Int

channel_layout

Channel layout.

Stringtimebase

Timebase.

Stringstart_time

Audio start time in seconds.

Float

duration

Audio duration in seconds.

Float

bit_rate

Bitrate in Kbps.

Float

language

Language.

Stringsubtitle structure description
Parameter

Description

Type

index

Stream number.

Intlanguage

Language. und indicates no query result.

StringResponse description
Response Parameter

Description

Type

code

Error codeInterror_code

Error code

Stringerror_msg

Error message

Stringreq_idRequest message ID

StringSampleFor the complete code, see the test_ci_media_process_media_info() function in cos_demo.c .

©2013-2022 Tencent Cloud. All rights reserved.

Page 174 of 1869

Cloud Infinite#include "cos_http_io.h"#include "cos_api.h"#include "cos_log.h"#include <sys/stat.h>// `endpoint` is the COS access domain name. For more information, visit https://wwstatic char TEST_COS_ENDPOINT[] = "cos.ap-guangzhou.myqcloud.com";// A developer-owned secret ID/key used for the project. It can be obtained at httpstatic char *TEST_ACCESS_KEY_ID;//your secret_id
static char *TEST_ACCESS_KEY_SECRET;//your secret_key// A unique user-level resource identifier for COS access. It can be obtained at ht©2013-2022 Tencent Cloud. All rights reserved.

Page 175 of 1869

Cloud Infinite

static char TEST_APPID[] = "<APPID>";//your appid// COS bucket name in the format of [bucket]-[appid], for example, `mybucket-125366
static char TEST_BUCKET_NAME[] = "<bucketname-appid>";void log_status(cos_status_t *s){
cos_warn_log("status->code: %d", s->code);if (s->error_code) cos_warn_log("status->error_code: %s", s->error_code);if (s->error_msg) cos_warn_log("status->error_msg: %s", s->error_msg);
if (s->req_id) cos_warn_log("status->req_id: %s", s->req_id);}
static void log_media_info_result(ci_media_info_result_t *result){// format
cos_warn_log("format.num_stream: %d", result->format.num_stream);cos_warn_log("format.num_program: %d", result->format.num_program);
cos_warn_log("format.format_name: %s", result->format.format_name.data);
cos_warn_log("format.format_long_name: %s", result->format.format_long_name.dat
cos_warn_log("format.start_time: %f", result->format.start_time);
cos_warn_log("format.duration: %f", result->format.duration);
cos_warn_log("format.bit_rate: %d", result->format.bit_rate);
cos_warn_log("format.size: %d", result->format.size);// stream.video
cos_warn_log("stream.video.index: %d", result->stream.video.index);
cos_warn_log("stream.video.codec_name: %s", result->stream.video.codec_name.dat
cos_warn_log("stream.video.codec_long_name: %s", result->stream.video.codec_lon
cos_warn_log("stream.video.codec_time_base: %s", result->stream.video.codec_tim
cos_warn_log("stream.video.codec_tag_string: %s", result->stream.video.codec_ta
cos_warn_log("stream.video.codec_tag: %s", result->stream.video.codec_tag.data)
cos_warn_log("stream.video.profile: %s", result->stream.video.profile.data);
cos_warn_log("stream.video.height: %d", result->stream.video.height);
cos_warn_log("stream.video.width: %d", result->stream.video.width);
cos_warn_log("stream.video.has_b_frame: %d", result->stream.video.has_b_frame);
cos_warn_log("stream.video.ref_frames: %d", result->stream.video.ref_frames);
cos_warn_log("stream.video.sar: %s", result->stream.video.sar.data);
cos_warn_log("stream.video.dar: %s", result->stream.video.dar.data);
cos_warn_log("stream.video.pix_format: %s", result->stream.video.pix_format.dat
cos_warn_log("stream.video.field_order: %s", result->stream.video.field_order.dcos_warn_log("stream.video.level: %d", result->stream.video.level);cos_warn_log("stream.video.fps: %d", result->stream.video.fps);
cos_warn_log("stream.video.avg_fps: %s", result->stream.video.avg_fps.data);
cos_warn_log("stream.video.timebase: %s", result->stream.video.timebase.data);
cos_warn_log("stream.video.start_time: %f", result->stream.video.start_time);
cos_warn_log("stream.video.duration: %f", result->stream.video.duration);
cos_warn_log("stream.video.bit_rate: %f", result->stream.video.bit_rate);©2013-2022 Tencent Cloud. All rights reserved.

Page 176 of 1869

Cloud Infinite

cos_warn_log("stream.video.num_frames: %d", result->stream.video.num_frames);
cos_warn_log("stream.video.language: %s", result->stream.video.language.data);// stream.audio
cos_warn_log("stream.audio.index: %d", result->stream.audio.index);
cos_warn_log("stream.audio.codec_name: %s", result->stream.audio.codec_name.dat
cos_warn_log("stream.audio.codec_long_name: %s", result->stream.audio.codec_lon
cos_warn_log("stream.audio.codec_time_base: %s", result->stream.audio.codec_tim
cos_warn_log("stream.audio.codec_tag_string: %s", result->stream.audio.codec_ta
cos_warn_log("stream.audio.codec_tag: %s", result->stream.audio.codec_tag.data)
cos_warn_log("stream.audio.sample_fmt: %s", result->stream.audio.sample_fmt.dat
cos_warn_log("stream.audio.sample_rate: %d", result->stream.audio.sample_rate);
cos_warn_log("stream.audio.channel: %d", result->stream.audio.channel);
cos_warn_log("stream.audio.channel_layout: %s", result->stream.audio.channel_lacos_warn_log("stream.audio.timebase: %s", result->stream.audio.timebase.data);
cos_warn_log("stream.audio.start_time: %f", result->stream.audio.start_time);
cos_warn_log("stream.audio.duration: %f", result->stream.audio.duration);
cos_warn_log("stream.audio.bit_rate: %f", result->stream.audio.bit_rate);
cos_warn_log("stream.audio.language: %s", result->stream.audio.language.data);// stream.subtitle
cos_warn_log("stream.subtitle.index: %d", result->stream.subtitle.index);
cos_warn_log("stream.subtitle.language: %s", result->stream.subtitle.language.d}void test_ci_media_process_media_info(){
cos_pool_t *p = NULL;
int is_cname = 0;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_string_t bucket;
cos_table_t *resp_headers;
ci_media_info_result_t *media_info;
cos_string_t object;// Basic configuration
cos_pool_create(&p, NULL);
options = cos_request_options_create(p);options->config = cos_config_create(options->pool);cos_str_set(&options->config->endpoint, TEST_COS_ENDPOINT);
cos_str_set(&options->config->access_key_id, TEST_ACCESS_KEY_ID);
cos_str_set(&options->config->access_key_secret, TEST_ACCESS_KEY_SECRET);
cos_str_set(&options->config->appid, TEST_APPID);
options->config->is_cname = is_cname;options->ctl = cos_http_controller_create(options->pool, 0);
cos_str_set(&bucket, TEST_BUCKET_NAME);©2013-2022 Tencent Cloud. All rights reserved.

Page 177 of 1869

Cloud Infinite

cos_str_set(&object, "test.mp4");// Use your own configuration. For more information, visit https://www.tencentc
s = ci_get_media_info(options, &bucket, &object, NULL, &resp_headers, &media_in
log_status(s);if (s->code == 200) {log_media_info_result(media_info);}// Terminate the memory poolcos_pool_destroy(p);}int main(int argc, char *argv[]){// Get `SECRETID` and `SECRETKEY` from environment variables
TEST_ACCESS_KEY_ID= getenv("COS_SECRETID");
TEST_ACCESS_KEY_SECRET = getenv("COS_SECRETKEY");
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {exit(1);}//set log level, default COS_LOG_WARN
cos_log_set_level(COS_LOG_WARN);//set log output, default stderr
cos_log_set_output(NULL);
test_ci_media_process_media_info();cos_http_io_deinitialize();
return 0;}©2013-2022 Tencent Cloud. All rights reserved.

Page 178 of 1869

Cloud Infinite

Media Screenshot APIs：

Last updated 2024-02-29 16:06:23

Overview
This document provides an overview of APIs and SDK code samples for media screenshot.
API

Operation

Description

GetSnapshot

Querying screenshot

Query the screenshot of media file at some time point

Note:
Before using this API, make sure that the media processing feature has been enabled in the data processing sectionin the console; otherwise, the error media bucket unbinded, bucket's host is unavailable will bereported. For more information, see Enabling Media Processing.

Querying Screenshot (Memory)
Feature description
This API is used to get a screenshot of a media file at some time point and put the screenshot information in thememory buffer.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 179 of 1869

Cloud Infinite

cos_status_t *ci_get_snapshot_to_buffer(const cos_request_options_t *options,const cos_string_t *bucket,
const cos_string_t *object,
const ci_get_snapshot_request_t *snapshot_r
cos_table_t *headers,
cos_list_t *buffer,cos_table_t **resp_headers);

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 180 of 1869

Cloud Infinite

Parameter

Description

Type

options

COS request options.

StructbucketBucket name in the format of BucketName-APPID .

StringobjectObject name.

Stringsnapshot_request

Request parameters for getting media screenshot.

Structtime

Screenshot time point in seconds.

Float

width

Screenshot width. Default value: 0.

Int

Screenshot height. Default value: 0
heightIf width and height are both 0 , the width and height of thevideo are used. If one of them is 0 , the other value is used toIntautomatically adapt to the aspect ratio of the video.
formatScreenshot format. Valid values: jpg; png. Default value: jpg.

StringImage rotation method
rotateauto: Rotate automatically according to the video rotation information.
off: Do not rotate.

StringDefault value: auto.

mode

Frame capturing method
keyframe: Capture the last keyframe before the specified time point.
exactframe: Capture the frame at a specified time point.
Default value: exactframe.

Stringheaders

COS request headers.

StructbufferReturned screenshot content.

Structresp_headers

Returned HTTP response headers.

StructResponse description
Response Parameter

Description

Type

code

Error codeInterror_code

Error code

Stringerror_msg

Error message

Stringreq_idRequest message ID

String©2013-2022 Tencent Cloud. All rights reserved.

Page 181 of 1869

Cloud Infinite

SampleFor the complete code, see the test_ci_media_process_snapshot() function in cos_demo.c .

#include "cos_http_io.h"#include "cos_api.h"#include "cos_log.h"// `endpoint` is the COS access domain name. For more information, visit https://wwstatic char TEST_COS_ENDPOINT[] = "cos.ap-guangzhou.myqcloud.com";// A developer-owned secret ID/key used for the project. It can be obtained at httpstatic char *TEST_ACCESS_KEY_ID;//your secret_id©2013-2022 Tencent Cloud. All rights reserved.

Page 182 of 1869

Cloud Infinite

static char *TEST_ACCESS_KEY_SECRET;//your secret_key// A unique user-level resource identifier for COS access. It can be obtained at ht
static char TEST_APPID[] = "<APPID>";//your appid// COS bucket name in the format of [bucket]-[appid], for example, `mybucket-125366
static char TEST_BUCKET_NAME[] = "<bucketname-appid>";void log_status(cos_status_t *s){
cos_warn_log("status->code: %d", s->code);if (s->error_code) cos_warn_log("status->error_code: %s", s->error_code);if (s->error_msg) cos_warn_log("status->error_msg: %s", s->error_msg);
if (s->req_id) cos_warn_log("status->req_id: %s", s->req_id);}void test_ci_media_process_snapshot(){cos_pool_t *p = NULL;
int is_cname = 0;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_string_t bucket;
cos_table_t *resp_headers;
cos_list_t download_buffer;cos_string_t object;ci_get_snapshot_request_t *snapshot_request;// Basic configuration
cos_pool_create(&p, NULL);
options = cos_request_options_create(p);options->config = cos_config_create(options->pool);cos_str_set(&options->config->endpoint, TEST_COS_ENDPOINT);
cos_str_set(&options->config->access_key_id, TEST_ACCESS_KEY_ID);
cos_str_set(&options->config->access_key_secret, TEST_ACCESS_KEY_SECRET);
cos_str_set(&options->config->appid, TEST_APPID);
options->config->is_cname = is_cname;options->ctl = cos_http_controller_create(options->pool, 0);
cos_str_set(&bucket, TEST_BUCKET_NAME);
cos_str_set(&object, "test.mp4");// Use your own configuration. For more information, visit https://www.tencentc
snapshot_request = ci_snapshot_request_create(p);snapshot_request->time = 7.5;
snapshot_request->width = 0;
snapshot_request->height = 0;
cos_str_set(&snapshot_request->format, "jpg");
cos_str_set(&snapshot_request->rotate, "auto");cos_str_set(&snapshot_request->mode, "exactframe");©2013-2022 Tencent Cloud. All rights reserved.

Page 183 of 1869

Cloud Infinite

cos_list_init(&download_buffer);s = ci_get_snapshot_to_buffer(options, &bucket, &object, snapshot_request, NULL
log_status(s);// Terminate the memory poolcos_pool_destroy(p);}int main(int argc, char *argv[]){// Get `SECRETID` and `SECRETKEY` from environment variables
TEST_ACCESS_KEY_ID= getenv("COS_SECRETID");
TEST_ACCESS_KEY_SECRET = getenv("COS_SECRETKEY");
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {exit(1);}//set log level, default COS_LOG_WARN
cos_log_set_level(COS_LOG_WARN);//set log output, default stderr
cos_log_set_output(NULL);
test_ci_media_process_snapshot();
cos_http_io_deinitialize();
return 0;}

Querying Screenshot (File)
Feature description
This API is used to get a screenshot of a media file at some time point and put the screenshot information in a local
file.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 184 of 1869

Cloud Infinite

cos_status_t *ci_get_snapshot_to_file(const cos_request_options_t *options,const cos_string_t *bucket,
const cos_string_t *object,
const ci_get_snapshot_request_t *snapshot_req
cos_table_t *headers,
cos_string_t *filename,cos_table_t **resp_headers);

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 185 of 1869

Cloud Infinite

Parameter

Description

Type

options

COS request options.

StructbucketBucket name in the format of BucketName-APPID .

StringobjectObject name.

Stringsnapshot_request

Request parameters for getting media screenshot.

Structtime

Screenshot time point in seconds.

Float

width

Screenshot width. Default value: 0.

IntheightScreenshot height. Default value: 0
If width and height are both 0 , the width and height of thevideo are used. If one of them is 0 , the other value is used toIntautomatically adapt to the aspect ratio of the video.
formatScreenshot format. Valid values: jpg; png. Default value: jpg.

StringImage rotation method
rotateauto: Rotate automatically according to the video rotation information.
off: Do not rotate.

StringDefault value: auto.

mode

Frame capturing method
keyframe: Capture the last keyframe before the specified time point.
exactframe: Capture the frame at a specified time point.

StringDefault value: exactframe.
headers

COS request headers.

Structfilename

Name of the file for storing screenshot information.

Stringresp_headers

Returned HTTP response headers.

StructResponse description
Response Parameter

Description

Type

code

Error codeInterror_code

Error code

Stringerror_msg

Error message

Stringreq_idRequest message ID

String©2013-2022 Tencent Cloud. All rights reserved.

Page 186 of 1869

Cloud Infinite

SampleFor the complete code, see the test_ci_media_process_snapshot() function in cos_demo.c .

#include "cos_http_io.h"#include "cos_api.h"#include "cos_log.h"#include <sys/stat.h>// `endpoint` is the COS access domain name. For more information, visit https://wwstatic char TEST_COS_ENDPOINT[] = "cos.ap-guangzhou.myqcloud.com";// A developer-owned secret ID/key used for the project. It can be obtained at http©2013-2022 Tencent Cloud. All rights reserved.

Page 187 of 1869

Cloud Infinite

static char *TEST_ACCESS_KEY_ID;//your secret_id
static char *TEST_ACCESS_KEY_SECRET;//your secret_key// A unique user-level resource identifier for COS access. It can be obtained at ht
static char TEST_APPID[] = "<APPID>";//your appid// COS bucket name in the format of [bucket]-[appid], for example, `mybucket-125366
static char TEST_BUCKET_NAME[] = "<bucketname-appid>";void log_status(cos_status_t *s){
cos_warn_log("status->code: %d", s->code);if (s->error_code) cos_warn_log("status->error_code: %s", s->error_code);if (s->error_msg) cos_warn_log("status->error_msg: %s", s->error_msg);
if (s->req_id) cos_warn_log("status->req_id: %s", s->req_id);}void test_ci_media_process_snapshot(){cos_pool_t *p = NULL;
int is_cname = 0;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_string_t bucket;
cos_table_t *resp_headers;
cos_string_t object;ci_get_snapshot_request_t *snapshot_request;
cos_string_t pic_file = cos_string("snapshot.jpg");// Basic configuration
cos_pool_create(&p, NULL);
options = cos_request_options_create(p);options->config = cos_config_create(options->pool);cos_str_set(&options->config->endpoint, TEST_COS_ENDPOINT);
cos_str_set(&options->config->access_key_id, TEST_ACCESS_KEY_ID);
cos_str_set(&options->config->access_key_secret, TEST_ACCESS_KEY_SECRET);
cos_str_set(&options->config->appid, TEST_APPID);
options->config->is_cname = is_cname;options->ctl = cos_http_controller_create(options->pool, 0);
cos_str_set(&bucket, TEST_BUCKET_NAME);
cos_str_set(&object, "test.mp4");// Use your own configuration. For more information, visit https://www.tencentc
snapshot_request = ci_snapshot_request_create(p);snapshot_request->time = 7.5;
snapshot_request->width = 0;
snapshot_request->height = 0;
cos_str_set(&snapshot_request->format, "jpg");
cos_str_set(&snapshot_request->rotate, "auto");©2013-2022 Tencent Cloud. All rights reserved.

Page 188 of 1869

Cloud Infinite

cos_str_set(&snapshot_request->mode, "exactframe");s = ci_get_snapshot_to_file(options, &bucket, &object, snapshot_request, NULL,
log_status(s);// Terminate the memory poolcos_pool_destroy(p);}int main(int argc, char *argv[]){// Get `SECRETID` and `SECRETKEY` from environment variables
TEST_ACCESS_KEY_ID= getenv("COS_SECRETID");
TEST_ACCESS_KEY_SECRET = getenv("COS_SECRETKEY");
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {exit(1);}//set log level, default COS_LOG_WARN
cos_log_set_level(COS_LOG_WARN);//set log output, default stderr
cos_log_set_output(NULL);
test_ci_media_process_snapshot();
cos_http_io_deinitialize();
return 0;}©2013-2022 Tencent Cloud. All rights reserved.

Page 189 of 1869

Cloud Infinite

Content Moderation
Video Moderation：

Last updated 2024-02-29 16:06:23

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for video moderation.
API

Description

Submitting video moderation job

Submits video moderation job.

Querying video moderation job result

Queries the result of specified video moderation job.

Submitting Video Moderation Job
Feature description
This API is used to submit a video moderation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 190 of 1869

Cloud Infinite

cos_status_t *ci_create_video_auditing_job(const cos_request_options_t *options,const cos_string_t *bucket,
const ci_video_auditing_job_options_t *j
cos_table_t *headers,
cos_table_t **resp_headers,
ci_video_auditing_job_result_t **job_res

Parameter description
Parameter

Description©2013-2022 Tencent Cloud. All rights reserved.

Type

Page 191 of 1869

Cloud Infinite

optionsbucket

COS request options
Bucket name in the format of BucketName-APPID . The bucket nameentered here must be in this format.

StructStringjob_options

Parameter configuration of the submitted video moderation job

Structinput_object

Object name

String

The scene to be moderated, such as Porn (pornography) and Ads
detect_type(advertising). You can pass in multiple types and separate them by comma,
such as Porn,Ads .

Stringcallback

Callback address, which must start with http:// or https:// .

StringStructure of the callback content. Valid values: Simple (the callback
callback_version

content contains basic information), Detail (the callback content

Stringcontains detailed information). Default value: Simple .
biz_type

Moderation policy. If this parameter is not specified, the default policy will be
used.

StringWhether to moderate video sound. Valid values: 0 (moderates the video
detect_content

image only), 1 (moderates both the video image and video sound).

Integer

Default value: 0 .
Video image moderation is implemented by taking a certain number ofsnapshotscreenshots based on the video frame capturing capability and thenmoderating the screenshots one by one. This parameter is used to specify

Structthe configuration of video frame capturing.
Frame capturing mode. Valid values: Interval (interval mode),
Average (average mode), Fps (fixed frame rate mode).
Interval mode: The TimeInterval and Count parameters
take effect. If Count is set but TimeInterval is not, all frames willmode

be captured to generate a total of Count images.

StringAverage mode: The Count parameter takes effect, indicating tocapture a total of Count images at an average interval in the entire video.
Fps mode: TimeInterval indicates how many frames to capture persecond, and Count indicates how many frames to capture in total.
count

The number of captured frames. Value range: (0, 10000].

Integer

time_intervalVideo frame capturing frequency. Value range: (0.000, 60.000] seconds. The
value supports the float format, accurate to the millisecond.

Float

headers

COS request headers

Struct©2013-2022 Tencent Cloud. All rights reserved.

Page 192 of 1869

Cloud Infinite

resp_headers

Returned HTTP response headers

Structjob_result

Returned response to job submission

Structjob_idID of the video moderation job

Stringstate
creation_time

Status of the video moderation job. Valid values: Submitted ,Snapshoting , Success , Failed , Auditing .
Creation time of the video moderation job.

StringStringResponse description
Returned Result

Description

Type

code

Error codeInterror_code

Error code

Stringerror_msg

Error message

Stringreq_idRequest ID

StringSampleFor the complete code, see the test_ci_video_auditing() function in cos_demo.c .

©2013-2022 Tencent Cloud. All rights reserved.

Page 193 of 1869

Cloud Infinite#include "cos_http_io.h"#include "cos_api.h"#include "cos_log.h"#include <sys/stat.h>// CI endpoint. For more information, visit https://www.tencentcloud.com/document/p
static char TEST_CI_ENDPOINT[] = "https://ci.ap-guangzhou.myqcloud.com";// A developer-owned secret ID/key used for the project. It can be obtained at httpstatic char *TEST_ACCESS_KEY_ID;//your secret_id
static char *TEST_ACCESS_KEY_SECRET;//your secret_key// A unique user-level resource identifier for COS access. It can be obtained at ht©2013-2022 Tencent Cloud. All rights reserved.

Page 194 of 1869

Cloud Infinite

static char TEST_APPID[] = "<APPID>";//your appid// COS bucket name in the format of [bucket]-[appid], for example, `mybucket-125366
static char TEST_BUCKET_NAME[] = "<bucketname-appid>";void log_status(cos_status_t *s){
cos_warn_log("status->code: %d", s->code);if (s->error_code) cos_warn_log("status->error_code: %s", s->error_code);if (s->error_msg) cos_warn_log("status->error_msg: %s", s->error_msg);
if (s->req_id) cos_warn_log("status->req_id: %s", s->req_id);}
static void log_video_auditing_result(ci_video_auditing_job_result_t *result){cos_warn_log("jobid: %s", result->jobs_detail.job_id.data);
cos_warn_log("state: %s", result->jobs_detail.state.data);
cos_warn_log("creation_time: %s", result->jobs_detail.creation_time.data);}
void test_ci_create_video_auditing(){
cos_pool_t *p = NULL;
int is_cname = 0;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_string_t bucket;
cos_table_t *resp_headers;
ci_video_auditing_job_options_t *job_options;
ci_video_auditing_job_result_t *job_result;// Basic configuration
cos_pool_create(&p, NULL);
options = cos_request_options_create(p);options->config = cos_config_create(options->pool);cos_str_set(&options->config->endpoint, TEST_CI_ENDPOINT);// https://ci.<R
cos_str_set(&options->config->access_key_id, TEST_ACCESS_KEY_ID);
cos_str_set(&options->config->access_key_secret, TEST_ACCESS_KEY_SECRET);
cos_str_set(&options->config->appid, TEST_APPID);
options->config->is_cname = is_cname;options->ctl = cos_http_controller_create(options->pool, 0);
cos_str_set(&bucket, TEST_BUCKET_NAME);// Replace with your configuration information. For more information, visit htt
job_options = ci_video_auditing_job_options_create(p);cos_str_set(&job_options->input_object, "test.mp4");
cos_str_set(&job_options->job_conf.detect_type, "Porn,Ads");
cos_str_set(&job_options->job_conf.callback_version, "Detail");©2013-2022 Tencent Cloud. All rights reserved.

Page 195 of 1869

Cloud Infinite

job_options->job_conf.detect_content = 1;
cos_str_set(&job_options->job_conf.snapshot.mode, "Interval");job_options->job_conf.snapshot.time_interval = 1.5;
job_options->job_conf.snapshot.count = 10;// Submit a video moderation job
s = ci_create_video_auditing_job(options, &bucket, job_options, NULL, &resp_hea
log_status(s);if (s->code == 200) {log_video_auditing_result(job_result);}// Terminate the memory poolcos_pool_destroy(p);}int main(int argc, char *argv[]){// Get `SECRETID` and `SECRETKEY` from environment variables
TEST_ACCESS_KEY_ID= getenv("COS_SECRETID");
TEST_ACCESS_KEY_SECRET = getenv("COS_SECRETKEY");
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {exit(1);}//set log level, default COS_LOG_WARN
cos_log_set_level(COS_LOG_WARN);//set log output, default stderr
cos_log_set_output(NULL);
test_ci_create_video_auditing();
cos_http_io_deinitialize();
return 0;}

Querying Video Moderation Job
Feature description
This API is used to query the status and result of a video moderation job.

©2013-2022 Tencent Cloud. All rights reserved.

Page 196 of 1869

Cloud Infinite

Method prototype

cos_status_t *ci_get_auditing_job(const cos_request_options_t *options,const cos_string_t *bucket,
const cos_string_t *job_id,
cos_table_t *headers,
cos_table_t **resp_headers,ci_auditing_job_result_t **job_result);

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 197 of 1869

Cloud Infinite

Parameter

Description

Type

options

COS request options

StructbucketBucket name in the format of BucketName-APPID . The bucket
name entered here must be in this format.

Stringjob_idID of the video moderation job

Stringheaders

COS request headers

Structresp_headers

Returned HTTP response headers

Structjob_result

Returned response to job query

Structnonexist_job_ids

List of non-existing job IDs queried. If all jobs exist, this node will not
be returned.

Stringjobs_detail

Details of the video moderation job

Structcode

Error code, which will be returned only if State is Failed .

Stringmessage

Error message, which will be returned only if State is Failed .

Stringjob_idID of the video moderation job

Stringstate

Status of the video moderation job. Valid values: Submitted ,Snapshoting , Success , Failed , Auditing .

Stringcreation_time

Creation time of the video moderation job.

StringobjectName of the video file to be moderated

Stringsnapshot_countTotal number of video screenshot

StringThis field indicates the moderation result. You can perform subsequent
operations based on the result. We recommend you handle different
resultresults based on your business needs. Valid values: 0 (normal),Integer

1 (sensitive), and 2 (suspiciously sensitive, with human review
recommended).
porn_info
ads_info
hit_flag

The moderation result of the pornographic information moderation
scene.
The moderation result of the advertising information moderation scene.
Whether the moderation type is hit. Valid values: 0 (miss), 1 (hit),and 2 (suspected).

©2013-2022 Tencent Cloud. All rights reserved.

StructStructInteger

Page 198 of 1869

Cloud Infinite

count

The number of screenshots that hit this moderation scene.

IntegerThis field is used to return the screenshot moderation result of thesnapshot_info_list

video. Note: Each URL is valid for two hours. If you need to view thedata after two hours, initiate a new query request.

StructThis field is used to return the audio moderation result of the video.
audio_section_info_list

Note: Each URL is valid for two hours. If you need to view the data

Structafter two hours, initiate a new query request.

snapshot_info_list structure description
Parameter
url

Description
URL of the current video screenshot, at which you can view the screenshot. It
must be a standard URL.

Type
StringThis field is used to return the time where the current screenshot is in the entire
snapshot_time

video in milliseconds, such as 5000 (i.e., 5000 milliseconds after the video

Integerstarts).
This field is used to return the OCR text recognition result of the current
text

screenshot. It will be returned only if text content detection is enabled in theStringmoderation policy. Up to 5,000 bytes can be recognized.
porn_info

The moderation result of the pornographic information moderation scene.

Structads_info

The moderation result of the advertising information moderation scene.

Structhit_flag

score

Whether the moderation type is hit. Valid values: 0 (miss), 1 (hit), and 2(suspected).
The confidence the moderation result hits the moderation scene. Value range:
0–100. The higher the value, the more likely the content hits the currently
returned moderation scene. For example, Porn 99 means that the content

Integer

Integer

is very likely to be pornographic.
This field indicates the result tag of the screenshot, which may belabel

SubLabel , a person name, etc. It is a reserved field for compatibility with

Stringlegacy versions.
This field indicates the specific sub-tag hit by the moderation job; for example,
sub_lable

SexBehavior is a sub-tag under the Porn tag. Note: This field may

Stringreturn null, indicating that no specific sub-tags are hit.

audio_section_info_list structure description©2013-2022 Tencent Cloud. All rights reserved.

Page 199 of 1869

Cloud Infinite

Parameter

Description

Type

url

URL of the current audio segment of the video, at which you can get the content
of the audio segment. It must be a standard URL.

StringThis field is used to return the ASR text recognition result of the audio of thetextcurrent video. It will be returned only if text content detection is enabled in theStringmoderation policy. Up to 5 hours of content can be recognized.

offset_time

This field is used to return the time where the current audio segment is in theentire video in milliseconds, such as 5000 (i.e., 5000 milliseconds after the video

Integerstarts).
duration

The duration of the current video sound segment in milliseconds.

Integer

porn_info

The moderation result of the pornographic information moderation scene.

Structads_info

The moderation result of the advertising information moderation scene.

Structhit_flag

Whether the moderation type is hit. Valid values: 0 (miss), 1 (hit), and 2

Integer(suspected).
The confidence the moderation result hits the moderation scene. Value range: 0–

score

100. The higher the value, the more likely the content hits the currently returned
moderation scene. For example, Porn 99 means that the content is very

Integerlikely to be pornographic.
key_words

Keywords hit by the current moderation scene.

StringResponse description
Returned Result

Description

Type

code

Error codeInterror_code

Error code

Stringerror_msg

Error message

Stringreq_idRequest ID

StringSampleFor the complete code, see the test_ci_video_auditing() function in cos_demo.c .

©2013-2022 Tencent Cloud. All rights reserved.

Page 200 of 1869

Cloud Infinite#include "cos_http_io.h"#include "cos_api.h"#include "cos_log.h"#include <unistd.h>// CI endpoint. For more information, visit https://www.tencentcloud.com/document/p
static char TEST_CI_ENDPOINT[] = "https://ci.ap-guangzhou.myqcloud.com";// A developer-owned secret ID/key used for the project. It can be obtained at httpstatic char *TEST_ACCESS_KEY_ID;//your secret_id
static char *TEST_ACCESS_KEY_SECRET;//your secret_key// A unique user-level resource identifier for COS access. It can be obtained at ht©2013-2022 Tencent Cloud. All rights reserved.

Page 201 of 1869

Cloud Infinite

static char TEST_APPID[] = "<APPID>";//your appid// COS bucket name in the format of [bucket]-[appid], for example, `mybucket-125366
static char TEST_BUCKET_NAME[] = "<bucketname-appid>";void log_status(cos_status_t *s){
cos_warn_log("status->code: %d", s->code);if (s->error_code) cos_warn_log("status->error_code: %s", s->error_code);if (s->error_msg) cos_warn_log("status->error_msg: %s", s->error_msg);
if (s->req_id) cos_warn_log("status->req_id: %s", s->req_id);}
static void log_get_auditing_result(ci_auditing_job_result_t *result){int index = 0;
ci_auditing_snapshot_result_t *snapshot_info;
ci_auditing_audio_section_result_t *audio_section_info;
cos_warn_log("nonexist_job_ids: %s", result->nonexist_job_ids.data);
cos_warn_log("code: %s", result->jobs_detail.code.data);
cos_warn_log("message: %s", result->jobs_detail.message.data);
cos_warn_log("state: %s", result->jobs_detail.state.data);
cos_warn_log("creation_time: %s", result->jobs_detail.creation_time.data);
cos_warn_log("object: %s", result->jobs_detail.object.data);
cos_warn_log("snapshot_count: %s", result->jobs_detail.snapshot_count.data);
cos_warn_log("result: %d", result->jobs_detail.result);
cos_warn_log("porn_info.hit_flag: %d", result->jobs_detail.porn_info.hit_flag);cos_warn_log("porn_info.count: %d", result->jobs_detail.porn_info.count);
cos_warn_log("ads_info.hit_flag: %d", result->jobs_detail.ads_info.hit_flag);cos_warn_log("ads_info.count: %d", result->jobs_detail.ads_info.count);
cos_list_for_each_entry(ci_auditing_snapshot_result_t, snapshot_info, &result->
cos_warn_log("snapshot index:%d", ++index);
cos_warn_log("snapshot_info->url: %s", snapshot_info->url.data);
cos_warn_log("snapshot_info->snapshot_time: %d", snapshot_info->snapshot_ti
cos_warn_log("snapshot_info->text: %s", snapshot_info->text.data);
cos_warn_log("snapshot_info->porn_info.hit_flag: %d", snapshot_info->porn_i
cos_warn_log("snapshot_info->porn_info.score: %d", snapshot_info->porn_info
cos_warn_log("snapshot_info->porn_info.label: %s", snapshot_info->porn_info
cos_warn_log("snapshot_info->porn_info.sub_lable: %s", snapshot_info->porn_
cos_warn_log("snapshot_info->ads_info.hit_flag: %d", snapshot_info->ads_inf
cos_warn_log("snapshot_info->ads_info.score: %d", snapshot_info->ads_info.s
cos_warn_log("snapshot_info->ads_info.label: %s", snapshot_info->ads_info.l
cos_warn_log("snapshot_info->ads_info.sub_lable: %s", snapshot_info->ads_in}©2013-2022 Tencent Cloud. All rights reserved.

Page 202 of 1869

Cloud Infinite

index = 0;
cos_list_for_each_entry(ci_auditing_audio_section_result_t, audio_section_info,
cos_warn_log("audio_section index:%d", ++index);
cos_warn_log("audio_section_info->url: %s", audio_section_info->url.data);
cos_warn_log("audio_section_info->text: %s", audio_section_info->text.data)
cos_warn_log("audio_section_info->offset_time: %d", audio_section_info->off
cos_warn_log("audio_section_info->duration: %d", audio_section_info->durati
cos_warn_log("audio_section_info->porn_info.hit_flag: %d", audio_section_in
cos_warn_log("audio_section_info->porn_info.score: %d", audio_section_infocos_warn_log("audio_section_info->porn_info.key_words: %s", audio_section_i
cos_warn_log("audio_section_info->ads_info.hit_flag: %d", audio_section_inf
cos_warn_log("audio_section_info->ads_info.score: %d", audio_section_info->
cos_warn_log("audio_section_info->ads_info.key_words: %s", audio_section_in}}
void test_ci_get_video_auditing(){
cos_pool_t *p = NULL;
int is_cname = 0;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_string_t bucket;
cos_table_t *resp_headers;
ci_video_auditing_job_options_t *job_options;
ci_video_auditing_job_result_t *job_result;ci_auditing_job_result_t *auditing_result;// Basic configuration
cos_pool_create(&p, NULL);
options = cos_request_options_create(p);options->config = cos_config_create(options->pool);cos_str_set(&options->config->endpoint, TEST_CI_ENDPOINT);// https://ci.<R
cos_str_set(&options->config->access_key_id, TEST_ACCESS_KEY_ID);
cos_str_set(&options->config->access_key_secret, TEST_ACCESS_KEY_SECRET);
cos_str_set(&options->config->appid, TEST_APPID);
options->config->is_cname = is_cname;options->ctl = cos_http_controller_create(options->pool, 0);
cos_str_set(&bucket, TEST_BUCKET_NAME);// Replace with your configuration information. For more information, visit htt
job_options = ci_video_auditing_job_options_create(p);cos_str_set(&job_options->input_object, "test.mp4");
cos_str_set(&job_options->job_conf.detect_type, "Porn,Ads");
cos_str_set(&job_options->job_conf.callback_version, "Detail");©2013-2022 Tencent Cloud. All rights reserved.

Page 203 of 1869

Cloud Infinite

job_options->job_conf.detect_content = 1;
cos_str_set(&job_options->job_conf.snapshot.mode, "Interval");job_options->job_conf.snapshot.time_interval = 1.5;
job_options->job_conf.snapshot.count = 10;// Submit a video moderation job
s = ci_create_video_auditing_job(options, &bucket, job_options, NULL, &resp_hea
log_status(s);// Wait for the video moderation job to complete. You can modify the wait time
sleep(300);// Get the moderation job results = ci_get_auditing_job(options, &bucket, &job_result->jobs_detail.job_id, NULL
log_status(s);if (s->code == 200) {log_get_auditing_result(auditing_result);}// Terminate the memory poolcos_pool_destroy(p);}int main(int argc, char *argv[]){// Get `SECRETID` and `SECRETKEY` from environment variables
TEST_ACCESS_KEY_ID= getenv("COS_SECRETID");
TEST_ACCESS_KEY_SECRET = getenv("COS_SECRETKEY");
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {exit(1);}//set log level, default COS_LOG_WARN
cos_log_set_level(COS_LOG_WARN);//set log output, default stderr
cos_log_set_output(NULL);
test_ci_get_video_auditing();
cos_http_io_deinitialize();
return 0;}©2013-2022 Tencent Cloud. All rights reserved.

Page 204 of 1869

Cloud Infinite

Content Recognition
QR Code Recognition：

Last updated 2024-02-29 16:06:23

Overview
This document provides an overview of APIs and SDK code samples for image QR codes.
API

Description

QR codeRecognizes the location and content of valid QR codes in an image, outputs the text information

recognition(URL or text) contained in the QR codes, and pixelates the recognized QR codes.

QR Code Recognition
The QR code recognition feature recognizes the location and content of valid QR codes in an image, outputs the text
information (URL or text) contained in the QR codes, and pixelates the recognized QR codes.

Recognizing during upload
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 205 of 1869

Cloud Infinite

cos_status_t *ci_put_object_from_file(const cos_request_options_t *options,const cos_string_t *bucket,
const cos_string_t *object,
const cos_string_t *filename,cos_table_t *headers,
cos_table_t **resp_headers,
ci_operation_result_t **results)

Feature description©2013-2022 Tencent Cloud. All rights reserved.

Page 206 of 1869

Cloud Infinite

The request for recognizing QR codes during image upload is the same as that used to simply upload a file to COS,
except that you need to add the image processing parameter Pic-Operations to the request header.
Sample request#include "cos_http_io.h"#include "cos_api.h"#include "cos_log.h"#include <unistd.h>// `endpoint` is the COS access domain name. For more information, visit https://cl©2013-2022 Tencent Cloud. All rights reserved.

Page 207 of 1869

Cloud Infinite

static char TEST_COS_ENDPOINT[] = "cos.ap-guangzhou.myqcloud.com";// CI endpoint. For more information, visit https://cloud.tencent.com/document/prod
static char TEST_CI_ENDPOINT[] = "https://ci.ap-guangzhou.myqcloud.com";// A developer-owned secret ID/key used for the project. It can be obtained at httpstatic char *TEST_ACCESS_KEY_ID;//your secret_id
static char *TEST_ACCESS_KEY_SECRET;//your secret_key// A unique user-level resource identifier for COS access. It can be obtained at ht
static char TEST_APPID[] = "<APPID>";//your appid// COS bucket name in the format of [bucket]-[appid], for example, `mybucket-125366
static char TEST_BUCKET_NAME[] = "<bucketname-appid>";void log_status(cos_status_t *s){
cos_warn_log("status->code: %d", s->code);if (s->error_code) cos_warn_log("status->error_code: %s", s->error_code);if (s->error_msg) cos_warn_log("status->error_msg: %s", s->error_msg);
if (s->req_id) cos_warn_log("status->req_id: %s", s->req_id);}void init_test_config(cos_config_t *config, int is_cname){cos_str_set(&config->endpoint, TEST_COS_ENDPOINT);
cos_str_set(&config->access_key_id, TEST_ACCESS_KEY_ID);
cos_str_set(&config->access_key_secret, TEST_ACCESS_KEY_SECRET);
cos_str_set(&config->appid, TEST_APPID);
config->is_cname = is_cname;}void init_test_request_options(cos_request_options_t *options, int is_cname){options->config = cos_config_create(options->pool);
init_test_config(options->config, is_cname);
options->ctl = cos_http_controller_create(options->pool, 0);}
void test_ci_image_qrcode(){
cos_pool_t *p = NULL;
int is_cname = 0;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_string_t bucket;
cos_string_t object;cos_string_t file;
cos_table_t *resp_headers;
cos_table_t *headers = NULL;
ci_operation_result_t *results = NULL;©2013-2022 Tencent Cloud. All rights reserved.

Page 208 of 1869

Cloud Infinite

ci_qrcode_info_t *content = NULL;
cos_pool_create(&p, NULL);
options = cos_request_options_create(p);init_test_request_options(options, is_cname);
cos_str_set(&bucket, TEST_BUCKET_NAME);
cos_str_set(&object, "test.jpg");
headers = cos_table_make(p, 1);
apr_table_addn(headers, "pic-operations", "{\\"is_pic_info\\":1,\\"rules\\":[{\// Recognize during upload
cos_str_set(&file, "test.jpg");
cos_str_set(&object, "test.jpg");s = ci_put_object_from_file(options, &bucket, &object, &file, headers, &resp_he
log_status(s);if (!cos_status_is_ok(s)) {printf("put object failed\\n");}printf("CodeStatus: %d\\n", results->object.code_status);
cos_list_for_each_entry(ci_qrcode_info_t, content, &results->object.qrcode_info
printf("CodeUrl: %s\\n", content->code_url.data);
printf("Point: %s\\n", content->point[0].data);
printf("Point: %s\\n", content->point[1].data);
printf("Point: %s\\n", content->point[2].data);
printf("Point: %s\\n", content->point[3].data);}// Terminate the memory poolcos_pool_destroy(p);}int main(int argc, char *argv[]){// Get `SECRETID` and `SECRETKEY` from environment variables
TEST_ACCESS_KEY_ID= getenv("COS_SECRETID");
TEST_ACCESS_KEY_SECRET = getenv("COS_SECRETKEY");
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {exit(1);}//set log level, default COS_LOG_WARN
cos_log_set_level(COS_LOG_WARN);//set log output, default stderr
cos_log_set_output(NULL);©2013-2022 Tencent Cloud. All rights reserved.

Page 209 of 1869

Cloud Infinite

test_ci_image_qrcode();cos_http_io_deinitialize();
return 0;}

Parameter description
Parameter

Description

Type

options

COS request options

StructbucketBucket name in the format of BucketName-APPID

StringobjectObject name

Stringfilename

Filename of the local object

Stringheaders

COS request headers

Structresp_headers

Returned HTTP response headers

Structresults

Processing result of the in-cloud data

StructRecognizing during download
Feature description
This feature recognizes QR codes during file download.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 210 of 1869

Cloud Infinite

cos_status_t *ci_get_qrcode(const cos_request_options_t *options,const cos_string_t *bucket,
const cos_string_t *object,
int cover,cos_table_t *headers,
cos_table_t *query_params,
cos_table_t **resp_headers,
ci_qrcode_result_t **results)

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 211 of 1869

Cloud Infinite#include "cos_http_io.h"#include "cos_api.h"#include "cos_log.h"#include <unistd.h>// `endpoint` is the COS access domain name. For more information, visit https://clstatic char TEST_COS_ENDPOINT[] = "cos.ap-guangzhou.myqcloud.com";// CI endpoint. For more information, visit https://cloud.tencent.com/document/prod
static char TEST_CI_ENDPOINT[] = "https://ci.ap-guangzhou.myqcloud.com";// A developer-owned secret ID/key used for the project. It can be obtained at httpstatic char *TEST_ACCESS_KEY_ID;//your secret_id©2013-2022 Tencent Cloud. All rights reserved.

Page 212 of 1869

Cloud Infinite

static char *TEST_ACCESS_KEY_SECRET;//your secret_key// A unique user-level resource identifier for COS access. It can be obtained at ht
static char TEST_APPID[] = "<APPID>";//your appid// COS bucket name in the format of [bucket]-[appid], for example, `mybucket-125366
static char TEST_BUCKET_NAME[] = "<bucketname-appid>";void log_status(cos_status_t *s){
cos_warn_log("status->code: %d", s->code);if (s->error_code) cos_warn_log("status->error_code: %s", s->error_code);if (s->error_msg) cos_warn_log("status->error_msg: %s", s->error_msg);
if (s->req_id) cos_warn_log("status->req_id: %s", s->req_id);}void init_test_config(cos_config_t *config, int is_cname){cos_str_set(&config->endpoint, TEST_COS_ENDPOINT);
cos_str_set(&config->access_key_id, TEST_ACCESS_KEY_ID);
cos_str_set(&config->access_key_secret, TEST_ACCESS_KEY_SECRET);
cos_str_set(&config->appid, TEST_APPID);
config->is_cname = is_cname;}void init_test_request_options(cos_request_options_t *options, int is_cname){options->config = cos_config_create(options->pool);
init_test_config(options->config, is_cname);
options->ctl = cos_http_controller_create(options->pool, 0);}
void test_ci_get_image_qrcode(){
cos_pool_t *p = NULL;
int is_cname = 0;
cos_status_t *s = NULL;
cos_request_options_t *options = NULL;
cos_string_t bucket;
cos_string_t object;cos_table_t *resp_headers;
ci_qrcode_info_t *content = NULL;
ci_qrcode_result_t *result2 = NULL;
cos_pool_create(&p, NULL);
options = cos_request_options_create(p);init_test_request_options(options, is_cname);
cos_str_set(&bucket, TEST_BUCKET_NAME);
cos_str_set(&object, "test.jpg");©2013-2022 Tencent Cloud. All rights reserved.

Page 213 of 1869

Cloud Infinite// Recognize during downloads = ci_get_qrcode(options, &bucket, &object, 1, NULL, NULL, &resp_headers, &res
log_status(s);if (!cos_status_is_ok(s)) {printf("get object failed\\n");}printf("CodeStatus: %d\\n", result2->code_status);
cos_list_for_each_entry(ci_qrcode_info_t, content, &result2->qrcode_info, node)printf("CodeUrl: %s\\n", content->code_url.data);
printf("Point: %s\\n", content->point[0].data);
printf("Point: %s\\n", content->point[1].data);
printf("Point: %s\\n", content->point[2].data);
printf("Point: %s\\n", content->point[3].data);}
printf("ImageResult: %s\\n", result2->result_image.data);// Terminate the memory poolcos_pool_destroy(p);}int main(int argc, char *argv[]){// Get `SECRETID` and `SECRETKEY` from environment variables
TEST_ACCESS_KEY_ID= getenv("COS_SECRETID");
TEST_ACCESS_KEY_SECRET = getenv("COS_SECRETKEY");
if (cos_http_io_initialize(NULL, 0) != COSE_OK) {exit(1);}//set log level, default COS_LOG_WARN
cos_log_set_level(COS_LOG_WARN);//set log output, default stderr
cos_log_set_output(NULL);
test_ci_get_image_qrcode();cos_http_io_deinitialize();
return 0;}

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 214 of 1869

Cloud Infinite

Parameter

Description

Type

options

COS request options

StructbucketBucket name in the format of BucketName-APPID . The bucket name entered
here must be in this format.

stringobjectObject namestringcover

Pixelates the recognized QR code. Valid values: 0 (no), 1 (yes).

int

headers

COS request headers

Structquery_params

COS request operation parameters

Structresp_headers

Returned HTTP response headers

Structresults

Recognized QR code

Struct©2013-2022 Tencent Cloud. All rights reserved.

Page 215 of 1869

Cloud Infinite

C++ SDK
Getting Started：

Last updated 2024-02-29 16:13:43

Download and Installation
Related resources
Download the COS XML C++ SDK source code below:
Linux/Windows/macOS: XML Linux C++ SDK
Download the XML C++ SDK.
Download the demo here.
For the SDK changelog, see Changelog.
Note:
If you encounter errors such as non-existent functions or methods when using the XML version of the SDK, update
the SDK to the latest version and try again.

Precompilation (Recommended)
Download the XML C++ SDK source code. In the libs directory, you can find the ready-to-use precompiled
libraries. Choose the one that suits your system version.

©2013-2022 Tencent Cloud. All rights reserved.

Page 216 of 1869

Cloud Infinite

libs/linux/libcossdk.a # Linux static library. `libcossdk.a` is compiled based on G
libs/linux/libcossdk-shared.so # Linux dynamic librarylibs/Win32/cossdk.lib # Windows 32-bit librarylibs/x64/cossdk.lib # Windows 64-bit librarylibs/macOS/libcossdk.a # macOS static librarylibs/macOS/libcossdk-shared.dylib # macOS dynamic library
Note:
Copy the libraries and SDK include files for your OS to your project.
The following third-party dependent libraries can be found in the Third-party directory:©2013-2022 Tencent Cloud. All rights reserved.

Page 217 of 1869

Cloud Infinite

third_party/lib/linux/poco/ # Linux-dependent POCO dynamic library. The POCO librar
third_party/lib/Win32/openssl/ # Windows 32-bit-dependent OpenSSL library
third_party/lib/Win32/poco/ # Windows 32-bit-dependent POCO library
third_party/lib/x64/openssl/ # Windows 64-bit-dependent OpenSSL library
third_party/lib/x64/poco/ # Windows 64-bit-dependent POCO library
third_party/lib/macOS/poco/ # macOS-dependent POCO library
Note:
Copy the dependent libraries for your OS to your project.

©2013-2022 Tencent Cloud. All rights reserved.

Page 218 of 1869

Cloud Infinite

Manual Compilation
Compilation options
You can configure the following compilation options by using the CMakeLists.txt file in the root directory:

option(BUILD_UNITTEST "Build unittest" OFF) # Configure unit testing compilation
option(BUILD_DEMO "Build demo" ON) # Configure demo testing code compilation
option(BUILD_SHARED_LIB "Build shared library" OFF) # Configure dynamic library com©2013-2022 Tencent Cloud. All rights reserved.

Page 219 of 1869

Cloud Infinite

Dependent libraries
Dynamic libraries: POCO, OpenSSL, and Crypto.

Compiling Linux SDK
1. Install the compiler and dependent libraries.

yum install -y gcc gcc-c++ make cmake openssl# The CMake version should be later than 2.8.

©2013-2022 Tencent Cloud. All rights reserved.

Page 220 of 1869

Cloud Infinite

2. Compile the SDK.
Download the XML C++ SDK source code to your development environment and run the following command:

cd ${cos-cpp-sdk}
mkdir -p build
cd build
cmake ..
make
3. Install the POCO library.

©2013-2022 Tencent Cloud. All rights reserved.

Page 221 of 1869

Cloud Infinite

cd ${cos-cpp-sdk}
sh install-libpoco.sh
Note:This script installs the POCO dynamic library to the /usr/lib64 directory and creates a soft link. To use a COS
SDK in the production environment, install the POCO library to the production environment as well.
4. Run the demo.
Note:
You can skip this step if you don't need to test the demo.

©2013-2022 Tencent Cloud. All rights reserved.

Page 222 of 1869

Cloud Infinite

cd ${cos-cpp-sdk}
vim demo/cos_demo.cpp # Modify the bucket name and testing code in the demo
vim CMakeLists.txt # Set `BUILD_DEMO` to `ON` in `CMakeLists.txt` to start compilin
cd build && make # Compile the demo
ls bin/cos_demo # The generated executable file is in the `bin` directoryvim bin/config.json # Modify the key and region
cd bin && ./cos_demo # Run the demo
5. Use the SDK.
The compiled libraries can be found in the build/lib directory. The static library name is libcossdk.a , and©2013-2022 Tencent Cloud. All rights reserved.

Page 223 of 1869

Cloud Infinite

the dynamic library name is libcossdk-shared.so . During actual use, copy the include directory to theinclude path of your project.

Compiling Windows SDK
1. Install Visual Studio 2017.
Install the Visual Studio 2017 development environment.
2. Install CMake.
Download the CMake for Windows compiler from CMake official website, and then configure ${CMakeinstallation path}\\bin in the Path environment variable.
3. Compile the SDK.
i. Download the XML Windows C++ SDK source code to your development environment.
ii. Open the Windows command-line tool, run cd to the directory of the C++ SDK source code, and run thefollowing command:©2013-2022 Tencent Cloud. All rights reserved.

Page 224 of 1869

Cloud Infinite

mkdir build
cd build
cmake .. # Generate the Windows 32-bit Makefile
cmake -G "Visual Studio 15 Win64" .. # Generate the Windows 64-bit Makefileiii. Use Visual Studio 2017 to open the Solution Explorer and perform compilation.
4. Run the demo.
Note:
You can skip this step if you don't need to test the demo.

©2013-2022 Tencent Cloud. All rights reserved.

Page 225 of 1869

Cloud Infinite

Modify the demo code and compile it. The generated cos_demo.exe file is in the bin directory. You can
modify bin/config.json to run cos_demo.exe .
5. Use the SDK.
The compiled libraries can be found in the build/Release directory. The static library name is cossdk.lib .
During actual use, copy the include directory to the include path of your project.

Compiling macOS SDK
1. Install the compiler and dependent libraries.

brew install gcc make cmake openssl©2013-2022 Tencent Cloud. All rights reserved.

Page 226 of 1869

Cloud Infinite

2. Compile the SDK.
Download the XML C++ SDK source code to your development environment and run the following command:

cd ${cos-cpp-sdk}
mkdir -p build
cd build
cmake ..
make©2013-2022 Tencent Cloud. All rights reserved.

Page 227 of 1869

Cloud Infinite

3. Install the POCO library.
The POCO library is in the third_party/lib/macOS/poco directory. You can install it by yourself.
4. Run the demo.
Note:
You can skip this step if you don't need to test the demo.
Modify the demo code and compile it. The generated cos_demo is in the bin directory. Copy cos-cpp-sdkv5/demo/config.json to the bin directory and modify bin/config.json . Then, you can run
cos_demo .
5. Use the SDK.
The compiled libraries can be found in the build/lib directory. The static library name is libcossdk.a , andthe dynamic library name is libcossdk-shared.dylib . During actual use, copy the include directory to
the include path of your project.

Common compilation errors
1. The following error information is displayed when the executable program is compiled:©2013-2022 Tencent Cloud. All rights reserved.

Page 228 of 1869

Cloud Infinite

PocoCrypto.so.64: undefined reference to `PEM_write_bio_PrivateKey@libcrypto.so.10'
libPocoNetSSL.so.64: undefined reference to `X509_check_host@libcrypto.so.10'
ibPocoCrypto.so.64: undefined reference to `ECDSA_sign@OPENSSL_1.0.1_EC'
libPocoCrypto.so.64: undefined reference to `CRYPTO_set_id_callback@libcrypto.so.10
ibPocoCrypto.so.64: undefined reference to `EVP_PKEY_id@libcrypto.so.10'
libPocoNetSSL.so.64: undefined reference to `SSL_get1_session@libssl.so.10'
libPocoNetSSL.so.64: undefined reference to `SSL_get_shutdown@libssl.so.10'
libPocoCrypto.so.64: undefined reference to `EVP_PKEY_set1_RSA@libcrypto.so.10'
libPocoCrypto.so.64: undefined reference to `SSL_load_error_strings@libssl.so.10'©2013-2022 Tencent Cloud. All rights reserved.

Page 229 of 1869

Cloud Infinite

This is usually caused by the inconsistency between the project's built-in SSL version on which the POCO librarycompilation depends and the SSL version on your device. You need to compile the POCO library again and replace
the POCO library in third_party .

wget https://github.com/pocoproject/poco/archive/refs/tags/poco-1.9.4-release.zip
cd poco-poco-1.9.4-release/./configure --omit=Data/ODBC,Data/MySQL
mkdir my_build
cd my_build
cmake ..
make -j5©2013-2022 Tencent Cloud. All rights reserved.

Page 230 of 1869

Cloud Infinite

2. The PocoNetSSL library failed to be compiled during POCO library compilation. This is usually because theopenssl-devel library is not installed.

yum install -y openssl-devel
3. The following error information is displayed when the executable program is compiled:©2013-2022 Tencent Cloud. All rights reserved.

Page 231 of 1869

Cloud Infinite

undefined reference to `qcloud_cos::CosConfig::CosConfig(std::__cxx11::basic_string
This is usually caused by the inconsistency between the project's built-in GCC version used by the libcossdk.acompilation and the GCC version on your device. You need to compile the POCO library and libcossdk.a again.

Getting Started©2013-2022 Tencent Cloud. All rights reserved.

Page 232 of 1869

Cloud Infinite

The section below describes how to use the COS C++ SDK to perform basic operations, such as initializing a client,creating a bucket, querying a bucket list, uploading an object, querying an object list, downloading an object, ordeleting an object.
Note:
For the definitions of terms such as SecretId , SecretKey , and bucket, see Introduction.

Initialization
Note:
We recommend you use a sub-account key and environment variables to call the SDK for security purposes. Whenauthorizing a sub-account, follow the Notes on Principle of Least Privilege to avoid leaking resources besides yourbuckets and objects.
If you must use a permanent key, we recommend you follow the Notes on Principle of Least Privilege to limit the scopeof permission on the permanent key.
Fields in the configuration file are as described below:©2013-2022 Tencent Cloud. All rights reserved.

Page 233 of 1869

Cloud Infinite{"SecretId":"********************************", // Replace the value with your `Secr"SecretKey":"*******************************", // Replace the value with your `Secr"Region":"ap-guangzhou",// Bucket region. Replace it with your buck
"SignExpiredTime":360,// Signature expiration time in seconds"ConnectTimeoutInms":6000,// Connection timeout period in milliseconds"ReceiveTimeoutInms":60000,// `Receive` timeout period in milliseconds"UploadPartSize":10485760,// Size of the part to be uploaded, which can b"UploadCopyPartSize":20971520,// Size of the copied part for upload, which ca"UploadThreadPoolSize":5,// Size of the upload thread pool for a single"DownloadSliceSize":4194304,// Size of the part to be downloaded©2013-2022 Tencent Cloud. All rights reserved.

Page 234 of 1869

Cloud Infinite"DownloadThreadPoolSize":5,"AsynThreadPoolSize":2,"LogoutType":1,"LogLevel":3,"IsDomainSameToHost":false,"DestDomain":"",// Size of the download thread pool for a singl// Size of the async thread pool for uploads/do// Log output type. Valid values: 0 (no output)// Log level. Valid values: 1 (ERR), 2 (WARN),// Whether to use a specific host// Specific host

"IsUseIntranet":false,"IntranetAddr":""}// Whether to use a specific IP and port number// Specific IP and port number, such as `127.0.

Accessing COS with temporary key
To access COS with a temporary key, see the code below:©2013-2022 Tencent Cloud. All rights reserved.

Page 235 of 1869

Cloud Infinite#include "cos_api.h"#include "cos_sys_config.h"#include "cos_defines.h"
int main(int argc, char *argv[]) {qcloud_cos::CosConfig config("./config.json");// Token is required for temporary keys but not permanent keys. For more informconfig.SetTmpToken("xxx");
qcloud_cos::CosAPI cos(config);}©2013-2022 Tencent Cloud. All rights reserved.

Page 236 of 1869

Cloud Infinite

Printing SDK internal logs to custom log file
To print SDK internal logs (especially for Windows) to a custom log file, see the code below:#include "cos_api.h"#include "cos_sys_config.h"#include "cos_defines.h"void TestLogCallback(const std::string& log) {std::ofstream ofs;
ofs.open("test.log", std::ios_base::app);ofs << log;
ofs.close();©2013-2022 Tencent Cloud. All rights reserved.

Page 237 of 1869

Cloud Infinite}
int main(int argc, char** argv) {qcloud_cos::CosConfig config("./config.json");config.SetLogCallback(&TestLogCallback);
qcloud_cos::CosAPI cos(config);}

Creating bucket#include "cos_api.h"©2013-2022 Tencent Cloud. All rights reserved.

Page 238 of 1869

Cloud Infinite#include "cos_sys_config.h"#include "cos_defines.h"
int main(int argc, char *argv[]) {// 1. Specify the path of the configuration file and initialize CosConfig
qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);// 2. Construct a request to create a bucket
std::string bucket_name = "examplebucket-1250000000"; // Bucket name in the for
qcloud_cos::PutBucketReq req(bucket_name);
qcloud_cos::PutBucketResp resp;// 3. Call the bucket creation API
qcloud_cos::CosResult result = cos.PutBucket(req, &resp);// 4. Process the call resultif (result.IsSucc()) {// Created successfully} else {// Failed to create the bucket. You can call the CosResult member functions
std::cout << "HttpStatus=" << result.GetHttpStatus() << std::endl;
std::cout << "ErrorCode=" << result.GetErrorCode() << std::endl;
std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
std::cout << "ResourceAddr=" << result.GetResourceAddr() << std::endl;
std::cout << "XCosRequestId=" << result.GetXCosRequestId() << std::endl;
std::cout << "XCosTraceId=" << result.GetXCosTraceId() << std::endl;}}

Querying bucket list

©2013-2022 Tencent Cloud. All rights reserved.

Page 239 of 1869

Cloud Infinite#include "cos_api.h"#include "cos_sys_config.h"#include "cos_defines.h"
int main(int argc, char *argv[]) {// 1. Specify the path of the configuration file and initialize CosConfig
qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);// 2. Construct a request to query the bucket list
qcloud_cos::GetServiceReq req;©2013-2022 Tencent Cloud. All rights reserved.

Page 240 of 1869

Cloud Infinite

qcloud_cos::GetServiceResp resp;
qcloud_cos::CosResult result = cos.GetService(req, &resp);// 3. Get the response information
const qcloud_cos::Owner& owner = resp.GetOwner();
const std::vector<qcloud_cos::Bucket>& buckets = resp.GetBuckets();
std::cout << "owner.m_id=" << owner.m_id << ", owner.display_name=" << owner.m_for (std::vector<qcloud_cos::Bucket>::const_iterator itr = buckets.begin(); itrconst qcloud_cos::Bucket& bucket = *itr;
std::cout << "Bucket name=" << bucket.m_name << ", location="<< bucket.m_location << ", create_date=" << bucket.m_create_date << std}// 4. Process the call resultif (result.IsSucc()) {// Queried the bucket list successfully} else {// Failed to query the bucket list. You can call the CosResult member functstd::cout << "HttpStatus=" << result.GetHttpStatus() << std::endl;
std::cout << "ErrorCode=" << result.GetErrorCode() << std::endl;
std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
std::cout << "ResourceAddr=" << result.GetResourceAddr() << std::endl;
std::cout << "XCosRequestId=" << result.GetXCosRequestId() << std::endl;
std::cout << "XCosTraceId=" << result.GetXCosTraceId() << std::endl;}}

Uploading object©2013-2022 Tencent Cloud. All rights reserved.

Page 241 of 1869

Cloud Infinite#include "cos_api.h"#include "cos_sys_config.h"#include "cos_defines.h"
int main(int argc, char *argv[]) {// 1. Specify the path of the configuration file and initialize CosConfig
qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);// 2. Construct a request to upload a file
std::string bucket_name = "examplebucket-1250000000"; // Bucket name in the for©2013-2022 Tencent Cloud. All rights reserved.

Page 242 of 1869

Cloud Infinite

std::string object_name = "exampleobject"; // `exampleobject` is the object key
qcloud_cos::PutObjectByFileReq req(bucket_name, object_name, "/path/to/local/fi//req.SetXCosStorageClass("STANDARD_IA"); // `STANDARD_IA` is the default value
qcloud_cos::PutObjectByFileResp resp;// 3. Call the object uploading API
qcloud_cos::CosResult result = cos.PutObject(req, &resp);// 4. Process the call resultif (result.IsSucc()) {// Uploaded the file successfully} else {// Failed to upload the file. You can call the CosResult member functions t
std::cout << "HttpStatus=" << result.GetHttpStatus() << std::endl;
std::cout << "ErrorCode=" << result.GetErrorCode() << std::endl;
std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
std::cout << "ResourceAddr=" << result.GetResourceAddr() << std::endl;
std::cout << "XCosRequestId=" << result.GetXCosRequestId() << std::endl;
std::cout << "XCosTraceId=" << result.GetXCosTraceId() << std::endl;}}

Querying object list

©2013-2022 Tencent Cloud. All rights reserved.

Page 243 of 1869

Cloud Infinite#include "cos_api.h"#include "cos_sys_config.h"#include "cos_defines.h"
int main(int argc, char *argv[]) {// 1. Specify the path of the configuration file and initialize CosConfig
qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);// 2. Construct a request to query the object list
std::string bucket_name = "examplebucket-1250000000"; // Bucket name in the for©2013-2022 Tencent Cloud. All rights reserved.

Page 244 of 1869

Cloud Infinite

qcloud_cos::GetBucketReq req(bucket_name);
qcloud_cos::GetBucketResp resp;
qcloud_cos::CosResult result = cos.GetBucket(req, &resp);
std::vector<qcloud_cos::Content> cotents = resp.GetContents();for (std::vector<qcloud_cos::Content>::const_iterator itr = cotents.begin(); it
const qcloud_cos::Content& content = *itr;
std::cout << "key name=" << content.m_key << ", lastmodified ="<< content.m_last_modified << ", size=" << content.m_size << std::endl;}// 3. Process the call resultif (result.IsSucc()) {// Queried the object list successfully} else {// Failed to query the object list. You can call the CosResult member functstd::cout << "HttpStatus=" << result.GetHttpStatus() << std::endl;
std::cout << "ErrorCode=" << result.GetErrorCode() << std::endl;
std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
std::cout << "ResourceAddr=" << result.GetResourceAddr() << std::endl;
std::cout << "XCosRequestId=" << result.GetXCosRequestId() << std::endl;
std::cout << "XCosTraceId=" << result.GetXCosTraceId() << std::endl;}}

Downloading object©2013-2022 Tencent Cloud. All rights reserved.

Page 245 of 1869

Cloud Infinite#include "cos_api.h"#include "cos_sys_config.h"#include "cos_defines.h"
int main(int argc, char *argv[]) {// 1. Specify the path of the configuration file and initialize CosConfig
qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);// 2. Construct a request to download an object
std::string bucket_name = "examplebucket-1250000000"; // Bucket name in the for©2013-2022 Tencent Cloud. All rights reserved.

Page 246 of 1869

Cloud Infinite

std::string object_name = "exampleobject"; // `exampleobject` is the object key
std::string local_path = "/tmp/exampleobject";// `appid`, `bucketname`, `object`, and a local path (including filename) are r
qcloud_cos::GetObjectByFileReq req(bucket_name, object_name, local_path);
qcloud_cos::GetObjectByFileResp resp;// 3. Call the object downloading API
qcloud_cos::CosResult result = cos.GetObject(req, &resp);// 4. Process the call resultif (result.IsSucc()) {// Downloaded the file successfully} else {// Failed to download the file. You can call the CosResult member functions
std::cout << "HttpStatus=" << result.GetHttpStatus() << std::endl;
std::cout << "ErrorCode=" << result.GetErrorCode() << std::endl;
std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
std::cout << "ResourceAddr=" << result.GetResourceAddr() << std::endl;
std::cout << "XCosRequestId=" << result.GetXCosRequestId() << std::endl;
std::cout << "XCosTraceId=" << result.GetXCosTraceId() << std::endl;}}

Deleting object©2013-2022 Tencent Cloud. All rights reserved.

Page 247 of 1869

Cloud Infinite#include "cos_api.h"#include "cos_sys_config.h"#include "cos_defines.h"
int main(int argc, char *argv[]) {// 1. Specify the path of the configuration file and initialize CosConfig
qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);// 2. Construct a request to delete an object
std::string bucket_name = "examplebucket-1250000000"; // Bucket name in the for©2013-2022 Tencent Cloud. All rights reserved.

Page 248 of 1869

Cloud Infinite

std::string object_name = "exampleobject"; // `exampleobject` is the object key// 3. Call the object deleting API
qcloud_cos::DeleteObjectReq req(bucket_name, object_name);
qcloud_cos::DeleteObjectResp resp;
qcloud_cos::CosResult result = cos.DeleteObject(req, &resp);// 4. Process the call resultif (result.IsSucc()) {// Deleted the object successfully} else {// Failed to delete the object. You can call the CosResult member functions
std::cout << "HttpStatus=" << result.GetHttpStatus() << std::endl;
std::cout << "ErrorCode=" << result.GetErrorCode() << std::endl;
std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
std::cout << "ResourceAddr=" << result.GetResourceAddr() << std::endl;
std::cout << "XCosRequestId=" << result.GetXCosRequestId() << std::endl;
std::cout << "XCosTraceId=" << result.GetXCosTraceId() << std::endl;}}©2013-2022 Tencent Cloud. All rights reserved.

Page 249 of 1869

Cloud Infinite

Image Processing
Persistent Image Processing：

Last updated 2024-02-29 16:13:43

Overview
This document provides an overview of APIs and SDK code samples for persistent image processing.
API

Description

Persistent image processing

Processes images persistently.

Processing during upload
Feature description
CI allows you to process images during upload and save the input images and processing results to COS. Currently,
images within 20 MB can be processed.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 250 of 1869

Cloud Infinite

CosResult PutImage(const PutImageByFileReq& request, PutImageByFileResp* response);

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 251 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
std::string bucket_name = "examplebucket-1250000000";
PutImageByFileReq req(bucket_name, object_name, local_file);
PutImageByFileResp resp;
PicOperation pic_operation;
PicRules rule;// Path of the processing result file. If the path starts with `/`, the result file

©2013-2022 Tencent Cloud. All rights reserved.

Page 252 of 1869

Cloud Infinite

rule.fileid = "/" + object_name + "_sharpen";// Sharpening parameterrule.rule = "imageMogr2/sharpen/70";
pic_operation.AddRule(rule);
rule.fileid = "/" + object_name + "_rotate";// Rotation parameterrule.rule = "imageMogr2/rotate/90";
pic_operation.AddRule(rule);
CosResult result = cos.PutImage(req, &resp);
if (result.IsSucc()) {// The call is successful. You can call the `resp` member functions to get the rstd::cout << "ProcessResult: " << resp.GetUploadResult().to_string() << std::end} else {// The call failed. You can call the `result` member functions to get the error}

Parameter description
Parameter

Description

Type

Requiredreq

PutImage operation request.

PutImageByFileReq

Yes

resp

PutImage operation response.

PutImageByFileResp

Yesreq involves the following structures:©2013-2022 Tencent Cloud. All rights reserved.

Page 253 of 1869

Cloud Infinite

struct PicRules {std::string bucket; // Name of the destination bucket to store the results in th
std::string fileid; // Path of the processing result file. If the path starts wi
std::string rule; // Processing parameters. For more information, see the COS im};class PicOperation {public:PicOperation() : is_pic_info(true) {}virtual ~PicOperation() {}void AddRule(const PicRules& rule) { rules.push_back(rule); }©2013-2022 Tencent Cloud. All rights reserved.

Page 254 of 1869

Cloud Infinite

void TurnOffPicInfo() { is_pic_info = false; }private:boolis_pic_info; // Whether to return the input image information. Valid values:
std::vector<PicRules> rules; // Processing rules (up to five rules are supported};
resp involves the following structures:

struct CodeLocation {std::vector<std::string> points;};©2013-2022 Tencent Cloud. All rights reserved.

// QR code coordinates

Page 255 of 1869

Cloud Infinite

struct QRcodeInfo {std::string code_url;
CodeLocation code_location;// QR code content. Content may not be recognized.
// Location coordinates of the QR code recognized in};struct Object {
std::string key;
std::string location;
std::string format;
int width;
int height;
int size;
int quality;
std::string etag;// Filename// Image path// Image format// Image width// Image height// Image size// Image quality// `ETag` of the processing result image

int code_status; // Whether QR codes are recognized. 0: no; 1: yes.
int watermark_status; // When `type`// is 2, this field will be returned to indicate the confi// Value range: 0–100. If the value is above 75, there is
std::vector<QRcodeInfo> qr_code_info; // Recognized QR code. There may be multip};
struct ProcessResults {
std::vector<Object> objects;};
struct ImageInfo {std::string format;
int width;
int height;
int quality;
std::string ave;
int orientation;};// There may be multiple objects// Format// Image width// Image height// Image quality// Image average hue// Image rotation angle

struct UploadResult {OriginalInfo original_info; // Input image information
ProcessResults process_result; // Image processing result};

Processing in-cloud image
Feature description
This feature can process an image stored in COS and save the processing result to COS.

©2013-2022 Tencent Cloud. All rights reserved.

Page 256 of 1869

Cloud Infinite

Method prototype

CosResult CloudImageProcess(const CloudImageProcessReq& request, CloudImageProcessR

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 257 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
std::string bucket_name = "examplebucket-1250000000";CloudImageProcessReq req(bucket_name, object_name);
CloudImageProcessResp resp;
PicOperation pic_operation;
PicRules rule;// Path of the processing result file. If the path starts with `/`, the result filerule.fileid = "/" + object_name + "_thumbnail";©2013-2022 Tencent Cloud. All rights reserved.

Page 258 of 1869

Cloud Infinite// Scaling parameterrule.rule = "imageMogr2/thumbnail/!30p";
pic_operation.AddRule(rule);
rule.fileid = "/" + object_name + "_cut";// Cropping parameterrule.rule = "imageMogr2/cut/300x300";
pic_operation.AddRule(rule);
req.SetPicOperation(pic_operation);
CosResult result = cos.CloudImageProcess(req, &resp);
if (result.IsSucc()) {// The call is successful. You can call the `resp` member functions to get the r} else {// The call failed. You can call the `result` member functions to get the error}

Parameter description
Parameter

Description

Type

Requiredreq

PutImage operation request.

PutImageByFileReq

Yes

resp

PutImage operation response.

PutImageByFileResp

Yes©2013-2022 Tencent Cloud. All rights reserved.

Page 259 of 1869

Cloud Infinite

Basic Image Processing：

Last updated 2024-02-29 16:13:43

Overview
COS has integrated Cloud Infinite (CI), a one-stop professional multimedia solution that offers the image processing
features as outlined below. For more information, see Image Processing Overview.
ServiceFeatureDescription

Scaling

Proportional scaling, scaling image to target width and height

Cropping
Rotation
Format conversion

Basic image
processing

Regular cropping, cropping and scaling, cropping to circle,
smart face cropping
Adaptive rotation, regular rotation
Format conversion, GIF format optimization, progressive
display

Quality change

Quality change for JPG and WebP images

Gaussian blurring

Image blurring

Sharpening

Image sharpening

Watermarking

Image watermark, text watermark

Image informationacquisition

Basic information, EXIF information, average hue

Metadata removal

Including EXIF information

Quick thumbnail
template

Quick image format conversion, scaling, and cropping for
thumbnail generation

Style configuration

Image style configuration for easy image management

Basic Image Processing©2013-2022 Tencent Cloud. All rights reserved.

Page 260 of 1869

Cloud Infinite

ScalingFeature description
Proportional scaling, scaling image to target width and height, etc.
Method prototype

CosResult GetObject(const GetObjectByFileReq& request, GetObjectByFileResp* respons

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 261 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
std::string bucket_name = "examplebucket-1250000000";
qcloud_cos::GetObjectByFileReq req(bucket_name, object_name, local_file);// Scale an image to 50% of its original width and height
req.AddParam("imageMogr2/thumbnail/!50p", "");
qcloud_cos::GetObjectByFileResp resp;
qcloud_cos::CosResult result = cos.GetObject(req, &resp);
if (result.IsSucc()) {// The call is successful. You can call the `resp` member functions to get the r©2013-2022 Tencent Cloud. All rights reserved.

Page 262 of 1869

Cloud Infinite} else {// The call failed. You can call the `result` member functions to get the error}

Parameter description
Parameter

Description

Type

Requiredreq

GetObject operation request

GetObjectByFileReq

Yes

resp

GetObject operation response

GetObjectByFileResp

Yes

Cropping
Feature description
Similar to the scaling operation.

©2013-2022 Tencent Cloud. All rights reserved.

Page 263 of 1869

Cloud Infinite

Blind Watermark：

Last updated 2024-02-29 16:13:43

Overview
This document provides an overview of APIs and SDK code samples for blind watermarking.
API

Description

Blind

Adds blind watermark to or extracts blind watermark from local image and uploads it towatermarking

bucketAdding Blind Watermark During Upload
Feature description
This API is used to add a blind watermark when uploading images.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 264 of 1869

Cloud Infinite

CosResult PutImage(const PutImageByFileReq& request, PutImageByFileResp* response);

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 265 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
std::string bucket_name = "examplebucket-1250000000";
PutImageByFileReq req(bucket_name, object_name, local_file);
PutImageByFileResp resp;
PicOperation pic_operation;
PicRules rule;// File storage pathrule.fileid = "/" + object_name + "_watermark";©2013-2022 Tencent Cloud. All rights reserved.

Page 266 of 1869

Cloud Infinite// URL-safe Base64-encoded URL of the blind watermark image
std::string image = "http://" + bucket_name + ".cos.ap-guangzhou.myqcloud.com/" + o// Blind watermark processing parameterrule.rule = "watermark/3/type/1/image/" + CodecUtil::Base64Encode(image);
pic_operation.AddRule(rule);
CosResult result = cos.PutImage(req, &resp);
if (result.IsSucc()) {// The call is successful. You can call the `resp` member functions to get the r} else {// The call failed. You can call the `result` member functions to get the error}

Parameter description
Parameter

Description

Type

Requiredreq

PutImage operation request.

PutImageByFileReq

Yes

resp

PutImage operation response.

PutImageByFileResp

YesAdding Blind Watermark During Download
Feature description
This API is used to add a blind watermark when downloading images.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 267 of 1869

Cloud Infinite

CosResult GetObject(const GetObjectByFileReq& request, GetObjectByFileResp* respons

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 268 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
std::string bucket_name = "examplebucket-1250000000";
GetObjectByFileReq req(bucket_name, object_name, local_file);
GetObjectByFileResp resp;// Blind watermark text
std::string watermark_text = "test";// URL-safe Base64-encoded blind watermark parameter
std::string watermark_param = "watermark/3/type/3/text/" + CodecUtil::Base64Encode(©2013-2022 Tencent Cloud. All rights reserved.

Page 269 of 1869

Cloud Infinite

req.AddParam(watermark_param, "");
CosResult result = cos.GetObject(req, &resp);
if (result.IsSucc()) {// The call is successful. You can call the `resp` member functions to get the r} else {// The call failed. You can call the `result` member functions to get the error}

Parameter description
Parameter

Description

Type

Requiredreq

PutImage operation request.

PutImageByFileReq

Yes

resp

PutImage operation response.

PutImageByFileResp

Yes©2013-2022 Tencent Cloud. All rights reserved.

Page 270 of 1869

Cloud Infinite

Media Processing
Media Bucket APIs：

Last updated 2024-02-29 16:13:43

Overview
This document provides an overview of APIs and SDK code samples for media buckets.
API
DescribeMediaBuckets

Operation

Description

Querying media processing activation

Queries buckets with media processing

statusenabledQuerying Media Processing Activation Status
Feature description
This API is used to query buckets with media processing enabled.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 271 of 1869

Cloud Infinite

CosResult DescribeMediaBuckets(const DescribeMediaBucketsReq& request, DescribeMedi

Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 272 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
DescribeMediaBucketsReq req;
DescribeMediaBucketsResp resp;
req.SetRegions("ap-guangzhou");// Set the bucket name. To specify multiple bucket names, separate them with commas// req.SetBucketNames("xxx");// Set the bucket name prefix for prefix search// req.SetBucketName("xxx");// Set the page number// req.SetPageNumber();©2013-2022 Tencent Cloud. All rights reserved.

Page 273 of 1869

Cloud Infinite// Set the number of entries per page// req.SetPageSize();
CosResult result = cos.DescribeMediaBuckets(req, &resp);
qcloud_cos::CosResult result = cos.GetObject(req, &resp);
if (result.IsSucc()) {// The call is successful. You can call the `resp` member functions to get the rstd::cout << "Result: " << resp.GetResult().to_string() << std::endl;} else {// The call failed. You can call the `result` member functions to get the error}

Parameter description
Parameter

Description

Type

Required

requestOperation request.

DescribeMediaBucketsReq

Yes

response

Operation response.

DescribeMediaBucketsResp

Yes©2013-2022 Tencent Cloud. All rights reserved.

Page 274 of 1869

Cloud Infinite

Media Information APIs：

Last updated 2024-02-29 16:13:43

Overview
This document provides an overview of APIs and SDK code samples for media information.
API

Operation

Description

GetMediaInfo

Querying file information

Queries media file information

Querying File Information
Feature description
This API is used to get media file information.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 275 of 1869

Cloud Infinite

CosResult GetMediaInfo(const GetMediaInfoReq& request, GetMediaInfoResp* response);

Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 276 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
GetMediaInfoReq req(bucket_name, object_name);
GetMediaInfoResp resp;
CosResult result = cos.GetMediaInfo(req, &resp);
if (result.IsSucc()) {// The call is successful. You can call the `resp` member functions to get the rstd::cout << "Result: " << resp.GetResult().to_string() << std::endl;} else {// The call failed. You can call the `result` member functions to get the error}©2013-2022 Tencent Cloud. All rights reserved.

Page 277 of 1869

Cloud Infinite

Parameter description
Parameter

Description

Type

Required

requestOperation request.

GetMediaInfoReq

Yes

response

Operation response.

GetMediaInfoResp

Yes©2013-2022 Tencent Cloud. All rights reserved.

Page 278 of 1869

Cloud Infinite

Media Screenshot APIs：

Last updated 2024-02-29 16:13:43

Overview
This document provides an overview of APIs and SDK code samples for media screenshot.
API

Operation

Description

GetSnapshot

Querying screenshot

Query the screenshot of media file at some time point

Querying Screenshot
Feature description
This API is used to get a screenshot of a media file at some time point and put the screenshot information in a local
file.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 279 of 1869

Cloud Infinite

CosResult GetSnapshot(const GetSnapshotReq& request, GetSnapshotResp* response);

Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 280 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
GetSnapshotReq req(bucket_name, object_name, local_file);
GetSnapshotResp resp;
req.SetTime(100);// Set the screenshot width// req.SetWitdh(xxx);// Set the screenshot height// req.SetHeight(xxx);// Set the format// req.SetFormat(xxx);©2013-2022 Tencent Cloud. All rights reserved.

Page 281 of 1869

Cloud Infinite

CosResult result = cos.GetSnapshot(req, &resp);
if (result.IsSucc()) {// The call is successful. You can call the `resp` member functions to get the r} else {// The call failed. You can call the `result` member functions to get the error}

Parameter description
Parameter

Description

Type

Required

requestOperation request.

GetSnapshotReq

Yes

response

Operation response.

GetSnapshotResp

Yes©2013-2022 Tencent Cloud. All rights reserved.

Page 282 of 1869

Cloud Infinite

Content Moderation
Image Moderation：

Last updated 2024-02-29 16:13:43

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for image moderation.
API
Moderating single image
Batch moderating images
Querying image moderation job
resultDescription
Scans existing data stored in COS for porn, illegal, and advertising
images.
Moderates multiple images in batches.
Queries the result of specified image moderation job.

Single Image Moderation
Feature description
The existing data scan feature of image moderation leverages CI's persistent processing API to scan existing datastored in COS for porn, illegal, and advertising images.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 283 of 1869

Cloud Infinite

CosResult GetImageAuditing(const GetImageAuditingReq& req, GetImageAuditingResp* re

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 284 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
std::string bucket_name = "examplebucket-1250000000";
std::string object_name = "test.jpg";
GetImageAuditingReq req(bucket_name);
GetImageAuditingResp resp;// Add request parameters as detailed in the API documentation
req.SetObjectKey(object_name);
req.SetBizType("b81d45f94b91a683255e9a9506f45a11");©2013-2022 Tencent Cloud. All rights reserved.

Page 285 of 1869

Cloud Infinite// req.SetDetectType("Porn,Ads");// Call the API to get the job response object
CosResult result = cos.GetImageAuditing(req, &resp);
if (result.IsSucc()) {// If the moderation job is created successfully, you can call the member funct} else {// If the moderation job failed to be created, you can call the member function}

Parameter description
Parameter

Description

Type

Requiredreq

GetImageAuditing operation request

GetImageAuditingReq

Yes

resp

GetImageAuditing operation response

GetImageAuditingResp

Yes

GetImageAuditingReq provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 286 of 1869

Cloud Infinite// Set the bucket for performing the operation
void SetBucketName(const std::string& bucket_name);// Name of the image file to be moderated in the COS bucket
void SetObjectKey(const std::string& object_name);// Unique identifier of the moderation policy. You can configure the scenes you wan// You can get `BizType` in the console. If `BizType` is specified, the moderation
void SetBizType(const std::string& biz_type);// The scene to be moderated, such as `Porn` (pornography) and `Ads` (advertising).
void SetDetectType(const std::string& detect_type);// URL of the image to be moderated, which can be a URL of any image accessible ove// If `detect-url` is set, moderation will be conducted by `detect-url` by default,©2013-2022 Tencent Cloud. All rights reserved.

Page 287 of 1869

Cloud Infinite// If `detect-url` is not set, moderation will be conducted by `ObjectKey` by defau
void SetDetectUrl(const std::string& detect_url);// For GIF image moderation, you can use this parameter to configure the frame capt
void SetInterval(int interval);// Maximum number of frames to be captured for animated image moderation. Default v
void SetMaxFrames(int max_frames);// Whether to compress the image that exceeds the size limit before moderation. Val
void SetLargeImageDetect(int large_image_detect);// Image ID. This field will return the original content, which can contain up to 5
void SetDataId(const std::string& data_id);
GetImageAuditingResp provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 288 of 1869

Cloud Infinite// Get the job details returned by the API request
ImageAuditingJobsDetail GetJobsDetail();// Get the `RequestId` returned by the API
std::string GetRequestId();

Response description
Success: The moderation job result in the XML content returned by the API will be parsed into the
ImageAuditingJobsDetail structure. For specific response parameters, see Single Image Moderation.

©2013-2022 Tencent Cloud. All rights reserved.

Page 289 of 1869

Cloud Infinite

Failure: If an error (for example, the bucket does not exist) occurs, the error message will be parsed into the
CosResult structure. For more information, see Troubleshooting.

Batch Image Moderation
Feature description
The batch image moderation API adopts a sync POST request method. You can use this API to perform content
moderation on multiple image files.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 290 of 1869

Cloud Infinite

CosResult CosAPI::BatchImageAuditing(const BatchImageAuditingReq& req, BatchImageAu

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 291 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
std::string bucket_name = "examplebucket-1250000000";
std::string object_name_a = "test1.jpg";
std::string object_name_b = "test2.jpg";
BatchImageAuditingReq req(bucket_name);
BatchImageAuditingResp resp;// input 1
AuditingInput input_a = AuditingInput();©2013-2022 Tencent Cloud. All rights reserved.

Page 292 of 1869

Cloud Infinite

input_a.SetObject(object_name_a);req.AddInput(input_a);// input2
AuditingInput input_b = AuditingInput();
input_a.SetObject(object_name_b);
req.AddInput(input_b);// Moderation configuration
req.SetBizType("b81d45f94b91a683255e9a9506f45a11");// req.SetDetectType("Porn,Ads");// Call the API to get the job response object
CosResult result = cos.BatchImageAuditing(req, &resp);
if (result.IsSucc()) {// If the moderation job is created successfully, you can call the member funct} else {// If the moderation job failed to be created, you can call the member function}

Parameter description
Parameter

Description

Type

Requiredreq

BatchImageAuditing operation request

BatchImageAuditingReq

Yes

resp

BatchImageAuditing operation response

BatchImageAuditingResp

Yes

AuditingInput

Yes

input

Input parameter of the BatchImageAuditing
operation request

BatchImageAuditingReq provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 293 of 1869

Cloud Infinite// Set the bucket for performing the operation
void SetBucketName(const std::string& bucket_name);// Set the moderation configuration
void SetConf(const Conf& conf);// Unique identifier of the moderation policy. You can configure the scenes you wan// You can get `BizType` in the console. If `BizType` is specified, the moderation
void SetBizType(const std::string& biz_type);// The scene to be moderated, such as `Porn` (pornography) and `Ads` (advertising).
void SetDetectType(const std::string& detect_type);// Add the input for single image moderation
void AddInput(const AuditingInput& input);©2013-2022 Tencent Cloud. All rights reserved.

Page 294 of 1869

Cloud Infinite// Set the input array for batch moderation
void SetInputs(const std::vector<AuditingInput>& inputs);
AuditingInput provides the following member functions:// Name of the image file to be moderated in the COS bucket
void SetObject(const std::string& object);// Full URL of the image file, such as `http://a-1250000.cos.ap-shanghai.myqcloud.cvoid SetUrl(const std::string& url);// Frame capturing frequency, which takes effect for GIF images only. The default v
void SetInterval(const int interval);©2013-2022 Tencent Cloud. All rights reserved.

Page 295 of 1869

Cloud Infinite// The maximum number of frames to be captured, which takes effect for GIF images ovoid SetMaxFrames(const int max_frames);// Image ID. This field will return the original content in the result, which can cvoid SetDataId(const std::string& data_id);// Whether to compress the image that exceeds the size limit before moderation. Val
void SetLargeImageDetect(const int large_image_detect);// Business field.
void SetUserInfo(const UserInfo& user_info);
BatchImageAuditingResp provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 296 of 1869

Cloud Infinite// Get the job details returned by the API request
std::vector<ImageAuditingJobsDetail> GetJobsDetails();// Get the `RequestId` returned by the API
std::string GetRequestId();

Response description
Success: The moderation job result in the XML content returned by the API will be parsed into the
ImageAuditingJobsDetail structure array. For specific response parameters, see Batch Image Moderation.
Failure: If an error (for example, the bucket does not exist) occurs, the error message will be parsed into the
CosResult structure. For more information, see Troubleshooting.

Querying Image Moderation Job Result
Feature description
This API is used to submit an image moderation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 297 of 1869

Cloud Infinite

CosResult DescribeImageAuditingJob(const DescribeImageAuditingJobReq &req, Describe

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 298 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
std::string bucket_name = "examplebucket-1250000000";
DescribeImageAuditingJobReq req(bucket_name);
DescribeImageAuditingJobResp resp;// Add request parameters as detailed in the API documentation
req.SetJobId("vab1ca9fc8a3ed11ea834c525400863904");// Call the API to get the job response object©2013-2022 Tencent Cloud. All rights reserved.

Page 299 of 1869

Cloud Infinite

CosResult result = cos.DescribeImageAuditingJob(req, &resp);
if (result.IsSucc()) {// If the moderation job is created successfully, you can call the member funct} else {// If the moderation job failed to be created, you can call the member function}

Parameter description
Parameter
req

resp

Description
DescribeImageAuditingJob operation
requestDescribeImageAuditingJob operation
response

Type

Required

DescribeImageAuditingJobReq

Yes

DescribeImageAuditingJobResp

Yes

DescribeVideoAuditingJobReq provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 300 of 1869

Cloud Infinite// Set the bucket for performing the operation
void SetBucketName(const std::string& bucket_name);// Set the ID of the moderation job to be queried
void SetJobId(const std::string& job_id);
DescribeVideoAuditingJobResp provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 301 of 1869

Cloud Infinite// Get the job details returned by the API request
ImageAuditingJobsDetail GetJobsDetail();// Get the `RequestId` returned by the API
std::string GetRequestId();

Response description
Success: The moderation job result in the XML content returned by the API will be parsed into the
ImageAuditingJobsDetail structure. For specific response parameters, see Querying Image Moderation Job©2013-2022 Tencent Cloud. All rights reserved.

Page 302 of 1869

Cloud Infinite

Result.
Failure: If an error (for example, the bucket does not exist) occurs, the error message will be parsed into the
CosResult structure. For more information, see Troubleshooting.

©2013-2022 Tencent Cloud. All rights reserved.

Page 303 of 1869

Cloud Infinite

Video Moderation：

Last updated 2024-02-29 16:13:43

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for video moderation.
API

Description

Submitting video moderation job

Submits video moderation job.

Querying video moderation job result

Queries the result of specified video moderation job.

Submitting Video Moderation Job
Feature description
This API is used to submit a video moderation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 304 of 1869

Cloud Infinite

CosResult CreateVideoAuditingJob(const CreateVideoAuditingJobReq& req, CreateVideoA

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 305 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
std::string bucket_name = "examplebucket-1250000000";
std::string object_name = "test.mp4";
CreateVideoAuditingJobReq req(bucket_name);
CreateVideoAuditingJobResp resp;// Add request parameters as detailed in the API documentation
req.SetObject(object_name);
req.SetBizType("b81d45f94b91a683255e9a9506f45a11");©2013-2022 Tencent Cloud. All rights reserved.

Page 306 of 1869

Cloud Infinite// req.SetDetectType("Porn,Ads");
SnapShotConf snap_shot = SnapShotConf();snap_shot.SetCount(100);snap_shot.SetMode("Interval");snap_shot.SetTimeInterval(10);req.SetSnapShot(snap_shot);// Call the API to get the job response object
CosResult result = cos.CreateVideoAuditingJob(req, &resp);
if (result.IsSucc()) {// If the moderation job is created successfully, you can call the member funct} else {// If the moderation job failed to be created, you can call the member function}

Parameter description
Parameter

Description

Type

RequiredreqCreateVideoAuditing operation request

CreateVideoAuditingReq

Yes

resp

CreateVideoAuditing operation response

CreateVideoAuditingResp

Yes

CreateVideoAuditingReq provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 307 of 1869

Cloud Infinite// Set the bucket for performing the operation
void SetBucketName(const std::string& bucket_name);// Set the input video to be moderated
void SetInput(const AuditingInput& input);// Set moderation configuration rules
void SetConf(const Conf& conf);// conf// Unique identifier of the moderation policy. You can configure the scenes you wan// You can get `BizType` in the console. If `BizType` is specified, the moderation
void SetBizType(const std::string& biz_type);©2013-2022 Tencent Cloud. All rights reserved.

Page 308 of 1869

Cloud Infinite// The scene to be moderated, such as `Porn` (pornography) and `Ads` (advertising).
void SetDetectType(const std::string& detect_type);// Video image moderation is implemented by taking a certain number of screenshots
void SetSnapShot(const SnapShotConf& snap_shot);// Callback address, which must start with `http://` or `https://`.
void SetCallBack(const std::string& callback);// Structure of the callback content. Valid values: `Simple` (the callback content
void SetCallBackVersion(const std::string& callback_version);// Specify whether to moderate video sound. Valid values: `0` (moderates the video
void SetDetectContent(const int detect_content);// input// Name of the video file stored in the COS bucket; for example, if the file is `vi
void SetObject(const std::string& object);// Full URL of the video file, such as `http://examplebucket-1250000000.cos.ap-shan
void SetUrl(const std::string& url);// This field will return the original content in the moderation result, which canvoid SetDataId(const std::string& data_id);// Business field.
void SetUserInfo(const UserInfo& user_info);
CreateVideoAuditingResp provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 309 of 1869

Cloud Infinite// Get the job details returned by the API request
VideoAuditingJobsDetail GetJobsDetail();// Get the `RequestId` returned by the API
std::string GetRequestId();

Response description
Success: The moderation job result in the XML content returned by the API will be parsed into theVideoAuditingJobsDetail structure. For specific response parameters, see Submitting Video Moderation©2013-2022 Tencent Cloud. All rights reserved.

Page 310 of 1869

Cloud Infinite

Job.
Failure: If an error (for example, the bucket does not exist) occurs, the error message will be parsed into the
CosResult structure. For more information, see Troubleshooting.

Querying Video Moderation Job Result
Feature description
This API is used to query the status and result of a video moderation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 311 of 1869

Cloud Infinite

CosResult DescribeVideoAuditingJob(const DescribeVideoAuditingJobReq& req, Describe

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 312 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
std::string bucket_name = "examplebucket-1250000000";
DescribeVideoAuditingJobReq req(bucket_name);
DescribeVideoAuditingJobResp resp;// Add request parameters as detailed in the API documentation
req.SetJobId("vab1ca9fc8a3ed11ea834c525400863904");// Call the API to get the job response object©2013-2022 Tencent Cloud. All rights reserved.

Page 313 of 1869

Cloud Infinite

CosResult result = cos.DescribeVideoAuditingJob(req, &resp);
if (result.IsSucc()) {// If the moderation job is queried successfully, you can call the member funct} else {// If the moderation job failed to be queried, you can call the member function}

Parameter description
Parameter
req

resp

Description
DescribeVideoAuditingJob operation
requestDescribeVideoAuditingJob operation
response

Type

Required

DescribeVideoAuditingJobReq

Yes

DescribeVideoAuditingJobResp

Yes

DescribeVideoAuditingJobReq provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 314 of 1869

Cloud Infinite// Set the bucket for performing the operation
void SetBucketName(const std::string& bucket_name);// Set the ID of the moderation job to be queried
void SetJobId(const std::string& job_id);
DescribeVideoAuditingJobResp provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 315 of 1869

Cloud Infinite// Get the job details returned by the API request
VideoAuditingJobsDetail GetJobsDetail();// Get the `RequestId` returned by the API
std::string GetRequestId();

Response description
Success: The moderation job result in the XML content returned by the API will be parsed into theVideoAuditingJobsDetail structure. For specific response parameters, see Submitting Video Moderation©2013-2022 Tencent Cloud. All rights reserved.

Page 316 of 1869

Cloud Infinite

Job.
Failure: If an error (for example, the bucket does not exist) occurs, the error message will be parsed into the
CosResult structure. For more information, see Troubleshooting.

©2013-2022 Tencent Cloud. All rights reserved.

Page 317 of 1869

Cloud Infinite

Audio Moderation：

Last updated 2024-02-29 16:13:43

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for audio moderation.
API

Description

Submitting audio moderation job

Submits audio moderation job.

Querying audio moderation job result

Queries the result of specified audio moderation job.

Submitting Audio Moderation Job
Feature description
This API is used to submit an audio moderation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 318 of 1869

Cloud Infinite

CosResult CosAPI::CreateAudioAuditingJob(const CreateAudioAuditingJobReq& req, Crea

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 319 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
std::string bucket_name = "examplebucket-1250000000";
std::string object_name = "test.mp3";
CreateAudioAuditingJobReq req(bucket_name);
CreateAudioAuditingJobResp resp;// Add request parameters as detailed in the API documentation
req.SetObject(object_name);
req.SetBizType("b81d45f94b91a683255e9a9506f45a11");©2013-2022 Tencent Cloud. All rights reserved.

Page 320 of 1869

Cloud Infinite// req.SetDetectType("Porn,Ads");// Call the API to get the job response object
CosResult result = cos.CreateAudioAuditingJob(req, &resp);
if (result.IsSucc()) {// If the moderation job is created successfully, you can call the member funct} else {// If the moderation job failed to be created, you can call the member function}

Parameter description
Parameter

Description

Type

RequiredreqCreateAudioAuditing operation request

CreateAudioAuditingJobReq

Yes

resp

CreateAudioAuditing operation response

CreateAudioAuditingJobResp

Yes

CreateAudioAuditingJobReq provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 321 of 1869

Cloud Infinite// Set the bucket for performing the operation
void SetBucketName(const std::string& bucket_name);// Set the input audio to be moderated
void SetInput(const AuditingInput& input);// Set moderation configuration rules
void SetConf(const Conf& conf);// conf// Unique identifier of the moderation policy. You can configure the scenes you wan// You can get `BizType` in the console. If `BizType` is specified, the moderation
void SetBizType(const std::string& biz_type);©2013-2022 Tencent Cloud. All rights reserved.

Page 322 of 1869

Cloud Infinite// The scene to be moderated, such as `Porn` (pornography) and `Ads` (advertising).
void SetDetectType(const std::string& detect_type);// Callback address, which must start with `http://` or `https://`.
void SetCallBack(const std::string& callback);// Structure of the callback content. Valid values: `Simple` (the callback content
void SetCallBackVersion(const std::string& callback_version);// input// Name of the audio file stored in the COS bucket; for example, if the file is `auvoid SetObject(const std::string& object);// Full URL of the audio file, such as `http://examplebucket-1250000000.cos.ap-shan
void SetUrl(const std::string& url);// This field will return the original content in the moderation result, which canvoid SetDataId(const std::string& data_id);// Business field.
void SetUserInfo(const UserInfo& user_info);
CreateAudioAuditingJobResp provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 323 of 1869

Cloud Infinite// Get the job details returned by the API request
AudioAuditingJobsDetail GetJobsDetail();// Get the `RequestId` returned by the API
std::string GetRequestId();

Response description
Success: The moderation job result in the XML content returned by the API will be parsed into the
AudioAuditingJobsDetail structure. For specific response parameters, see Submitting Audio Moderation©2013-2022 Tencent Cloud. All rights reserved.

Page 324 of 1869

Cloud Infinite

Job.
Failure: If an error (for example, the bucket does not exist) occurs, the error message will be parsed into the
CosResult structure. For more information, see Troubleshooting.

Querying Audio Moderation Job Result
Feature description
This API is used to query the status and result of an audio moderation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 325 of 1869

Cloud Infinite

CosResult DescribeAudioAuditingJob(const DescribeAudioAuditingJobReq& req, Describe

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 326 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
std::string bucket_name = "examplebucket-1250000000";
DescribeAudioAuditingJobReq req(bucket_name);
DescribeAudioAuditingJobResp resp;// Add request parameters as detailed in the API documentation
req.SetJobId("aab1ca9fc8a3ed11ea834c525400863904");// Call the API to get the job response object©2013-2022 Tencent Cloud. All rights reserved.

Page 327 of 1869

Cloud Infinite

CosResult result = cos.DescribeAudioAuditingJob(req, &resp);
if (result.IsSucc()) {// If the moderation job is queried successfully, you can call the member funct} else {// If the moderation job failed to be queried, you can call the member function}

Parameter description
Parameter
req

resp

Description
DescribeAudioAuditingJob operation
requestDescribeAudioAuditingJob operation
response

Type

Required

DescribeAudioAuditingJobReq

Yes

DescribeAudioAuditingJobResp

Yes

DescribeAudioAuditingJobReq provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 328 of 1869

Cloud Infinite// Set the bucket for performing the operation
void SetBucketName(const std::string& bucket_name);// Set the ID of the moderation job to be queried
void SetJobId(const std::string& job_id);
DescribeAudioAuditingJobResp provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 329 of 1869

Cloud Infinite// Get the job details returned by the API request
AudioAuditingJobsDetail GetJobsDetail();// Get the `RequestId` returned by the API
std::string GetRequestId();

Response description
Success: The moderation job result in the XML content returned by the API will be parsed into the
AudioAuditingJobsDetail structure. For specific response parameters, see Querying Audio Moderation Job©2013-2022 Tencent Cloud. All rights reserved.

Page 330 of 1869

Cloud Infinite

Result.
Failure: If an error (for example, the bucket does not exist) occurs, the error message will be parsed into the
CosResult structure. For more information, see Troubleshooting.

©2013-2022 Tencent Cloud. All rights reserved.

Page 331 of 1869

Cloud Infinite

Text Moderation：

Last updated 2024-02-29 16:13:43

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for text moderation.
API

Description

Submitting text moderation job

Submits text moderation job.

Querying text moderation job result

Queries the result of specified text moderation job.

Submitting Text Moderation Job
Feature description
This API is used to submit a text moderation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 332 of 1869

Cloud Infinite

CosResult CosAPI::CreateTextAuditingJob(const CreateTextAuditingJobReq& req, Create

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 333 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
std::string bucket_name = "examplebucket-1250000000";
std::string object_name = "test.txt";
CreateTextAuditingJobReq req(bucket_name);
CreateTextAuditingJobResp resp;// Add request parameters as detailed in the API documentation
req.SetObject(object_name);
req.SetBizType("b81d45f94b91a683255e9a9506f45a11");©2013-2022 Tencent Cloud. All rights reserved.

Page 334 of 1869

Cloud Infinite// req.SetDetectType("Porn,Ads");// Call the API to get the job response object
CosResult result = cos.CreateTextAuditingJob(req, &resp);
if (result.IsSucc()) {// If the moderation job is created successfully, you can call the member funct} else {// If the moderation job failed to be created, you can call the member function}

Parameter description
Parameter

Description

Type

RequiredreqCreateTextAuditing operation request

CreateTextAuditingJobReq

Yes

resp

CreateTextAuditing operation response

CreateTextAuditingJobResp

Yes

CreateTextAuditingJobReq provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 335 of 1869

Cloud Infinite// Set the bucket for performing the operation
void SetBucketName(const std::string& bucket_name);// Set the input video to be moderated
void SetInput(const AuditingInput& input);// Set moderation configuration rules
void SetConf(const Conf& conf);// conf// Unique identifier of the moderation policy. You can configure the scenes you wan// You can get `BizType` in the console. If `BizType` is specified, the moderation
void SetBizType(const std::string& biz_type);©2013-2022 Tencent Cloud. All rights reserved.

Page 336 of 1869

Cloud Infinite// The scene to be moderated, such as `Porn` (pornography) and `Ads` (advertising).
void SetDetectType(const std::string& detect_type);// Callback address, which must start with `http://` or `https://`.
void SetCallBack(const std::string& callback);// Structure of the callback content. Valid values: `Simple` (the callback content
void SetCallBackVersion(const std::string& callback_version);// input// Name of the text file stored in the current COS bucket; for example, if the filevoid SetObject(const std::string& object);// Full URL of the text file, such as `https://www.test.com/test.txt`.
void SetUrl(const std::string& url);// This field will return the original content in the moderation result, which canvoid SetDataId(const std::string& data_id);// Business field.
void SetUserInfo(const UserInfo& user_info);// When the input content is plain text, it needs to be Base64-encoded first. The lvoid SetContent(const std::string& content) { m_input.SetContent(content); }CreateTextAuditingJobResp provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 337 of 1869

Cloud Infinite// Get the job details returned by the API request
TextAuditingJobsDetail GetJobsDetail();// Get the `RequestId` returned by the API
std::string GetRequestId();

Response description
Success: The moderation job result in the XML content returned by the API will be parsed into the
TextAuditingJobsDetail structure. For specific response parameters, see Submitting Text Moderation Job.

©2013-2022 Tencent Cloud. All rights reserved.

Page 338 of 1869

Cloud Infinite

Failure: If an error (for example, the bucket does not exist) occurs, the error message will be parsed into the
CosResult structure. For more information, see Troubleshooting.

Querying Text Moderation Job Result
Feature description
This API is used to query the status and result of a text moderation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 339 of 1869

Cloud Infinite

CosResult DescribeTextAuditingJob(const DescribeTextAuditingJobReq& req, DescribeTe

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 340 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
std::string bucket_name = "examplebucket-1250000000";
DescribeTextAuditingJobReq req(bucket_name);
DescribeTextAuditingJobResp resp;// Add request parameters as detailed in the API documentation
req.SetJobId("aab1ca9fc8a3ed11ea834c525400863904");// Call the API to get the job response object©2013-2022 Tencent Cloud. All rights reserved.

Page 341 of 1869

Cloud Infinite

CosResult result = cos.DescribeTextAuditingJob(req, &resp);
if (result.IsSucc()) {// If the moderation job is queried successfully, you can call the member funct} else {// If the moderation job failed to be queried, you can call the member function}

Parameter description
Parameter
req

resp

Description
DescribeTextAuditingJob operation
requestDescribeTextAuditingJob operation
response

Type

Required

DescribeTextAuditingJobReq

Yes

DescribeTextAuditingJobResp

Yes

DescribeTextAuditingJobReq provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 342 of 1869

Cloud Infinite// Set the bucket for performing the operation
void SetBucketName(const std::string& bucket_name);// Set the ID of the moderation job to be queried
void SetJobId(const std::string& job_id);
DescribeTextAuditingJobResp provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 343 of 1869

Cloud Infinite// Get the job details returned by the API request
TextAuditingJobsDetail GetJobsDetail();// Get the `RequestId` returned by the API
std::string GetRequestId();

Response description
Success: The moderation job result in the XML content returned by the API will be parsed into the
TextAuditingJobsDetail structure. For specific response parameters, see Querying Text Moderation Job©2013-2022 Tencent Cloud. All rights reserved.

Page 344 of 1869

Cloud Infinite

Result.
Failure: If an error (for example, the bucket does not exist) occurs, the error message will be parsed into the
CosResult structure. For more information, see Troubleshooting.

©2013-2022 Tencent Cloud. All rights reserved.

Page 345 of 1869

Cloud Infinite

File Moderation：

Last updated 2024-02-29 16:13:43

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for file moderation.
API

Description

Submitting file moderation job

Submits file moderation job.

Querying file moderation job result

Queries the result of specified file moderation job.

Submitting File Moderation Job
Feature description
This API is used to submit a file moderation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 346 of 1869

Cloud Infinite

CosResult CosAPI::CreateDocumentAuditingJob(const CreateDocumentAuditingJobReq& req

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 347 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
std::string bucket_name = "examplebucket-1250000000";
std::string object_name = "test.docx";
CreateDocumentAuditingJobReq req(bucket_name);
CreateDocumentAuditingJobResp resp;// Add request parameters as detailed in the API documentation
req.SetObject(object_name);
req.SetType("docx");©2013-2022 Tencent Cloud. All rights reserved.

Page 348 of 1869

Cloud Infinite

req.SetBizType("b81d45f94b91a683255e9a9506f45a11");// req.SetDetectType("Porn,Ads");// Call the API to get the job response object
CosResult result = cos.CreateDocumentAuditingJob(req, &resp);
if (result.IsSucc()) {// If the moderation job is created successfully, you can call the member funct} else {// If the moderation job failed to be created, you can call the member function}

Parameter description
Parameter
req

resp

Description
CreateDocumentAuditing operation
requestCreateDocumentAuditing operation
response

Type

RequiredCreateDocumentAuditingJobReq

Yes

CreateDocumentAuditingJobResp

Yes

CreateDocumentAuditingJobReq provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 349 of 1869

Cloud Infinite// Set the bucket for performing the operation
void SetBucketName(const std::string& bucket_name);// Set the input video to be moderated
void SetInput(const AuditingInput& input);// Set moderation configuration rules
void SetConf(const Conf& conf);// conf// Unique identifier of the moderation policy. You can configure the scenes you wan// You can get `BizType` in the console. If `BizType` is specified, the moderation
void SetBizType(const std::string& biz_type);©2013-2022 Tencent Cloud. All rights reserved.

Page 350 of 1869

Cloud Infinite// The scene to be moderated, such as `Porn` (pornography) and `Ads` (advertising).
void SetDetectType(const std::string& detect_type);// Callback address, which must start with `http://` or `https://`.
void SetCallBack(const std::string& callback);// input// Name of the file stored in the COS bucket; for example, if the file is `test.doc
void SetObject(const std::string& object);// Full URL of the file, such as `http://www.example.com/doctest.doc`. Either `Obje
void SetUrl(const std::string& url);// This field will return the original content in the moderation result, which canvoid SetDataId(const std::string& data_id);// Business field.
void SetUserInfo(const UserInfo& user_info);// File type. If this parameter is not specified, the file extension will be used avoid SetType(const std::string& type);

CreateDocumentAuditingJobResp provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 351 of 1869

Cloud Infinite// Get the job details returned by the API request
DocumentAuditingJobsDetail GetJobsDetail();// Get the `RequestId` returned by the API
std::string GetRequestId();

Response description
Success: The moderation job result in the XML content returned by the API will be parsed into theDocumentAuditingJobsDetail structure. For specific response parameters, see Submitting File Moderation©2013-2022 Tencent Cloud. All rights reserved.

Page 352 of 1869

Cloud Infinite

Job.
Failure: If an error (for example, the bucket does not exist) occurs, the error message will be parsed into the
CosResult structure. For more information, see Troubleshooting.

Querying File Moderation Job Result
Feature description
This API is used to query the status and result of a file moderation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 353 of 1869

Cloud Infinite

CosResult DescribeDocumentAuditingJob(const DescribeDocumentAuditingJobReq& req, De

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 354 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
std::string bucket_name = "examplebucket-1250000000";
DescribeDocumentAuditingJobReq req(bucket_name);
DescribeDocumentAuditingJobResp resp;// Add request parameters as detailed in the API documentation
req.SetJobId("stb1ca9fc8a34c525400863904****");// Call the API to get the job response object©2013-2022 Tencent Cloud. All rights reserved.

Page 355 of 1869

Cloud Infinite

CosResult result = cos.DescribeDocumentAuditingJob(req, &resp);
if (result.IsSucc()) {// If the moderation job is queried successfully, you can call the member funct} else {// If the moderation job failed to be queried, you can call the member function}

Parameter description
Parameter
req

resp

Description
DescribeDocumentAuditingJob
operation request
DescribeDocumentAuditingJob
operation response

Type

Required

DescribeDocumentAuditingJobReq

Yes

DescribeDocumentAuditingJobResp

Yes

DescribeDocumentAuditingJobReq provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 356 of 1869

Cloud Infinite// Set the bucket for performing the operation
void SetBucketName(const std::string& bucket_name);// Set the ID of the moderation job to be queried
void SetJobId(const std::string& job_id);
DescribeDocumentAuditingJobResp provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 357 of 1869

Cloud Infinite// Get the job details returned by the API request
DocumentAuditingJobsDetail GetJobsDetail();// Get the `RequestId` returned by the API
std::string GetRequestId();

Response description
Success: The moderation job result in the XML content returned by the API will be parsed into theDocumentAuditingJobsDetail structure. For specific response parameters, see Querying File Moderation©2013-2022 Tencent Cloud. All rights reserved.

Page 358 of 1869

Cloud Infinite

Job Result.
Failure: If an error (for example, the bucket does not exist) occurs, the error message will be parsed into the
CosResult structure. For more information, see Troubleshooting.

©2013-2022 Tencent Cloud. All rights reserved.

Page 359 of 1869

Cloud Infinite

Webpage Moderation：

Last updated 2024-02-29 16:13:43

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for webpage moderation.
API

Description

Submitting webpage moderation job

Submits webpage moderation job.

Querying webpage moderation job result

Queries the result of specified webpage moderation job.

Submitting Webpage Moderation Job
Feature description
This API is used to submit a webpage moderation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 360 of 1869

Cloud Infinite

CosResult CosAPI::CreateWebPageAuditingJob(const CreateWebPageAuditingJobReq& req,

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 361 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
std::string bucket_name = "examplebucket-1250000000";
std::string url = "http://test.com";CreateWebPageAuditingJobReq req(bucket_name);
CreateWebPageAuditingJobResp resp;// Add request parameters as detailed in the API documentation
req.SetUrl(url);
req.SetDetectType("Porn,Ads");©2013-2022 Tencent Cloud. All rights reserved.

Page 362 of 1869

Cloud Infinite// Call the API to get the job response object
CosResult result = cos.CreateWebPageAuditingJob(req, &resp);
if (result.IsSucc()) {// If the moderation job is created successfully, you can call the member funct} else {// If the moderation job failed to be created, you can call the member function}

Parameter description
Parameter
req

resp

Description
CreateWebPageAuditing operation
requestCreateWebPageAuditing operation
response

Type

RequiredCreateWebPageAuditingJobReq

Yes

CreateWebPageAuditingJobResp

Yes

CreateWebPageAuditingJobReq provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 363 of 1869

Cloud Infinite// Set the bucket for performing the operation
void SetBucketName(const std::string& bucket_name);// Set the input video to be moderated
void SetInput(const AuditingInput& input);// Set moderation configuration rules
void SetConf(const Conf& conf);// conf// The scene to be moderated, such as `Porn` (pornography) and `Ads` (advertising).
void SetDetectType(const std::string& detect_type);// Callback address, which must start with `http://` or `https://`.

©2013-2022 Tencent Cloud. All rights reserved.

Page 364 of 1869

Cloud Infinite

void SetCallBack(const std::string& callback);// Specify whether to highlight the non-compliant text on the webpage. When the res
void SetReturnHighligthHtml(const bool return_highlight_html);// input// Full URL of the webpage, such as `http://www.test.com`.
void SetUrl(const std::string& url);// This field will return the original content in the moderation result, which canvoid SetDataId(const std::string& data_id);// Business field.
void SetUserInfo(const UserInfo& user_info);
CreateWebPageAuditingJobResp provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 365 of 1869

Cloud Infinite// Get the job details returned by the API request
WebPageAuditingJobsDetail GetJobsDetail();// Get the `RequestId` returned by the API
std::string GetRequestId();

Response description
Success: The moderation job result in the XML content returned by the API will be parsed into the
WebPageAuditingJobsDetail structure. For specific response parameters, see Submitting Webpage©2013-2022 Tencent Cloud. All rights reserved.

Page 366 of 1869

Cloud Infinite

Moderation Job.
Failure: If an error (for example, the bucket does not exist) occurs, the error message will be parsed into the
CosResult structure. For more information, see Troubleshooting.

Querying Webpage Moderation Job Result
Feature description
This API is used to query the status and result of a webpage moderation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 367 of 1869

Cloud Infinite

CosResult DescribeWebPageAuditingJob(const DescribeWebPageAuditingJobReq& req, Desc

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 368 of 1869

Cloud Infinite

qcloud_cos::CosConfig config("./config.json");qcloud_cos::CosAPI cos(config);
std::string bucket_name = "examplebucket-1250000000";
DescribeWebPageAuditingJobReq req(bucket_name);
DescribeWebPageAuditingJobResp resp;// Add request parameters as detailed in the API documentation
req.SetJobId("aab1ca9fc8a3ed11ea834c525400863904");// Call the API to get the job response object©2013-2022 Tencent Cloud. All rights reserved.

Page 369 of 1869

Cloud Infinite

CosResult result = cos.DescribeWebPageAuditingJob(req, &resp);
if (result.IsSucc()) {// If the moderation job is queried successfully, you can call the member funct} else {// If the moderation job failed to be queried, you can call the member function}

Parameter description
Parameter
req

resp

Description
DescribeWebPageAuditingJob
operation request
DescribeWebPageAuditingJob
operation response

Type

Required

DescribeWebPageAuditingJobReq

Yes

DescribeWebPageAuditingJobResp

Yes

DescribeWebPageAuditingJobReq provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 370 of 1869

Cloud Infinite// Set the bucket for performing the operation
void SetBucketName(const std::string& bucket_name);// Set the ID of the moderation job to be queried
void SetJobId(const std::string& job_id);
DescribeWebPageAuditingJobResp provides the following member functions:©2013-2022 Tencent Cloud. All rights reserved.

Page 371 of 1869

Cloud Infinite// Get the job details returned by the API request
WebPageAuditingJobsDetail GetJobsDetail();// Get the `RequestId` returned by the API
std::string GetRequestId();

Response description
Success: The moderation job result in the XML content returned by the API will be parsed into the
WebPageAuditingJobsDetail structure. For specific response parameters, see Querying Webpage©2013-2022 Tencent Cloud. All rights reserved.

Page 372 of 1869

Cloud Infinite

Moderation Job Result.
Failure: If an error (for example, the bucket does not exist) occurs, the error message will be parsed into the
CosResult structure. For more information, see Troubleshooting.

©2013-2022 Tencent Cloud. All rights reserved.

Page 373 of 1869

Cloud Infinite.NET(C#) SDK
Getting Started：

Last updated 2024-02-29 16:52:32

Resources
Download the XML .NET SDK source code here.
Download XML .NET SDK here.
Find the complete code here.
For the SDK changelog, see Changelog.
For SDK FAQs, see .NET (C#) SDK FAQs.
Note:
If you encounter errors such as non-existent functions or methods when using the SDK, you can update the SDK to
the latest version and try again.

Step 1. Integrate the SDK
Environmental dependencies
The .NET SDK is developed based on .NET Standard 2.0.
Windows: Install .NET Core 2.0 or above or .NET Framework 2.0 or above.
For Linux/Mac users: Install .NET Core 2.0 or above.
Installing the SDK
You can install the SDK using NuGet by adding the following to the csproj file in your project:©2013-2022 Tencent Cloud. All rights reserved.

Page 374 of 1869

Cloud Infinite<PackageReference Include="Tencent.QCloud.Cos.Sdk" Version="5.4.*" />If .NET CLI is used instead, run the following command:©2013-2022 Tencent Cloud. All rights reserved.

Page 375 of 1869

Cloud Infinite

dotnet add package Tencent.QCloud.Cos.Sdk
If you develop for the target framework .Net Framework 4.0 or below, please download Releases and use COSXMLCompatible.dll .
In your Visual Studio project, click Project > Add Reference > Browse > COSXML-Compatible.dll to add the.NET(C#) SDK.
Note:
The compatible package does not support features such as advanced upload and download. For details, see
Backward Compatibility.

©2013-2022 Tencent Cloud. All rights reserved.

Page 376 of 1869

Cloud Infinite

Step 2. Initialize COS Services
Caution:We recommend you use a temporary key as instructed in Generating and Using Temporary Keys to call the SDK for
security purposes. When you apply for a temporary key, follow the Notes on Principle of Least Privilege to avoid
leaking resources besides your buckets and objects.
If you must use a permanent key, we recommend you follow the Notes on Principle of Least Privilege to limit the scopeof permission on the permanent key.
The section below describes how to perform basic COS operations with the .NET SDK, such as initializing a client,creating a bucket, querying a bucket list, uploading an object, querying an object list, downloading an object, anddeleting an object.
Note:
For the definition of terms such as SecretId, SecretKey, and Bucket, see COS Glossary.
Namespaces commonly used in this SDK include:©2013-2022 Tencent Cloud. All rights reserved.

Page 377 of 1869

Cloud Infinite

using COSXML;
using COSXML.Auth;using COSXML.Model.Object;using COSXML.Model.Bucket;
using COSXML.CosException;
Before making any COS requests, always instantiate the following 3 objects: CosXmlConfig ,QCloudCredentialProvider , and CosXmlServer .
CosXmlConfig provides an API to configure SDK.
QCloudCredentialProvider provides an API to set the key information.

©2013-2022 Tencent Cloud. All rights reserved.

Page 378 of 1869

Cloud Infinite

CosXmlServer provides APIs to perform operations on COS API services.
Note:
The initialization sample below uses a temporary key. For more information about how to generate and use atemporary key, see Generating and Using Temporary Keys.

1. Initialize a COS service// Initialize CosXmlConfig.
string appid = "1250000000";// Set the APPID of your Tencent Cloud account.
string region = "COS_REGION"; // Set the default bucket region.

©2013-2022 Tencent Cloud. All rights reserved.

Page 379 of 1869

Cloud Infinite

CosXmlConfig config = new CosXmlConfig.Builder().IsHttps(true) // Set HTTPS as default request method.
.SetRegion(region) // Set the default bucket region.
.SetDebugLog(true) // Display logs.
.Build(); // Create a CosXmlConfig object.

2. Provide access credentials
The SDK supports three types of access credentials: updated temporary keys, unchanging temporary keys, andpermanent keys.
Type 1: updated temporary key
Since temporary keys are short term, you can obtain new ones using the following method:©2013-2022 Tencent Cloud. All rights reserved.

Page 380 of 1869

Cloud Infinite

public class CustomQCloudCredentialProvider : DefaultSessionQCloudCredentialProvide{// Even if you do not already have a current temporary key, you can still use thi
public CustomQCloudCredentialProvider(): base(null, null, 0L, null) {;}public override void Refresh(){//... First, request a temporary key from Tencent Cloud.

©2013-2022 Tencent Cloud. All rights reserved.

Page 381 of 1869

Cloud Infinite

string tmpSecretId = "SECRET_ID"; // SecretId of a temporary key. For more info
string tmpSecretKey = "SECRET_KEY"; // SecretKey of a temporary key. For more istring tmpToken = "COS_TOKEN"; // Token of a temporary key. For more informatio
long tmpStartTime = 1546860702;// Start time in seconds of the temporary key’s
long tmpExpireTime = 1546862502;// End time in seconds of the temporary key’s v// Call the API to update the key
SetQCloudCredential(tmpSecretId, tmpSecretKey,
String.Format("{0};{1}", tmpStartTime, tmpExpiredTime), tmpToken);}}
QCloudCredentialProvider cosCredentialProvider = new CustomQCloudCredentialProvider
Type 2: unchanging temporary key (not recommended)
Caution:This method is not recommended as a request may fail if the temporary key has expired at the time of request.

©2013-2022 Tencent Cloud. All rights reserved.

Page 382 of 1869

Cloud Infinite

string tmpSecretId = "SECRET_ID"; // “SecretId of the temporary key”;
string tmpSecretKey = "SECRET_KEY"; // “SecretKey of the temporary key”;
string tmpToken = "COS_TOKEN"; // “Token of the temporary key”;
long tmpExpireTime = 1546862502;// End time in seconds of the temporary key’s valid
QCloudCredentialProvider cosCredentialProvider = new DefaultSessionQCloudCredential
tmpSecretId, tmpSecretKey, tmpExpireTime, tmpToken);Type 3: permanent key (not recommended)©2013-2022 Tencent Cloud. All rights reserved.

Page 383 of 1869

Cloud Infinite

string secretId = Environment.GetEnvironmentVariable("SECRET_ID"); // User `SecretI
string secretKey = Environment.GetEnvironmentVariable("SECRET_KEY"); // User `Secrelong durationSecond = 600;// Validity period of each request signature in
QCloudCredentialProvider cosCredentialProvider = new DefaultQCloudCredentialProvide
secretId, secretKey, durationSecond);

3. Initialize CosXmlServer
Use CosXmlConfig and QCloudCredentialProvider to initialize the CosXmlServer service class.
We recommend you use the service class as a singleton in your project.

©2013-2022 Tencent Cloud. All rights reserved.

Page 384 of 1869

Cloud Infinite

CosXml cosXml = new CosXmlServer(config, cosCredentialProvider);Step 3. Access COS
Creating a bucket©2013-2022 Tencent Cloud. All rights reserved.

Page 385 of 1869

Cloud Infinite

try{
String bucket = "examplebucket-1250000000"; // Format: BucketName-APPID
PutBucketRequest request = new PutBucketRequest(bucket);// Execute the request
PutBucketResult result = cosXml.PutBucket(request);// Request succeeded
Console.WriteLine(result.GetResultInfo());}
catch (COSXML.CosException.CosClientException clientEx){©2013-2022 Tencent Cloud. All rights reserved.

Page 386 of 1869

Cloud Infinite// Request failed
Console.WriteLine("CosClientException: " + clientEx);}
catch (COSXML.CosException.CosServerException serverEx){// Request failed
Console.WriteLine("CosServerException: " + serverEx.GetInfo());}

Querying the bucket list

©2013-2022 Tencent Cloud. All rights reserved.

Page 387 of 1869

Cloud Infinite

try{
GetServiceRequest request = new GetServiceRequest();// Execute the request
GetServiceResult result = cosXml.GetService(request);// Get the list of all buckets.
List<ListAllMyBuckets.Bucket> allBuckets = result.listAllMyBuckets.buckets;}
catch (COSXML.CosException.CosClientException clientEx){// Request failed
Console.WriteLine("CosClientException: " + clientEx);}
catch (COSXML.CosException.CosServerException serverEx){// Request failed
Console.WriteLine("CosServerException: " + serverEx.GetInfo());}

Uploading an object©2013-2022 Tencent Cloud. All rights reserved.

Page 388 of 1869

Cloud Infinite// Initialize TransferConfig
TransferConfig transferConfig = new TransferConfig();// Initialize TransferManager
TransferManager transferManager = new TransferManager(cosXml, transferConfig);
String bucket = "examplebucket-1250000000"; // Bucket name in the format of BucketN
String cosPath = "exampleobject"; // The location identifier of the object in the bString srcPath = @"temp-source-file";// Absolute path to the local file// Upload an object©2013-2022 Tencent Cloud. All rights reserved.

Page 389 of 1869

Cloud Infinite

COSXMLUploadTask uploadTask = new COSXMLUploadTask(bucket, cosPath);
uploadTask.SetSrcPath(srcPath);
uploadTask.progressCallback = delegate (long completed, long total){
Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / to};try {COSXML.Transfer.COSXMLUploadTask.UploadTaskResult result = await
transferManager.UploadAsync(uploadTask);
Console.WriteLine(result.GetResultInfo());
string eTag = result.eTag;} catch (Exception e){
Console.WriteLine("CosException: " + e);}

Querying objects©2013-2022 Tencent Cloud. All rights reserved.

Page 390 of 1869

Cloud Infinite

try{
String bucket = "examplebucket-1250000000"; // Format: BucketName-APPID
GetBucketRequest request = new GetBucketRequest(bucket);// Execute the request
GetBucketResult result = cosXml.GetBucket(request);// Bucket information
ListBucket info = result.listBucket;
if (info.isTruncated) {// The data is truncated, and the next marker of the data is recorded.
this.nextMarker = info.nextMarker;©2013-2022 Tencent Cloud. All rights reserved.

Page 391 of 1869

Cloud Infinite}}
catch (COSXML.CosException.CosClientException clientEx){// Request failed
Console.WriteLine("CosClientException: " + clientEx);}
catch (COSXML.CosException.CosServerException serverEx){// Request failed
Console.WriteLine("CosServerException: " + serverEx.GetInfo());}

Downloading an object©2013-2022 Tencent Cloud. All rights reserved.

Page 392 of 1869

Cloud Infinite// Initialize TransferConfig
TransferConfig transferConfig = new TransferConfig();// Initialize TransferManager
TransferManager transferManager = new TransferManager(cosXml, transferConfig);
String bucket = "examplebucket-1250000000"; // Bucket name in the format of BucketN
String cosPath = "exampleobject"; // The location identifier of the object in the bstring localDir = System.IO.Path.GetTempPath();// Local file directorystring localFileName = "my-local-temp-file"; // Filename of the local file

©2013-2022 Tencent Cloud. All rights reserved.

Page 393 of 1869

Cloud Infinite// Download an object
COSXMLDownloadTask downloadTask = new COSXMLDownloadTask(bucket, cosPath,
localDir, localFileName);
downloadTask.progressCallback = delegate (long completed, long total){
Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / to};try {COSXML.Transfer.COSXMLDownloadTask.DownloadTaskResult result = await
transferManager.DownloadAsync(downloadTask);
Console.WriteLine(result.GetResultInfo());
string eTag = result.eTag;} catch (Exception e){
Console.WriteLine("CosException: " + e);}

Deleting an object©2013-2022 Tencent Cloud. All rights reserved.

Page 394 of 1869

Cloud Infinite

try{
string bucket = "examplebucket-1250000000"; // Bucket name in the format of Bucke
string key = "exampleobject"; // Object key
DeleteObjectRequest request = new DeleteObjectRequest(bucket, key);// Execute the request
DeleteObjectResult result = cosXml.DeleteObject(request);// Request succeeded
Console.WriteLine(result.GetResultInfo());}
catch (COSXML.CosException.CosClientException clientEx)©2013-2022 Tencent Cloud. All rights reserved.

Page 395 of 1869

Cloud Infinite{// Request failed
Console.WriteLine("CosClientException: " + clientEx);}
catch (COSXML.CosException.CosServerException serverEx){// Request failed
Console.WriteLine("CosServerException: " + serverEx.GetInfo());}©2013-2022 Tencent Cloud. All rights reserved.

Page 396 of 1869

Cloud Infinite

Image Processing
Basic Image Processing：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for basic image processing.
Service

Basic image
processing

FeatureDescription

Scaling

Proportional scaling, scaling image to target width and height

Cropping

Regular cropping, cropping and scaling, cropping to circle,
smart face cropping

Rotation

Adaptive rotation, regular rotation

Format conversion

Format conversion, GIF format optimization, progressive
display

Quality change

Quality change for JPG and WebP images

Gaussian blurring

Image blurring

Sharpening

Image sharpening

Watermarking

Image watermark, text watermark

Image informationacquisition

Basic information, EXIF information, average hue

Metadata removal

Including EXIF information

Quick thumbnail

Quick image format conversion, scaling, and cropping fortemplatethumbnail generation

Processing Image During Upload
The following example shows how to automatically process an image when you upload it to COS.
When the image is uploaded successfully, COS will save both the original and the processed images. You can later
obtain the processing results by using a general download request.

©2013-2022 Tencent Cloud. All rights reserved.

Page 397 of 1869

Cloud Infinite

Sample code

PutObjectRequest request = new PutObjectRequest(bucket, key, srcPath);
JObject o = new JObject();// Do not return the input imageo["is_pic_info"] = 0;
JArray rules = new JArray();
JObject rule = new JObject();
rule["bucket"] = bucket;
rule["fileid"] = "desample_photo.jpg";©2013-2022 Tencent Cloud. All rights reserved.

Page 398 of 1869

Cloud Infinite// Processing parameters. For rules, visit https://cloud.tencent.com/document/produ
rule["rule"] = "imageMogr2/thumbnail/400x400";
rules.Add(rule);o["rules"] = rules;
string ruleString = o.ToString(Formatting.None);
request.SetRequestHeader("Pic-Operations", ruleString);// Execute the request
PutObjectResult result = cosXml.PutObject(request);
Note:
For more complete samples, visit GitHub.

Processing In-Cloud Image
The following example shows how to process an image stored in COS and save the processing result to COS.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 399 of 1869

Cloud Infinite

JObject o = new JObject();// Do not return the input imageo["is_pic_info"] = 0;
JArray rules = new JArray();
JObject rule = new JObject();
rule["bucket"] = bucket;
rule["fileid"] = "desample_photo.jpg";// Processing parameters. For rules, visit https://cloud.tencent.com/document/produ
rule["rule"] = "imageMogr2/thumbnail/400x400";
rules.Add(rule);o["rules"] = rules;©2013-2022 Tencent Cloud. All rights reserved.

Page 400 of 1869

Cloud Infinite

string ruleString = o.ToString(Formatting.None);
ImageProcessRequest request = new ImageProcessRequest(bucket, key, ruleString);
ImageProcessResult result = cosXml.ImageProcess(request);
Note:
For more complete samples, visit GitHub.

Processing Image During Download
The following example shows how to process an image stored in COS during download.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 401 of 1869

Cloud Infinite

GetObjectRequest getObjectRequest = new GetObjectRequest(bucket, key, localDir, loc// Processing parameters. This sample converts the image into TPG format. For the r
getObjectRequest.SetQueryParameter("imageMogr2/format/tpg", null);Note:
For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 402 of 1869

Cloud Infinite

Blind Watermark：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for blind watermarking.

SDK API References
For the parameters and method description of all the APIs in the SDK, see the API documentation.

Adding Blind Watermark
Feature description
You can add a blind watermark when uploading or downloading an object.

Sample 1: Adding a blind watermark during upload©2013-2022 Tencent Cloud. All rights reserved.

Page 403 of 1869

Cloud Infinite

PutObjectRequest request = new PutObjectRequest(bucket, key, srcPath);
JObject o = new JObject();// Do not return the input imageo["is_pic_info"] = 0;
JArray rules = new JArray();
JObject rule = new JObject();
rule["bucket"] = bucket;
rule["fileid"] = key;// Processing parameters. For rules, visit https://cloud.tencent.com/document/produ
rule["rule"] = "watermark/3/type/<type>/image/<imageUrl>/text/<text>/level/<level>"©2013-2022 Tencent Cloud. All rights reserved.

Page 404 of 1869

Cloud Infinite

rules.Add(rule);o["rules"] = rules;
string ruleString = o.ToString(Formatting.None);
request.SetRequestHeader("Pic-Operations", ruleString);// Execute the request
PutObjectResult result = cosXml.PutObject(request);
Note:
For more complete samples, visit GitHub.

Sample 2: Adding a blind watermark during download[//]: #".cssg-snippet-download-object-with-watermark"©2013-2022 Tencent Cloud. All rights reserved.

Page 405 of 1869

Cloud Infinite

GetObjectRequest getObjectRequest = new GetObjectRequest(bucket, key, localDir, loc// Processing parameters. For rules, visit https://cloud.tencent.com/document/produ
getObjectRequest.SetQueryParameter("watermark/3/type/<type>/image/<imageUrl>/text/<
GetObjectResult result = cosXml.GetObject(getObjectRequest);
Note:
For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 406 of 1869

Cloud Infinite

Media Processing
Media Bucket APIs：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for media buckets.
API

Operation

Description

DescribeMediaBuckets

Querying media processing activation
statusQueries buckets with media processing
enabledQuerying Media Processing Activation Status
Feature description
This API is used to query buckets with media processing enabled.
Note:
The DescribeMediaBuckets API is supported since v5.4.24. To download the new version of SDK, go to
Releases or see Getting Started.
For the SDK version changelog, see Changelog.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 407 of 1869

Cloud Infinite

using COSXML.Model.CI;
using COSXML.Auth;using System;
using COSXML;
namespace COSSnippet{
public class DescribeMediaBucketModel {private CosXml cosXml;©2013-2022 Tencent Cloud. All rights reserved.

Page 408 of 1869

Cloud Infinite

DescribeMediaBucketModel() {CosXmlConfig config = new CosXmlConfig.Builder().SetRegion("COS_REGION") // Set the default region. For abbreviations of.Build();string secretId = "SECRET_ID";// TencentCloud API `SecretId`. For more istring secretKey = "SECRET_KEY"; // TencentCloud API `SecretKey`. For morelong durationSecond = 600;// Validity period of the request signa
QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCreden
secretKey, durationSecond);
this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);}/// Get the list of buckets with CI enabledpublic void DescribeMediaBucket(){//.cssg-snippet-body-start:[DescribeMediaBucket]
DescribeMediaBucketsRequest request = new DescribeMediaBucketsRequest();// Execute the request
DescribeMediaBucketsResult result = cosXml.DescribeMediaBuckets(request);
Console.WriteLine(result.GetResultInfo());// Traverse the bucket list
for (int i = 0; i < result.mediaBuckets.MediaBucketList.Count; i++){Console.WriteLine(result.mediaBuckets.MediaBucketList[i].BucketId);
Console.WriteLine(result.mediaBuckets.MediaBucketList[i].Region);
Console.WriteLine(result.mediaBuckets.MediaBucketList[i].CreateTime);}//.cssg-snippet-body-end}
static void Main(string[] args){
DescribeMediaBucketModel m = new DescribeMediaBucketModel();/// Get the list of media buckets
m.DescribeMediaBucket();// .cssg-methods-pragma
}
}
}

Note:
For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 409 of 1869

Cloud Infinite

Media Information APIs：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for media information.
API

Operation

Description

GetMediaInfo

Querying file information

Queries media file information

Querying File Information
Feature description
This API is used to query the information of a media file. To use this API, you must enable media processing for the
bucket in the console.
Note:
The GetMediainfo API is supported since v5.4.24. To download the new version of SDK, go to Releases or see
Getting Started.
For the SDK version changelog, see Changelog.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 410 of 1869

Cloud Infinite

using COSXML.Model.CI;
using COSXML.Auth;using System;
using COSXML;
namespace COSSnippet{
public class GetMediaInfoModel {private CosXml cosXml;©2013-2022 Tencent Cloud. All rights reserved.

Page 411 of 1869

Cloud Infinite

GetMediaInfoModel() {CosXmlConfig config = new CosXmlConfig.Builder().SetRegion("COS_REGION") // Set the default region. For abbreviations of.Build();string secretId = "SECRET_ID";// TencentCloud API `SecretId`. For more istring secretKey = "SECRET_KEY"; // TencentCloud API `SecretKey`. For morelong durationSecond = 600;// Validity period of the request signa
QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCreden
secretKey, durationSecond);
this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);}/// Get media file information
public void GetMediaInfo(){//.cssg-snippet-body-start:[GetMediaInfo]// Bucket name in the format of `BucketName-APPID`. You can get the `APPID`
string bucket = "examplebucket-1250000000";
string key = "mediafile"; // Object key of the media file, which should be
GetMediaInfoRequest request = new GetMediaInfoRequest(bucket, key);// Execute the request
GetMediaInfoResult result = cosXml.GetMediaInfo(request);
Console.WriteLine(result.GetResultInfo());// Get video media information
Console.WriteLine(result.mediaInfoResult.MediaInfo.Stream);
Console.WriteLine(result.mediaInfoResult.MediaInfo.Stream.Video);
Console.WriteLine(result.mediaInfoResult.MediaInfo.Stream.Video.Index);
Console.WriteLine(result.mediaInfoResult.MediaInfo.Stream.Video.CodecName);// Get audio information
Console.WriteLine(result.mediaInfoResult.MediaInfo.Stream.Audio);
Console.WriteLine(result.mediaInfoResult.MediaInfo.Stream.Audio.Index);
Console.WriteLine(result.mediaInfoResult.MediaInfo.Stream.Audio.CodecName);
Console.WriteLine(result.mediaInfoResult.MediaInfo.Stream.Audio.CodecLongNa// Get the `Format` field
Console.WriteLine(result.mediaInfoResult.MediaInfo.Format);Console.WriteLine(result.mediaInfoResult.MediaInfo.Format.NumStream);
Console.WriteLine(result.mediaInfoResult.MediaInfo.Format.NumProgram);//.cssg-snippet-body-end}
static void Main(string[] args){
GetMediaInfoModel m = new GetMediaInfoModel();/// Get media file informationm.GetMediaInfo();©2013-2022 Tencent Cloud. All rights reserved.

Page 412 of 1869

Cloud Infinite// .cssg-methods-pragma
}
}
}
Note:
For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 413 of 1869

Cloud Infinite

Media Screenshot APIs：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for media screenshot.
API

Operation

Description

GetSnapshot

Querying screenshot

Query the screenshot of media file at some time point

Querying Screenshot
Feature description
This API is used to query the screenshot of a media file at some time point.
Note:
The GetSnapshot API is supported since v5.4.24. To download the new version of SDK, go to Releases or see
Getting Started.
For the SDK version changelog, see Changelog.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 414 of 1869

Cloud Infinite

using COSXML.Model.CI;
using COSXML.Auth;using System;
using COSXML;
namespace COSSnippet{
public class GetSnapshotModel {private CosXml cosXml;©2013-2022 Tencent Cloud. All rights reserved.

Page 415 of 1869

Cloud Infinite

GetSnapshotModel() {CosXmlConfig config = new CosXmlConfig.Builder().SetRegion("COS_REGION") // Set the default region. For abbreviations of.Build();string secretId = "SECRET_ID";// TencentCloud API `SecretId`. For more istring secretKey = "SECRET_KEY"; // TencentCloud API `SecretKey`. For morelong durationSecond = 600;// Validity period of the request signa
QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCreden
secretKey, durationSecond);
this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);}/// Capture video frames
public void GetSnapshot(){// Bucket name in the format of `BucketName-APPID`. You can get the `APPID`
string bucket = "examplebucket-1250000000";
string key = "video.mp4"; // Object key of the media file, which should befloat time = 1.5F; // Screenshot time point expressed as a floating point n
string destPath = @"temp-source-file"; // The path to save the screenshot f
GetSnapshotRequest request = new GetSnapshotRequest(bucket, key, time, dest// Execute the request
GetSnapshotResult result = cosXml.GetSnapshot(request);
Console.WriteLine(result.GetResultInfo());}
static void Main(string[] args){
GetSnapshotModel m = new GetSnapshotModel();/// Capture video frames
m.GetSnapshot();
}
}
}
Note:
For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 416 of 1869

Cloud Infinite

Content Moderation
Image Moderation：

Last updated 2024-02-29 16:52:32

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for image moderation.
API

Description

Moderating single image

Scans existing data stored in COS for porn, illegal, and advertising images.

Moderating Existing Image
Feature description
The following example shows how to scan existing images stored in COS for porn, illegal, and advertising information.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 417 of 1869

Cloud Infinite

using COSXML.Model.CI;
using COSXML.Auth;using COSXML;
namespace COSSnippet{
public class PictureOperationModel {private CosXml cosXml;
PictureOperationModel() {©2013-2022 Tencent Cloud. All rights reserved.

Page 418 of 1869

Cloud Infinite

CosXmlConfig config = new CosXmlConfig.Builder().SetRegion("COS_REGION") // Set the default region. For abbreviations of.Build();string secretId = "SECRET_ID";// SecretId of the TencentCloud API. For mstring secretKey = "SECRET_KEY"; // SecretKey of the TencentCloud API. For
long durationSecond = 600;// Validity period of the request signa
QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCreden
secretKey, durationSecond);
this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);}/// Image moderation
public void SensitiveContentRecognition(){// Bucket name in the format of `BucketName-APPID`. You can get APPID by restring bucket = "examplebucket-1250000000";
string key = "exampleobject"; // Object key//.cssg-snippet-body-start:[sensitive-content-recognition]
SensitiveContentRecognitionRequest request =new SensitiveContentRecognitionRequest(bucket, key, "ads");
SensitiveContentRecognitionResult result = cosXml.SensitiveContentRecogniti}
static void Main(string[] args){
PictureOperationModel m = new PictureOperationModel();/// Image moderation
m.SensitiveContentRecognition();
}
}
}
Note:
For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 419 of 1869

Cloud Infinite

Video Moderation：

Last updated 2024-02-29 16:52:32

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for video moderation.
API

Description

Submitting video moderation job

Submits a video moderation job.

Querying video moderation job result

Queries the result of a specified video moderation job.

Submitting a Video Moderation Job
Feature description
The video moderation feature is async. You can submit a job to moderate your video files, and then use the API for
querying video moderation job result to query the moderation results.
The following example shows how to submit a video moderation job and then query the result by JobId .
Note:
To perform this operation, the bucket should have CI features enabled.
Video moderation APIs are supported starting from v5.4.24. To download the latest SDK, go to Releases or see
Getting Started.
To view the version change log, go to GitHub.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 420 of 1869

Cloud Infinite

using COSXML.Model.CI;
using COSXML.Auth;using System;
using System.Threading;using COSXML;
namespace COSSnippet{
public class SubmitVideoCensorJobModel {private CosXml cosXml;©2013-2022 Tencent Cloud. All rights reserved.

Page 421 of 1869

Cloud Infinite

SubmitVideoCensorJobModel() {CosXmlConfig config = new CosXmlConfig.Builder().SetRegion("COS_REGION") // Set the default region. For abbreviations of.Build();string secretId = "SECRET_ID";// SecretId of the TencentCloud API. For mstring secretKey = "SECRET_KEY"; // SecretKey of the TencentCloud API. For
long durationSecond = 600;// Validity period of the request signa
QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCreden
secretKey, durationSecond);
this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);}/// Submit the video moderation job
public string SubmitVideoCensorJob(){// Bucket name in the format of `BucketName-APPID`. You can get APPID by restring bucket = "examplebucket-1250000000"; // Note: To perform this operat
SubmitVideoCensorJobRequest request = new SubmitVideoCensorJobRequest(buckerequest.SetCensorObject("video.mp4"); // Object key of the media file, whic// The scene to be moderated, such as `Porn` (pornography) and `Ads` (adver
request.SetDetectType("Porn,Ads");// Video image moderation is implemented by taking a certain number of screrequest.SetSnapshotMode("Average"); // Frame capturing mode. Valid values:
request.SetSnapshotCount("100"); // The number of captured frames. Value rarequest.SetSnapshotTimeInterval("1.0"); // Video frame capturing frequency.
// Execute the request
SubmitCensorJobResult result = cosXml.SubmitVideoCensorJob(request);
Console.WriteLine(result.GetResultInfo());
Console.WriteLine(result.censorJobsResponse.JobsDetail.JobId);
Console.WriteLine(result.censorJobsResponse.JobsDetail.State);
Console.WriteLine(result.censorJobsResponse.JobsDetail.CreationTime);
return result.censorJobsResponse.JobsDetail.JobId;}
static void Main(string[] args){
SubmitVideoCensorJobModel m = new SubmitVideoCensorJobModel();/// Submit the moderation job. The `JobId` uniquely identifies the result ostring JobId = m.SubmitVideoCensorJob();/// Print the `JobId`
Console.WriteLine("JobId : " + JobId);}}}©2013-2022 Tencent Cloud. All rights reserved.

Page 422 of 1869

Cloud Infinite

Note:
For more complete samples, visit GitHub.

Querying Video Moderation Job Result
Feature description
This API is used to query the status and result of a video moderation job.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 423 of 1869

Cloud Infinite

using COSXML.Model.CI;
using COSXML.Auth;using System;
using System.Threading;using COSXML;
namespace COSSnippet{
public class SubmitVideoCensorJobModel {private CosXml cosXml;©2013-2022 Tencent Cloud. All rights reserved.

Page 424 of 1869

Cloud Infinite

SubmitVideoCensorJobModel() {CosXmlConfig config = new CosXmlConfig.Builder().SetRegion("COS_REGION") // Set the default region. For abbreviations of.Build();string secretId = "SECRET_ID";// SecretId of the TencentCloud API. For mstring secretKey = "SECRET_KEY"; // SecretKey of the TencentCloud API. For
long durationSecond = 600;// Validity period of the request signa
QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCreden
secretKey, durationSecond);
this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);}/// Query the video moderation job result
public void GetVideoCensorJobResult(string JobId){// Bucket name in the format of `BucketName-APPID`. You can get APPID by restring bucket = "examplebucket-1250000000"; // Note: To perform this operat
GetVideoCensorJobRequest request = new GetVideoCensorJobRequest(bucket, Job// Execute the request
GetVideoCensorJobResult result = cosXml.GetVideoCensorJob(request);
Console.WriteLine(result.GetResultInfo());// Read the moderation result
Console.WriteLine(result.resultStruct.JobsDetail.JobId);
Console.WriteLine(result.resultStruct.JobsDetail.State);
Console.WriteLine(result.resultStruct.JobsDetail.CreationTime);
Console.WriteLine(result.resultStruct.JobsDetail.Object);
Console.WriteLine(result.resultStruct.JobsDetail.SnapshotCount);
Console.WriteLine(result.resultStruct.JobsDetail.Result);
Console.WriteLine(result.resultStruct.JobsDetail.PornInfo.HitFlag);Console.WriteLine(result.resultStruct.JobsDetail.PornInfo.Count);
Console.WriteLine(result.resultStruct.JobsDetail.AdsInfo.HitFlag);Console.WriteLine(result.resultStruct.JobsDetail.AdsInfo.Count);// Moderate video screenshots
for(int i = 0; i < result.resultStruct.JobsDetail.Snapshot.Count; i++){Console.WriteLine(result.resultStruct.JobsDetail.Snapshot[i].Url);
Console.WriteLine(result.resultStruct.JobsDetail.Snapshot[i].Text);
Console.WriteLine(result.resultStruct.JobsDetail.Snapshot[i].SnapshotTi
Console.WriteLine(result.resultStruct.JobsDetail.Snapshot[i].PornInfo.H
Console.WriteLine(result.resultStruct.JobsDetail.Snapshot[i].PornInfo.S©2013-2022 Tencent Cloud. All rights reserved.

Page 425 of 1869

Cloud Infinite

Console.WriteLine(result.resultStruct.JobsDetail.Snapshot[i].PornInfo.L
Console.WriteLine(result.resultStruct.JobsDetail.Snapshot[i].PornInfo.S
Console.WriteLine(result.resultStruct.JobsDetail.Snapshot[i].AdsInfo.Hi
Console.WriteLine(result.resultStruct.JobsDetail.Snapshot[i].AdsInfo.Sc
Console.WriteLine(result.resultStruct.JobsDetail.Snapshot[i].AdsInfo.La
Console.WriteLine(result.resultStruct.JobsDetail.Snapshot[i].AdsInfo.Su}}
static void Main(string[] args){
SubmitVideoCensorJobModel m = new SubmitVideoCensorJobModel();// Enter the `JobId` obtained when you submit the moderation job
string JobId = "xxx";/// Query the moderation job
m.GetVideoCensorJobResult(JobId);
}
}
}

Note:
For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 426 of 1869

Cloud Infinite

Audio Moderation：

Last updated 2024-02-29 16:52:32

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for audio moderation.
API

Description

Submitting audio moderation job

Submits an audio moderation job.

Querying audio moderation job result

Queries the result of a specified audio moderation job.

Submitting an Audio Moderation Job
Feature description
This API is used to submit an audio moderation job. The audio moderation feature is async. You can submit a job tomoderate your audio files, and then use the API for querying audio moderation job result to query the moderation
results.
The following example shows how to submit an audio moderation job and then query the result by JobId .
Note:
To perform this operation, the bucket should have CI features enabled.
Audio moderation APIs are supported starting from v5.4.24. To download the latest SDK, go to Releases or see
Getting Started.
To view the version change log, go to GitHub.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 427 of 1869

Cloud Infinite

using COSXML.Model.CI;
using COSXML.Auth;using System;
using System.Threading;using COSXML;
namespace COSSnippet{
public class SubmitAudioCensorJobModel {private CosXml cosXml;©2013-2022 Tencent Cloud. All rights reserved.

Page 428 of 1869

Cloud Infinite

SubmitAudioCensorJobModel() {CosXmlConfig config = new CosXmlConfig.Builder().SetRegion("COS_REGION") // Set the default region. For abbreviations of.Build();string secretId = "SECRET_ID";// SecretId of the TencentCloud API. For mstring secretKey = "SECRET_KEY"; // SecretKey of the TencentCloud API. For
long durationSecond = 600;// Validity period of the request signa
QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCreden
secretKey, durationSecond);
this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);}/// Submit the audio moderation job
public string SubmitAudioCensorJob(){// Bucket name in the format of `BucketName-APPID`. You can get APPID by restring bucket = "examplebucket-1250000000"; // Note: To perform this operat
SubmitAudioCensorJobRequest request = new SubmitAudioCensorJobRequest(buckerequest.SetCensorObject("audio.mp3"); // Object key of the media file, whic// The scene to be moderated, such as `Porn` (pornography) and `Ads` (adver
request.SetDetectType("Porn,Ads");// Execute the request
SubmitCensorJobResult result = cosXml.SubmitAudioCensorJob(request);
Console.WriteLine(result.GetResultInfo());
Console.WriteLine(result.censorJobsResponse.JobsDetail.JobId);
Console.WriteLine(result.censorJobsResponse.JobsDetail.State);
Console.WriteLine(result.censorJobsResponse.JobsDetail.CreationTime);
return result.censorJobsResponse.JobsDetail.JobId;}
static void Main(string[] args){
SubmitAudioCensorJobModel m = new SubmitAudioCensorJobModel();/// Submit the moderation job
string JobId = m.SubmitAudioCensorJob();/// Print the `JobId` that uniquely identifies this moderation job
Console.WriteLine("JobId : " + JobId);
}
}
}
Note:
For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 429 of 1869

Cloud Infinite

Querying Audio Moderation Job Result
Feature description
This API is used to query the status and result of an audio moderation job.
Sample codeusing COSXML.Model.CI;
using COSXML.Auth;using System;©2013-2022 Tencent Cloud. All rights reserved.

Page 430 of 1869

Cloud Infinite

using System.Threading;using COSXML;
namespace COSSnippet{
public class SubmitAudioCensorJobModel {private CosXml cosXml;
SubmitAudioCensorJobModel() {CosXmlConfig config = new CosXmlConfig.Builder().SetRegion("COS_REGION") // Set the default region. For abbreviations of.Build();string secretId = "SECRET_ID";// SecretId of the TencentCloud API. For mstring secretKey = "SECRET_KEY"; // SecretKey of the TencentCloud API. For
long durationSecond = 600;// Validity period of the request signa
QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCreden
secretKey, durationSecond);
this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);}/// Query the audio moderation job result
public void GetAudioCensorJobResult(string JobId){// Bucket name in the format of `BucketName-APPID`. You can get APPID by restring bucket = "examplebucket-1250000000"; // Note: To perform this operat
GetAudioCensorJobRequest request = new GetAudioCensorJobRequest(bucket, Job// Execute the request
GetAudioCensorJobResult result = cosXml.GetAudioCensorJob(request);
Console.WriteLine(result.GetResultInfo());// Read the moderation result
Console.WriteLine(result.resultStruct.JobsDetail.JobId);
Console.WriteLine(result.resultStruct.JobsDetail.State);
Console.WriteLine(result.resultStruct.JobsDetail.CreationTime);
Console.WriteLine(result.resultStruct.JobsDetail.Object);
Console.WriteLine(result.resultStruct.JobsDetail.Result);
Console.WriteLine(result.resultStruct.JobsDetail.AudioText);
Console.WriteLine(result.resultStruct.JobsDetail.PornInfo.HitFlag);Console.WriteLine(result.resultStruct.JobsDetail.PornInfo.Score);
Console.WriteLine(result.resultStruct.JobsDetail.PornInfo.Label);Console.WriteLine(result.resultStruct.JobsDetail.AdsInfo.HitFlag);Console.WriteLine(result.resultStruct.JobsDetail.AdsInfo.Score);©2013-2022 Tencent Cloud. All rights reserved.

Page 431 of 1869

Cloud Infinite

Console.WriteLine(result.resultStruct.JobsDetail.AdsInfo.Label);// Information of audio sections
for(int i = 0; i < result.resultStruct.JobsDetail.Section.Count; i++){Console.WriteLine(result.resultStruct.JobsDetail.Section[i].Url);
Console.WriteLine(result.resultStruct.JobsDetail.Section[i].OffsetTime)
Console.WriteLine(result.resultStruct.JobsDetail.Section[i].Duration);
Console.WriteLine(result.resultStruct.JobsDetail.Section[i].Text);
Console.WriteLine(result.resultStruct.JobsDetail.Section[i].PornInfo.Hi
Console.WriteLine(result.resultStruct.JobsDetail.Section[i].PornInfo.Sc
Console.WriteLine(result.resultStruct.JobsDetail.Section[i].AdsInfo.Hit
Console.WriteLine(result.resultStruct.JobsDetail.Section[i].AdsInfo.Sco}}
static void Main(string[] args){
SubmitAudioCensorJobModel m = new SubmitAudioCensorJobModel();/// Enter the `JobId` obtained when you submit the moderation job
string JobId = "xxx";/// Query the moderation job result
m.GetAudioCensorJobResult(JobId);
}
}
}
Note:
For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 432 of 1869

Cloud Infinite

File Moderation：

Last updated 2024-02-29 16:52:32

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for file moderation.
API

Description

Submitting file moderation job

Submits a file moderation job.

Querying file moderation job result

Queries the result of a specified file moderation job.

Submitting a File Moderation Job
Feature description
This API is used to submit a file moderation job, which can check your file for sensitive or non-compliant information.
The file moderation feature combines the file preview feature of COS to moderate files by converting them into images
and leveraging image content moderation and OCR capabilities.
The following example shows how to submit a file moderation job and then query the result by JobId .
Note:
To perform this operation, the bucket should have CI features enabled.
File moderation APIs are supported starting from v5.4.24. To download the latest SDK, go to Releases or see Getting
Started.
To view the version change log, go to GitHub.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 433 of 1869

Cloud Infinite

using COSXML.Model.CI;
using COSXML.Auth;using System;
using System.Threading;using COSXML;
namespace COSSnippet{
public class SubmitDocumentCensorJobModel {private CosXml cosXml;©2013-2022 Tencent Cloud. All rights reserved.

Page 434 of 1869

Cloud Infinite

SubmitDocumentCensorJobModel() {CosXmlConfig config = new CosXmlConfig.Builder().SetRegion("COS_REGION") // Set the default region. For abbreviations of.Build();string secretId = "SECRET_ID";// SecretId of the TencentCloud API. For mstring secretKey = "SECRET_KEY"; // SecretKey of the TencentCloud API. For
long durationSecond = 600;// Validity period of the request signa
QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCreden
secretKey, durationSecond);
this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);}/// Submit the file moderation job
public string SubmitDocumentCensorJob(){// Bucket name in the format of `BucketName-APPID`. You can get APPID by restring bucket = "examplebucket-1250000000"; // Note: To perform this operat
SubmitDocumentCensorJobRequest request = new SubmitDocumentCensorJobRequest
request.SetUrl("url"); // URL of the file to be moderated, which should be// The scene to be moderated, such as `Porn` (pornography) and `Ads` (adver
request.SetDetectType("Porn,Ads");// Execute the request
SubmitCensorJobResult result = cosXml.SubmitDocumentCensorJob(request);
Console.WriteLine(result.GetResultInfo());
Console.WriteLine(result.censorJobsResponse.JobsDetail.JobId);
Console.WriteLine(result.censorJobsResponse.JobsDetail.State);
Console.WriteLine(result.censorJobsResponse.JobsDetail.CreationTime);
return result.censorJobsResponse.JobsDetail.JobId;}
static void Main(string[] args){
SubmitDocumentCensorJobModel m = new SubmitDocumentCensorJobModel();/// Submit the moderation job
string JobId = m.SubmitDocumentCensorJob();
}
}
}

Note:
For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 435 of 1869

Cloud Infinite

Querying File Moderation Job
Feature description
This API is used to query the status and result of a file moderation job.
Sample codeusing COSXML.Model.CI;
using COSXML.Auth;using System;©2013-2022 Tencent Cloud. All rights reserved.

Page 436 of 1869

Cloud Infinite

using System.Threading;using COSXML;
namespace COSSnippet{
public class SubmitDocumentCensorJobModel {private CosXml cosXml;
SubmitDocumentCensorJobModel() {CosXmlConfig config = new CosXmlConfig.Builder().SetRegion("COS_REGION") // Set the default region. For abbreviations of.Build();string secretId = "SECRET_ID";// SecretId of the TencentCloud API. For mstring secretKey = "SECRET_KEY"; // SecretKey of the TencentCloud API. For
long durationSecond = 600;// Validity period of the request signa
QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCreden
secretKey, durationSecond);
this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);}/// Query the file moderation job result
public void GetDocumentCensorJobResult(string JobId){// Bucket name in the format of `BucketName-APPID`. You can get APPID by restring bucket = "examplebucket-1250000000"; // Note: To perform this operat
GetDocumentCensorJobRequest request = new GetDocumentCensorJobRequest(bucke// Execute the request
GetDocumentCensorJobResult result = cosXml.GetDocumentCensorJob(request);
Console.WriteLine(result.GetResultInfo());// Read the moderation result
Console.WriteLine(result.resultStruct.JobsDetail.State);
Console.WriteLine(result.resultStruct.JobsDetail.JobId);
Console.WriteLine(result.resultStruct.JobsDetail.Suggestion);
Console.WriteLine(result.resultStruct.JobsDetail.CreationTime);
Console.WriteLine(result.resultStruct.JobsDetail.Url);
Console.WriteLine(result.resultStruct.JobsDetail.PageCount);
Console.WriteLine(result.resultStruct.JobsDetail.Labels);
Console.WriteLine(result.resultStruct.JobsDetail.Labels.PornInfo.HitFlag);Console.WriteLine(result.resultStruct.JobsDetail.Labels.PornInfo.Score);
Console.WriteLine(result.resultStruct.JobsDetail.PageSegment.Results.Url);
Console.WriteLine(result.resultStruct.JobsDetail.PageSegment.Results.Text);
Console.WriteLine(result.resultStruct.JobsDetail.PageSegment.Results.PageNu
Console.WriteLine(result.resultStruct.JobsDetail.PageSegment.Results.PornIn©2013-2022 Tencent Cloud. All rights reserved.

Page 437 of 1869

Cloud Infinite

Console.WriteLine(result.resultStruct.JobsDetail.PageSegment.Results.PornIn
Console.WriteLine(result.resultStruct.JobsDetail.PageSegment.Results.PornIn}
static void Main(string[] args){
SubmitDocumentCensorJobModel m = new SubmitDocumentCensorJobModel();/// Enter the `JobId` that is returned during moderation job submission andstring JobId = "xxx";/// Query the moderation job result
m.GetDocumentCensorJobResult(JobId);
}
}
}

Note:
For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 438 of 1869

Cloud Infinite

Text Moderation：

Last updated 2024-02-29 16:52:32

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for text moderation.
API

Description

Submitting text moderation job

Submits a text moderation job.

Querying text moderation job result

Queries the result of a specified text moderation job.

Submitting a Text Moderation Job
Feature description
This API is used to submit a text moderation job. You can submit a job to moderate your text files, and then use the
API for querying text moderation job result to query the moderation results.
The following example shows how to submit a text moderation job and then query the result by JobId .
Note:
To perform this operation, the bucket should have CI features enabled.
Text moderation APIs are supported starting from v5.4.24. To download the latest SDK, go to Releases or see Getting
Started.
To view the version change log, go to GitHub.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 439 of 1869

Cloud Infinite

using COSXML.Model.CI;
using COSXML.Auth;using System;
using System.Threading;using COSXML;
namespace COSSnippet{
public class SubmitTextCensorJobModel {private CosXml cosXml;©2013-2022 Tencent Cloud. All rights reserved.

Page 440 of 1869

Cloud Infinite

SubmitTextCensorJobModel() {CosXmlConfig config = new CosXmlConfig.Builder().SetRegion("COS_REGION") // Set the default region. For abbreviations of.Build();string secretId = "SECRET_ID";// SecretId of the TencentCloud API. For mstring secretKey = "SECRET_KEY"; // SecretKey of the TencentCloud API. For
long durationSecond = 600;// Validity period of the request signa
QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCreden
secretKey, durationSecond);
this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);}/// Submit the text moderation job
public string SubmitTextCensorJob(){// Bucket name in the format of `BucketName-APPID`. You can get APPID by restring bucket = "examplebucket-1250000000"; // Note: To perform this operat
SubmitTextCensorJobRequest request = new SubmitTextCensorJobRequest(bucket
request.SetCensorObject("text.txt"); // Object key of the media file, which// The scene to be moderated, such as `Porn` (pornography) and `Ads` (adver
request.SetDetectType("Porn,Ads");// Execute the request
SubmitCensorJobResult result = cosXml.SubmitTextCensorJob(request);
Console.WriteLine(result.GetResultInfo());
Console.WriteLine(result.censorJobsResponse.JobsDetail.JobId);
Console.WriteLine(result.censorJobsResponse.JobsDetail.State);
Console.WriteLine(result.censorJobsResponse.JobsDetail.CreationTime);
return result.censorJobsResponse.JobsDetail.JobId;//.cssg-snippet-body-end}
static void Main(string[] args){
SubmitTextCensorJobModel m = new SubmitTextCensorJobModel();/// Submit the moderation job
string JobId = m.SubmitTextCensorJob();/// Print the `JobId` that uniquely identifies this moderation job
Console.WriteLine("JobId : " + JobId);
}
}
}

Note:

©2013-2022 Tencent Cloud. All rights reserved.

Page 441 of 1869

Cloud Infinite

For more complete samples, visit GitHub.

Querying a Text Moderation Job
Feature description
This API is used to query the status and result of a text moderation job.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 442 of 1869

Cloud Infinite

using COSXML.Model.CI;
using COSXML.Auth;using System;
using System.Threading;using COSXML;
namespace COSSnippet{
public class SubmitTextCensorJobModel {private CosXml cosXml;
SubmitTextCensorJobModel() {CosXmlConfig config = new CosXmlConfig.Builder().SetRegion("COS_REGION") // Set the default region. For abbreviations of.Build();string secretId = "SECRET_ID";// SecretId of the TencentCloud API. For mstring secretKey = "SECRET_KEY"; // SecretKey of the TencentCloud API. For
long durationSecond = 600;// Validity period of the request signa
QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCreden
secretKey, durationSecond);
this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);}/// Query the text moderation job result
public void GetTextCensorJobResult(string JobId){// Bucket name in the format of `BucketName-APPID`. You can get APPID by restring bucket = "examplebucket-1250000000"; // Note: To perform this operat
GetTextCensorJobRequest request = new GetTextCensorJobRequest(bucket, JobId// Execute the request
GetTextCensorJobResult result = cosXml.GetTextCensorJob(request);
Console.WriteLine(result.GetResultInfo());// Read the moderation result
Console.WriteLine(result.resultStruct.JobsDetail.JobId);
Console.WriteLine(result.resultStruct.JobsDetail.State);
Console.WriteLine(result.resultStruct.JobsDetail.CreationTime);
Console.WriteLine(result.resultStruct.JobsDetail.Object);
Console.WriteLine(result.resultStruct.JobsDetail.SectionCount);
Console.WriteLine(result.resultStruct.JobsDetail.Result);
Console.WriteLine(result.resultStruct.JobsDetail.PornInfo.HitFlag);Console.WriteLine(result.resultStruct.JobsDetail.PornInfo.Count);©2013-2022 Tencent Cloud. All rights reserved.

Page 443 of 1869

Cloud Infinite

Console.WriteLine(result.resultStruct.JobsDetail.AdsInfo.HitFlag);Console.WriteLine(result.resultStruct.JobsDetail.AdsInfo.Count);// Information of text sections
for(int i = 0; i < result.resultStruct.JobsDetail.Section.Count; i++){Console.WriteLine(result.resultStruct.JobsDetail.Section[i].StartByte);
Console.WriteLine(result.resultStruct.JobsDetail.Section[i].PornInfo.Hi
Console.WriteLine(result.resultStruct.JobsDetail.Section[i].PornInfo.Sc
Console.WriteLine(result.resultStruct.JobsDetail.Section[i].PornInfo.Ke}}
static void Main(string[] args){
SubmitTextCensorJobModel m = new SubmitTextCensorJobModel();// Enter the `JobId` obtained when you submit the text moderation job
string JobId = "xxx";// Query the moderation job result
m.GetTextCensorJobResult(JobId);
}
}
}

Note:
For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 444 of 1869

Cloud Infinite

Go SDK
Getting Started：

Last updated 2024-02-29 16:52:32

Download and Installation
Relevant resources
Download the source code for the COS XML Go SDK here.
Download the demo here.
For more information, see GitHub.
For the complete sample code, see SDK Sample Code.
For the SDK changelog, see Changelog.
For SDK FAQs, see Go SDK.
Note:
If you encounter errors such as non-existent functions or methods when using the SDK, you can update the SDK to
the latest version and try again.
Environmental dependencies
Golang is used to download and install the Go operating environment; it can be downloaded from the Golang official
website.
Installing SDK
Execute the following command to install the COS Go SDK:©2013-2022 Tencent Cloud. All rights reserved.

Page 445 of 1869

Cloud Infinite

go get -u github.com/tencentyun/cos-go-sdk-v5

Getting Started
The section below describes how to use the COS Go SDK to perform basic operations, such as initializing a client,creating a bucket, querying a bucket list, uploading an object, querying an object list, downloading an object, ordeleting an object.

©2013-2022 Tencent Cloud. All rights reserved.

Page 446 of 1869

Cloud Infinite

Initialization
Note:
We recommend you use a sub-account key and environment variables to call the SDK for security purposes. Whenauthorizing a sub-account, follow the Notes on Principle of Least Privilege to avoid leaking resources besides yourbuckets and objects.
If you must use a permanent key, we recommend you follow the Notes on Principle of Least Privilege to limit the scopeof permission on the permanent key.
A COS GO client is generated using the COS domain name.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 447 of 1869

Cloud Infinite

func NewClient(uri *BaseURL, httpClient *http.Client) *Client

Field description©2013-2022 Tencent Cloud. All rights reserved.

Page 448 of 1869

Cloud Infinite// `BaseURL` indicates the base URL required for accessing APIs
type BaseURL struct {// Base URL (excluding `path`) for accessing bucket and object related APIs: ht
BucketURL *url.URL// Base URL (excluding `path`) for accessing service APIs: https://cos.<Region>
ServiceURL *url.URL// Base URL (excluding `path`) for accessing batch APIs: https://<UIN>.cos-cont
BatchURL *url.URL// Base URL (excluding `path`) for accessing CI: https://examplebucket-12500000
CIURL *url.URL}©2013-2022 Tencent Cloud. All rights reserved.

Page 449 of 1869

Cloud Infinite

Parameter
BucketURL

Description
Base URL (excluding path ) for accessing bucket and object related
APIs

Type

Required

StringYes

ServiceURL

Base URL (excluding path ) for accessing service APIs

StringNo

BatchURL

Base URL (excluding path ) for accessing batch APIs

StringNo

CIURL

Base URL (excluding path ) for accessing CI

StringNo

Sample request 1: using a permanent key©2013-2022 Tencent Cloud. All rights reserved.

Page 450 of 1869

Cloud Infinite// Replace `examplebucket-1250000000` and `COS_REGION` with the actual information// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which can// `COS_REGION` can be viewed in the COS console at https://console.tencentcloud.co
u, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")// The following calls the `Get Service` API. By default, all regions (service.cos.
su, _ := url.Parse("https://cos.COS_REGION.myqcloud.com")
b := &cos.BaseURL{BucketURL: u, ServiceURL: su}// 1. Permanent key
client := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you use©2013-2022 Tencent Cloud. All rights reserved.

Page 451 of 1869

Cloud Infinite

SecretKey: os.Getenv("SECRETKEY"),// User `SecretKey`. We recommend you u},})

Sample request 2: using a temporary key// Replace `examplebucket-1250000000` and `COS_REGION` with the actual information// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which can// `COS_REGION` can be viewed in the COS console at https://console.tencentcloud.co
u, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")
b := &cos.BaseURL{BucketURL: u}©2013-2022 Tencent Cloud. All rights reserved.

Page 452 of 1869

Cloud Infinite// 2. Temporary key
client := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{// If a temporary key is required, see the instructions at https://www.tenc
SecretID:"SECRETID",
SecretKey:"SECRETKEY",
SessionToken: "SECRETTOKEN",},})
if client != nil {// Call the COS request}

Note:
For more information about how to generate and use a temporary key, see Generating and Using Temporary Keys.
Sample request 3: setting a domain nameBy modifying BaseURL , you can directly use a custom domain name or global acceleration domain name to access
COS.

©2013-2022 Tencent Cloud. All rights reserved.

Page 453 of 1869

Cloud Infinite// Use a global acceleration domain name to access COSu, _ := url.Parse("http://<BucketName-APPID>.cos.accelerate.myqcloud.com")
b := &cos.BaseURL{BucketURL: u}// 2. Temporary key
client := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{// If a temporary key is required, see the instructions at https://www.tenc
SecretID:"SECRETID",
SecretKey:"SECRETKEY",
SessionToken: "SECRETTOKEN",},©2013-2022 Tencent Cloud. All rights reserved.

Page 454 of 1869

Cloud Infinite})

Sample request 4: CRC64 verification
By default, CRC64 verification is enabled in the COS Go SDK for the uploaded objects.
Note:
The COS Go SDK version should be or later than v0.7.23.
You are strongly advised not to disable CRC64 verification.

// Replace `examplebucket-1250000000` and `COS_REGION` with the actual information// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which can©2013-2022 Tencent Cloud. All rights reserved.

Page 455 of 1869

Cloud Infinite// `COS_REGION` can be viewed in the COS console at https://console.tencentcloud.co
u, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")
b := &cos.BaseURL{BucketURL: u}// 2. Temporary key
client := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{// If a temporary key is required, see the instructions at https://www.tenc
SecretID:"SECRETID",
SecretKey:"SECRETKEY",
SessionToken: "SECRETTOKEN",},})// Disable CRC64 verification.
client.Conf.EnableCRC = false

Creating a bucket©2013-2022 Tencent Cloud. All rights reserved.

Page 456 of 1869

Cloud Infinite

package main

import ("context""net/http""net/url""os""github.com/tencentyun/cos-go-sdk-v5"©2013-2022 Tencent Cloud. All rights reserved.

Page 457 of 1869

Cloud Infinite)

func main(){// Replace `examplebucket-1250000000` and `COS_REGION` with the actual informat// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which// `COS_REGION` can be viewed in the COS console at https://console.tencentclou
u, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com
b := &cos.BaseURL{BucketURL: u}c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you
SecretKey: os.Getenv("SECRETKEY"),// User `SecretKey`. We recommend y},})_, err := c.Bucket.Put(context.Background(), nil)
if err != nil{panic(err)}}

Querying the bucket list

©2013-2022 Tencent Cloud. All rights reserved.

Page 458 of 1869

Cloud Infinite

package main

import ("context""fmt""net/http""os""github.com/tencentyun/cos-go-sdk-v5"©2013-2022 Tencent Cloud. All rights reserved.

Page 459 of 1869

Cloud Infinite)

func main(){c := cos.NewClient(nil, &http.Client{Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you
SecretKey: os.Getenv("SECRETKEY"), // User `SecretKey`. We recommend y},})s, _, err := c.Service.Get(context.Background())
if err != nil{panic(err)}for _, b := range s.Buckets {fmt.Printf("%#v\\n", b)}}

Uploading an object©2013-2022 Tencent Cloud. All rights reserved.

Page 460 of 1869

Cloud Infinite

package main

import ("context""net/http""net/url""os""strings""github.com/tencentyun/cos-go-sdk-v5"©2013-2022 Tencent Cloud. All rights reserved.

Page 461 of 1869

Cloud Infinite)

func main(){// Replace `examplebucket-1250000000` and `COS_REGION` with the actual informat// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which// `COS_REGION` can be viewed in the COS console at https://console.tencentclou
u, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com
b := &cos.BaseURL{BucketURL: u}c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you
SecretKey: os.Getenv("SECRETKEY"),// User `SecretKey`. We recommend y},})// An object key is the unique identifier of an object in a bucket// For example, in the access domain name `examplebucket-1250000000.cos.COS_REG
name := "test/objectPut.go"// 1. Upload the object with a string.
f := strings.NewReader("test")_, err := c.Object.Put(context.Background(), name, f, nil)
if err != nil{panic(err)}// 2. Upload the object with a local file.
_, err = c.Object.PutFromFile(context.Background(), name, "../test", nil)
if err != nil{panic(err)}// 3. Upload the object with a file stream.
fd, err := os.Open("./test")
if err != nil{panic(err)}defer fd.Close()_, err = c.Object.Put(context.Background(), name, fd, nil)
if err != nil{panic(err)}}

Querying objects©2013-2022 Tencent Cloud. All rights reserved.

Page 462 of 1869

Cloud Infinite

package main

import ("context""fmt""net/http""net/url""os""github.com/tencentyun/cos-go-sdk-v5"©2013-2022 Tencent Cloud. All rights reserved.

Page 463 of 1869

Cloud Infinite)

func main(){// Replace `examplebucket-1250000000` and `COS_REGION` with the actual informat// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which// `COS_REGION` can be viewed in the COS console at https://console.tencentclou
u, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com
b := &cos.BaseURL{BucketURL: u}c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you
SecretKey: os.Getenv("SECRETKEY"),// User `SecretKey`. We recommend y},})

opt := &cos.BucketGetOptions{Prefix: "test",
MaxKeys: 3,}v, _, err := c.Bucket.Get(context.Background(), opt)
if err != nil{panic(err)}for _, c := range v.Contents {fmt.Printf("%s, %d\\n", c.Key, c.Size)}}

Download an object©2013-2022 Tencent Cloud. All rights reserved.

Page 464 of 1869

Cloud Infinite

package main

import ("context""fmt""io/ioutil""net/http""net/url""os"©2013-2022 Tencent Cloud. All rights reserved.

Page 465 of 1869

Cloud Infinite"github.com/tencentyun/cos-go-sdk-v5")

func main(){// Replace `examplebucket-1250000000` and `COS_REGION` with the actual informat// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which// `COS_REGION` can be viewed in the COS console at https://console.tencentclou
u, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com
b := &cos.BaseURL{BucketURL: u}c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you
SecretKey: os.Getenv("SECRETKEY"), // User `SecretKey`. We recommend y},})// 1. Obtain the object through response bodyname := "test/objectPut.go"
resp, err := c.Object.Get(context.Background(), name, nil)
if err != nil{panic(err)}bs, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
fmt.Printf("%s\\n", string(bs))// 2. Download the object to the local file system_, err = c.Object.GetToFile(context.Background(), name, "exampleobject", nil)
if err != nil{panic(err)}}Deleting an object©2013-2022 Tencent Cloud. All rights reserved.

Page 466 of 1869

Cloud Infinite

package main

import ("context""net/http""net/url""os""github.com/tencentyun/cos-go-sdk-v5")©2013-2022 Tencent Cloud. All rights reserved.

Page 467 of 1869

Cloud Infinite

func main(){// Replace `examplebucket-1250000000` and `COS_REGION` with the actual informat// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which// `COS_REGION` can be viewed in the COS console at https://console.tencentclou
u, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com
b := &cos.BaseURL{BucketURL: u}c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you
SecretKey: os.Getenv("SECRETKEY"), // User `SecretKey`. We recommend y},})name := "test/objectPut.go"_, err := c.Object.Delete(context.Background(), name)
if err != nil{panic(err)}}©2013-2022 Tencent Cloud. All rights reserved.

Page 468 of 1869

Cloud Infinite

Image Processing
Persistent Image Processing：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for persistent image processing.
API

Description

Persistent image processing

Processes images persistently.

Processing During Upload
COS allows you to process images during upload. To enable this, add Pic-Operations to the request header
and set relevant parameters. You can also save the input images and processing results to COS. Currently, images
within 20 MB can be processed.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 469 of 1869

Cloud Infinite

opt := &cos.ObjectPutOptions{nil,&cos.ObjectPutHeaderOptions{
XOptionHeader: &http.Header{},},}pic := &cos.PicOperations{
IsPicInfo: 1,
Rules: []cos.PicOperationsRules{{
FileId: "format.jpg",©2013-2022 Tencent Cloud. All rights reserved.

Page 470 of 1869

Cloud Infinite

Rule:"imageView2/format/png",},},}
opt.XOptionHeader.Add("Pic-Operations", cos.EncodePicOperations(pic))
name := "test.jpg"
local_filename := "./test.jpg"
res, _, err := c.CI.PutFromFile(context.Background(), name, local_filename, opt)

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 471 of 1869

Cloud Infinite

type PicOperations struct {IsPicInfo int
Rules[]PicOperationsRules}
type PicOperationsRules struct {Bucket string
FileId string
Rulestring}Parameter
IsPicInfo

Rules

Description
Whether to return the input image information. Valid values: 0 (no),1 (yes). Default value: 0.
Processing rules (up to five rules are supported). Each rule
corresponds to one processing result. If this parameter is not
specified, images will not be processed.

Type

Required

int

No

Array

No

StringNo

stringYes

stringNo

Name of the destination bucket to store the results in the format of
BucketBucketName-APPID . If this parameter is not specified, theresults will be stored in the current bucket by default.
Path of the processing result file. If the path starts with / , theFileIdresult file will be stored in the specified folder; otherwise, it will be
stored in the same directory as the input image file.
Processing parameters. For more information, see the persistentimage processing API. To process an image with a specified style,Rule

the value must start with style/ with the style name followed.
For example, if the style name is test , the value of ruleshould be style/test .

Processing In-Cloud Data
This API is used to process an image stored in COS and save the processing result to COS.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 472 of 1869

Cloud Infinite

opt := &cos.ImageProcessOptions{
IsPicInfo: 1,
Rules: []cos.PicOperationsRules{{
FileId: "format.jpg",
Rule:"imageView2/format/png",},},}
name := "test.jpg"
res, _, err := c.CI.ImageProcess(context.Background(), name, opt)

©2013-2022 Tencent Cloud. All rights reserved.

Page 473 of 1869

Cloud Infinite©2013-2022 Tencent Cloud. All rights reserved.

Page 474 of 1869

Cloud Infinite

Basic Image Processing：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for basic image processing.
API

Description

Scaling

Scales up/down an image.

Cropping

Crops an image, including regular cropping, scaling and cropping, cropping to circle,
rounded corner cropping, and smart face cropping.

Rotation

Rotates an image, including regular rotation and adaptive rotation.

Format conversion

Converts the format of an image, optimizes the GIF format, and performs progressive
display.

Quality change

Adjusts the quality of an image.

Gaussian blurring

Blurs an image by a Gaussian function.

Sharpening

Sharpens an image.

Image watermark

Adds a watermark to an image.

Text watermark

Adds a real-time text watermark to an image.

Basic image
information

Queries the basic information of an image, such as format, width, and height.

acquisition
Image EXIF dataacquisition

Queries the EXIF data of an image.

Image average hue
acquisition

Queries the average hue of an image.

Metadata removal

Removes the image metadata, including the EXIF data.

Quick thumbnail
template

Generates a thumbnail through an image processing template.

Pipeline operator

Performs multiple operations on an image in sequence.

©2013-2022 Tencent Cloud. All rights reserved.

Page 475 of 1869

Cloud Infinite

ScalingFeature description
CI uses the imageMogr2 API to scale images.
Method prototype

func (s *CIService) Get(ctx context.Context, key string, operation string, opt *Objfunc (s *CIService) GetToFile(ctx context.Context, key, localpath, operation string©2013-2022 Tencent Cloud. All rights reserved.

Page 476 of 1869

Cloud Infinite

Sample request

name := "test.jpg"// Sample 1. Get an object from the response bodyresp, err := c.CI.Get(context.Background(), name, "imageMogr2/thumbnail/!50px", nil
if err != nil {//ERROR}defer resp.Body.Close()
ioutil.ReadAll(resp.Body)©2013-2022 Tencent Cloud. All rights reserved.

Page 477 of 1869

Cloud Infinite// Sample 2. Download an object
filepath := "test.jpg"_, err = c.CI.GetToFile(context.Background(), name, filepath, "imageMogr2/thumbnail

Parameter description
Parameter

Description

Type

Required

stringYes

Unique identifier of the object in the bucket. For example, if an
object's access endpoint is examplebucketkey

1250000000.cos.apguangzhou.myqcloud.com/doc/pic.jpg , its key is
doc/pic.jpg .

operation

Image processing operation, such as scaling, cropping,rotation, format conversion, and quality change.

stringYes

ObjectGetOptions

Object download parameters. For more information, see Object
Operations.

stringNo

id

Object VersionId

stringNo

Cropping
Feature description
CI uses the imageMogr2 API to crop images, including regular cropping, scaling and cropping, cropping to circle,
rounded corner cropping, and smart face cropping.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 478 of 1869

Cloud Infinitename := "test.jpg"
filepath := "test.jpg"_, err = c.CI.GetToFile(context.Background(), name, filepath, "imageMogr2/cut/600x6

Other Basic Image Processing Operations
Feature description©2013-2022 Tencent Cloud. All rights reserved.

Page 479 of 1869

Cloud Infinite

You can perform other basic processing operations on images by changing the value of the operation
parameter. For example, you can rotate the image clockwise by 90 degrees as follows:name := "test.jpg"
filepath := "test.jpg"_, err = c.CI.GetToFile(context.Background(), name, filepath, "imageMogr2/rotate/90©2013-2022 Tencent Cloud. All rights reserved.

Page 480 of 1869

Cloud Infinite

Image Advanced Compression：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for image advanced compression.
API

Description

Imageadvancedcompression

Allows you to easily convert images into formats that provide a high compression ratio, such as
TPG and HEIF. This effectively reduces the transfer time, loading time, and the use of
bandwidth and traffic.

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 481 of 1869

Cloud Infinite// Convert the input image to TPG format
name := "test.png"
filepath := "test.tpg"_, err := c.CI.GetToFile(context.Background(), name, filepath, "imageMogr2/format/t
if err != nil {// ERROR}// Convert the input image to HEIF format
filepath = "test.heif"_, err = c.CI.GetToFile(context.Background(), name, filepath, "imageMogr2/format/he©2013-2022 Tencent Cloud. All rights reserved.

Page 482 of 1869

Cloud Infinite

if err != nil {// ERROR}©2013-2022 Tencent Cloud. All rights reserved.

Page 483 of 1869

Cloud Infinite

Guetzli Compression：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for Guetzli compression.
API

Description

Enabling Guetzli compression

Enables the Guetzli compression feature for a bucket.

Querying Guetzli status

Queries whether the Guetzli compression feature is enabled.

Disabling Guetzli compression

Disables the Guetzli compression feature.

Enabling Guetzli Compression
Feature description
This API is used to enable the Guetzli compression feature for a bucket.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 484 of 1869

Cloud Infinite

func (s *CIService) PutGuetzli(ctx context.Context) (*Response, error)

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 485 of 1869

Cloud Infinite// `CIURL` is requiredu, _ := url.Parse("https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com")cu, _ := url.Parse("http://examplebucket-1250000000.pic.ap-guangzhou.myqcloud.com")
b := &cos.BaseURL{BucketURL: u, CIURL: cu}
c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("SECRETID"),
SecretKey: os.Getenv("SECRETKEY"),},})©2013-2022 Tencent Cloud. All rights reserved.

Page 486 of 1869

Cloud Infinite_, err := c.CI.PutGuetzli(context.Background())
log_status(err)

Querying Guetzli Status
Feature description
This API is used to query whether the Guetzli compression feature is enabled.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 487 of 1869

Cloud Infinite

func (s *CIService) GetGuetzli(ctx context.Context) (*GetGuetzliResult, *Response,

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 488 of 1869

Cloud Infinite// `CIURL` is requiredu, _ := url.Parse("https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com")cu, _ := url.Parse("http://examplebucket-1250000000.pic.ap-guangzhou.myqcloud.com")
b := &cos.BaseURL{BucketURL: u, CIURL: cu}
c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("SECRETID"),
SecretKey: os.Getenv("SECRETKEY"),},})©2013-2022 Tencent Cloud. All rights reserved.

Page 489 of 1869

Cloud Infinite

res, _, err := c.CI.GetGuetzli(context.Background())
if err == nil {fmt.Printf("%v\\n", res.GuetzliStatus)}

Response description

type GetGuetzliResult struct {GuetzliStatus string}©2013-2022 Tencent Cloud. All rights reserved.

Page 490 of 1869

Cloud Infinite

Node Name

Description

Type

GuetzliStatus

Whether to enable the Guetzli compression feature: on or off

StringDisabling Guetzli Compression
This API is used to disable the Guetzli compression feature.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 491 of 1869

Cloud Infinite

func (s *CIService) DeleteGuetzli(ctx context.Context) (*Response, error)

Sample request// `CIURL` is requiredu, _ := url.Parse("https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com")cu, _ := url.Parse("http://examplebucket-1250000000.pic.ap-guangzhou.myqcloud.com")
b := &cos.BaseURL{BucketURL: u, CIURL: cu}
c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{©2013-2022 Tencent Cloud. All rights reserved.

Page 492 of 1869

Cloud Infinite

SecretID: os.Getenv("SECRETID"),
SecretKey: os.Getenv("SECRETKEY"),},})_, err := c.CI.DeleteGuetzli(context.Background())©2013-2022 Tencent Cloud. All rights reserved.

Page 493 of 1869

Cloud Infinite

Blind Watermark：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for blind watermarking.
API

Description

Blindwatermarking

Adds a blind watermark to or extracts a blind watermark from a local image and uploads theimage to a bucket.

Adding Blind Watermark
Feature description
You can add a blind watermark when uploading or downloading an object.
Sample 1: Adding a blind watermark during upload©2013-2022 Tencent Cloud. All rights reserved.

Page 494 of 1869

Cloud Infinite

opt := &cos.ObjectPutOptions{nil,&cos.ObjectPutHeaderOptions{
XOptionHeader: &http.Header{},},}pic := &cos.PicOperations{
IsPicInfo: 1,
Rules: []cos.PicOperationsRules{{
FileId: ".jpg",©2013-2022 Tencent Cloud. All rights reserved.

Page 495 of 1869

Cloud Infinite

Rule:"watermark/3/type/3/text/" + base64.StdEncoding.EncodeToString(},},}
opt.XOptionHeader.Add("Pic-Operations", cos.EncodePicOperations(pic))
name := "test.jpg"
filepath := "./test.jpg"
res, _, err := c.CI.PutFromFile(context.Background(), name, filepath, opt)

Sample 2: Adding a blind watermark during download©2013-2022 Tencent Cloud. All rights reserved.

Page 496 of 1869

Cloud Infinitename = "test.jpg"
filepath := "watermark.jpg"_, err = c.CI.GetToFile(context.Background(), name, filepath, "watermark/3/type/3/t

Extracting Blind Watermark
The request for extracting a blind watermark is the same as that used to simply upload a file to COS, except that you
need to add the image processing parameter Pic-Operations to the request header and use the blind
watermark extraction parameter watermark/4 .
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 497 of 1869

Cloud Infinite

opt := &cos.ObjectPutOptions{nil,&cos.ObjectPutHeaderOptions{
XOptionHeader: &http.Header{},},}pic := &cos.PicOperations{
IsPicInfo: 1,
Rules: []cos.PicOperationsRules{{
FileId: "format2.jpg",©2013-2022 Tencent Cloud. All rights reserved.

Page 498 of 1869

Cloud Infinite

Rule:"watermark/4/type/3/text/" + base64.StdEncoding.EncodeToString(},},}
opt.XOptionHeader.Add("Pic-Operations", cos.EncodePicOperations(pic))
name := "test2.jpg"_, err := c.Object.PutFromFile(context.Background(), name, filepath, opt)

©2013-2022 Tencent Cloud. All rights reserved.

Page 499 of 1869

Cloud Infinite

CI Service：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for CI.
API

Description

Binding CI

Activates the CI service, which needs to be bound to an existing COS bucket.

Querying CI status

Queries whether the CI service has been activated for a bucket.

Unbinding CI

Unbinds the CI service from a bucket (the bucket and files in it will be retained in COS).

Binding CI
Feature description
This API is used to activate the CI service.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 500 of 1869

Cloud Infinite

func (s *CIService) OpenCIService(ctx context.Context) (*Response, error)

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 501 of 1869

Cloud Infinite_, err := c.CI.OpenCIService(context.Background())

Querying CI Status
Feature description
This API is used to query whether CI has been enabled for a bucket.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 502 of 1869

Cloud Infinite

func (s *CIService) GetCIService(ctx context.Context) (*CIServiceResult, *Response,

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 503 of 1869

Cloud Infinite

res, _, err := c.CI.GetCIService(context.Background())

Parameter description
Parameter

Description

CIServiceResult

Whether the CI service is activated.

©2013-2022 Tencent Cloud. All rights reserved.

Page 504 of 1869

Cloud Infinite

Unbinding CI
Feature description
This API is used to unbind the CI service from a bucket.
Method prototype

func (s *CIService) CloseCIService(ctx context.Context) (*Response, error)©2013-2022 Tencent Cloud. All rights reserved.

Page 505 of 1869

Cloud Infinite

Sample request_, err := c.CI.CloseCIService(context.Background())©2013-2022 Tencent Cloud. All rights reserved.

Page 506 of 1869

Cloud Infinite

Original Image Protection：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for original image protection.
API

Description

Enabling original image protection

Enables the original image protection feature for a bucket.

Querying original image protection status

Queries whether the original image protection feature is enabled.

Disabling original image protection

Disables the original image protection feature.

Enabling Original Image Protection
Feature description
This API is used to enable the original image protection feature for a bucket.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 507 of 1869

Cloud Infinite

func (s *CIService) OpenOriginProtect(ctx context.Context) (*Response, error)

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 508 of 1869

Cloud Infinite_, err := c.CI.OpenOriginProtect(context.Background())

Querying Original Image Protection Status
Feature description
This API is used to query whether the original image protection feature is enabled.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 509 of 1869

Cloud Infinite

func (s *CIService) GetOriginProtect(ctx context.Context) (*OriginProtectResult, *R

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 510 of 1869

Cloud Infinite

res, _, err := c.CI.GetOriginProtect(context.Background())

Parameter description
Parameter

Description

OriginProtectResult

Whether original image protection is enabled©2013-2022 Tencent Cloud. All rights reserved.

Page 511 of 1869

Cloud Infinite

Disabling Original Image Protection
Feature description
This API is used to disable the original image protection feature.
Method prototype

func (s *CIService) CloseOriginProtect(ctx context.Context) (*Response, error)©2013-2022 Tencent Cloud. All rights reserved.

Page 512 of 1869

Cloud Infinite

Sample request_, err := c.CI.CloseOriginProtect(context.Background())©2013-2022 Tencent Cloud. All rights reserved.

Page 513 of 1869

Cloud Infinite

Media Processing
Media Bucket APIs：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for media buckets.
API

Operation

Description

DescribeMediaBuckets

Querying media processing activation
statusQueries buckets with media processing
enabledQuerying Media Processing Activation Status
Feature description
This API is used to query buckets with media processing enabled.
Note:
The COS Go SDK version must be at least v0.7.32.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 514 of 1869

Cloud Infinite

func (s *CIService) DescribeMediaProcessBuckets(ctx context.Context, opt *DescribeM

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 515 of 1869

Cloud Infinite// Set the request URL to `ci.<Region>.myqcloud.com`
cu, _ := url.Parse("https://ci.ap-guangzhou.myqcloud.com")
b := &cos.BaseURL{CIURL: cu}
c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{
SecretID: "SECRETID",
SecretKey: "SECRETKEY",})
opt := &cos.DescribeMediaProcessBucketsOptions{Regions: "ap-guangzhou",©2013-2022 Tencent Cloud. All rights reserved.

Page 516 of 1869

Cloud Infinite}
res, _, err := c.CI.DescribeMediaProcessBuckets(context.Background(), opt)
if err != nil {// ERROR}
fmt.Printf("res: %+v\\n", res)Parameter description

type DescribeMediaProcessBucketsOptions struct {Regions
string©2013-2022 Tencent Cloud. All rights reserved.

Page 517 of 1869

Cloud Infinite

BucketNames string
BucketName string
PageNumber int
PageSize
int}
Parameter

Description

Type

Required

stringNo

string

No

Region information, such as ap-shanghai and ap-beijing .
Regions

BucketNames

To specify multiple regions, separate them with commas. For more
information, see Regions and Domain Names.
Bucket name. To specify multiple bucket names, separate them withcommas. Exact search is supported.

BucketName

Bucket name prefix for prefix search.

stringNo

PageNumber

Page number.

stringNo

PageSize

Number of entries per page.

stringNo

Response description©2013-2022 Tencent Cloud. All rights reserved.

Page 518 of 1869

Cloud Infinite

type DescribeMediaProcessBucketsResult struct {RequestId
stringTotalCount
int
PageNumber
int
PageSize
intMediaBucketList []MediaProcessBucket}
type MediaProcessBucket struct {BucketId
stringRegionstringCreateTime string©2013-2022 Tencent Cloud. All rights reserved.

Page 519 of 1869

Cloud Infinite}
The nodes are as described below:
Node Name

Parent(Keyword)

NodeRequestId

Description

Type

Response

Unique ID of the request.

StringTotalCount

Response

Total number of media buckets.

Int

PageNumber

Response

PageSize

Response

Number of entries per page, which is the same as
pageSize in the request.

Int

MediaBucketList

Response

Media bucket list.

Container

Current page number, which is the same as pageNumberin the request.

Int

MediaBucketList has the following sub-nodes:
Node Name

Parent NodeDescription

Type

BucketId

Response.MediaBucketList

Bucket ID.

StringName

Response.MediaBucketList

Bucket name, which is the same as
BucketId .

StringRegionResponse.MediaBucketList

Bucket region.

StringCreateTime

Response.MediaBucketList

Creation time.

String(Keyword)©2013-2022 Tencent Cloud. All rights reserved.

Page 520 of 1869

Cloud Infinite

Media Information APIs：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for media information.
API

Operation

Description

GetMediaInfo

Querying file information

Queries media file information

Querying File Information
Feature description
This API is used to query the information of a media file.
Note:
The COS Go SDK version must be at least v0.7.32.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 521 of 1869

Cloud Infinite

func (s *CIService) GetMediaInfo(ctx context.Context, name string, opt *ObjectGetOp

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 522 of 1869

Cloud Infinite

res, _, err := c.CI.GetMediaInfo(context.Background(), "test.mp4", nil)
if err != nil {// ERROR}
fmt.Printf("res: %+v\\n", res)Parameter description
Parameter

Description©2013-2022 Tencent Cloud. All rights reserved.

Type

RequiredPage 523 of 1869

Cloud Infinite

nameUnique identifier of the object in the bucket. For example, if an object's

name

Yes

access endpoint is examplebucket-1250000000.cos.apguangzhou.myqcloud.com/doc/pic.jpg , its key is
doc/pic.jpg .
opt

Common request headers and parameters. For more information, see
Cloud Object Storage.

structNo

id

Object VersionId for versioning.

stringNo

Response description©2013-2022 Tencent Cloud. All rights reserved.

Page 524 of 1869

Cloud Infinite

type GetMediaInfoResult struct {XMLNamexml.Name
MediaInfo struct {Format struct {Bitratefloat32
Duration
float32
FormatLongName string
FormatName
stringNumProgram
NumStream
Size

int
int
int

©2013-2022 Tencent Cloud. All rights reserved.

Page 525 of 1869

Cloud Infinite

StartTimefloat32}
Stream struct {Audio []struct {
Index
int
CodecNamestringCodecLongName string
CodecTimeBase string
CodecTagString string
CodecTag
SampleFmt
SampleRate

stringstringint

ChannelChannelLayout
Timebase
StartTime
Duration
BitrateLanguageintstringstringfloat32
float32
float32
string}
Subtitle struct {
Index
int
Language string}
Video struct {
Index
int
CodecName
CodecLongName
CodecTimeBasestringstringstringCodecTagString string
CodecTag
string
ProfilestringHeight
int
Width
int
HasBFrameint
RefFrames
intSar
stringDarstringPixFormat
stringFieldOrder
string
Level
int
Fps
float32
AvgFpsstringTimebase
StartTime
Durationstringfloat32
float32

Bitratefloat32©2013-2022 Tencent Cloud. All rights reserved.

Page 526 of 1869

Cloud Infinite

NumFrames
Languageintstring}}}}
The nodes are as described below:
Node Name (Keyword)

Parent NodeDescription

Type

Response

None

Response container

Container

Response has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

MediaInfo

Response

Media details.

Container

MediaInfo has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

StreamResponse.MediaInfo

Stream information.

Container

FormatResponse.MediaInfo

Format information.

Container

Stream has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Video

Response.MediaInfo. Stream

Video information.

Container

Audio

Response.MediaInfo. Stream

Audio information.

Container

Subtitle

Response.MediaInfo. Stream

Subtitles information.

Container

Format has the following sub-nodes (certain nodes may not be returned during video information query):
Node Name(Keyword)

Parent NodeDescription

Type

NumStream

Response.MediaInfo.
FormatNumber of streams (including videos, audios, andsubtitles).

Int

NumProgram

Response.MediaInfo.

Number of programs.

Int

Format©2013-2022 Tencent Cloud. All rights reserved.

Page 527 of 1869

Cloud Infinite

FormatName

Response.MediaInfo.
FormatContainer format name.

StringFormatLongName

Response.
MediaInfo.Format

Detailed name of the container format.

StringStart time in seconds.

Float

StartTime

Response.MediaInfo.
FormatDuration

Response.MediaInfo.
FormatDuration in seconds.

Float

BitrateResponse.MediaInfo.
FormatBitrate in Kbps.

Int

Size in bytes.

Int

Size

Response.MediaInfo.
FormatVideo has the following sub-nodes (certain nodes may not be returned during video information query):
Node Name(Keyword)
Index

Parent Node
Response.MediaInfo.
Stream.Video

Description

Type

Stream number.

Int

CodecName

Response.MediaInfo.
Stream.Video

Codec format name.

StringCodecLongName

Response.MediaInfo.
Stream.Video

Detailed name of the codec format.

StringCodec timebase.

StringCodecTimeBase

Response.MediaInfo.
Stream.Video

CodecTagString

Response.MediaInfo.
Stream.Video

Codec tag name.

StringCodecTag

Response.MediaInfo.
Stream.Video

Codec tag.

StringVideo codec profile.

StringVideo height in px.

Int

ProfileHeightResponse.MediaInfo.
Stream.Video
Response.MediaInfo.
Stream.Video©2013-2022 Tencent Cloud. All rights reserved.

Page 528 of 1869

Cloud Infinite

Width

Response.MediaInfo.

Video width in px.

Int

Stream.Video
HasBFrame

Response.MediaInfo.
Stream.Video

Whether B-frames exist. 1: yes; 0: no.

Int

RefFrames

Response.MediaInfo.
Stream.Video

Number of reference frames for video
codec.

Int

Sample aspect ratio.

StringSar

Response.MediaInfo.
Stream.Video

Dar

Response.MediaInfo.
Stream.Video

Display aspect ratio.

StringPixFormat

Response.MediaInfo.
Stream.Video

Pixel format.

StringField order.

StringFieldOrder

Response.MediaInfo.
Stream.Video

Level

Response.MediaInfo.
Stream.Video

Video codec level.

Int

Fps

Response.MediaInfo.
Stream.Video

Video frame rate.

Int

Average frame rate.

StringTimebase.

StringVideo start time in seconds.

Float

Video duration in seconds.

Float

Bitrate in Kbps.

Float

AvgFpsTimebase

StartTime

Duration

BitrateResponse.MediaInfo.
Stream.Video
Response.MediaInfo.
Stream.Video
Response.MediaInfo.
Stream.Video
Response.MediaInfo.
Stream.Video
Response.MediaInfo.
Stream.Video

NumFrames

Response.MediaInfo.
Stream.Video

Total number of frames.

Int

Language

Response.MediaInfo.
Stream.Video

Language.

String©2013-2022 Tencent Cloud. All rights reserved.

Page 529 of 1869

Cloud Infinite

Audio has the following sub-nodes (certain nodes may not be returned during video information query):
Node Name

Parent NodeDescription

Type

Index

Response.MediaInfo. Stream.Audio

Stream number.

Int

CodecName

Response.MediaInfo. Stream.Audio

Codec format name.

StringCodecLongName

Response.MediaInfo. Stream.Audio

Detailed name of the codec format.

StringCodecTimeBase

Response.MediaInfo. Stream.Audio

Codec timebase.

StringCodecTagString

Response.MediaInfo. Stream.Audio

Codec tag name.

StringCodecTag

Response.MediaInfo. Stream.Audio

Codec tag.

StringSampleFmt

Response.MediaInfo. Stream.Audio

Sample format.

StringSampleRate

Response.MediaInfo. Stream.Audio

Sample rate.

Int

ChannelResponse.MediaInfo. Stream.Audio

Number of channels.

Int

ChannelLayout

Response.MediaInfo. Stream.Audio

Channel layout.

StringTimebase

Response.MediaInfo. Stream.Audio

Timebase.

StringStartTime

Response.MediaInfo. Stream.Audio

Audio start time in seconds.

Float

Duration

Response.MediaInfo. Stream.Audio

Audio duration in seconds.

Float

BitrateResponse.MediaInfo. Stream.Audio

Bitrate in Kbps.

Float

Language

Response.MediaInfo. Stream.Audio

Language.

String(Keyword)

Subtitle has the following sub-nodes:
Node Name

Parent NodeDescription

Type

Index

Response.MediaInfo.
Stream.Subtitle

Stream number.

Int

Language

Response.MediaInfo.
Stream.Subtitle(Keyword)©2013-2022 Tencent Cloud. All rights reserved.

Language. und indicates no query
result.

StringPage 530 of 1869

Cloud Infinite

Media Screenshot APIs：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for media screenshot.
API

Operation

Description

GetSnapshot

Querying screenshot

Query the screenshot of media file at some time point

Querying Screenshot
Feature description
This API is used to query the screenshot of a media file at some time point.
Note:
The COS Go SDK version must be at least v0.7.32.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 531 of 1869

Cloud Infinite

func (s *CIService) GetSnapshot(ctx context.Context, name string, opt *GetSnapshotO

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 532 of 1869

Cloud Infinite

opt := &cos.GetSnapshotOptions{
Time: 1,}
resp, err := c.CI.GetSnapshot(context.Background(), "test.mp4", opt)
if err != nil {// ERROR}
fd, err := os.OpenFile("test.jpg", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
if err != nil {// ERROR©2013-2022 Tencent Cloud. All rights reserved.

Page 533 of 1869

Cloud Infinite}_, err = io.Copy(fd, resp.Body)
fd.Close()

Parameter description

type GetSnapshotOptions struct {Time
float32
Height int
Width int
Format string©2013-2022 Tencent Cloud. All rights reserved.

Page 534 of 1869

Cloud Infinite

Rotate stringModestring}Parameter

Description

Required

Type

Yes

name

Unique identifier of the object in the bucket. For example, if an
object's access endpoint is examplebucketname

1250000000.cos.apguangzhou.myqcloud.com/doc/pic.jpg , its key is
doc/pic.jpg .

opt

Screenshot parameter.

No

structid

Object VersionId for versioning.

No

StringTime

Screenshot time point in seconds.

Yes

float

Width

Screenshot width. Default value: 0.

No

Int

No

Int

No

StringNo

StringNo

StringScreenshot height. Default value: 0. If width and height are
Heightboth 0 , the width and height of the video are used. If one of themis 0 , the other value is used to automatically adapt to the aspectratio of the video.

FormatRotateScreenshot format. Valid values: jpg, png. Default value: jpg.
Image rotation method. auto: Rotate automatically according to thevideo rotation information. off: Do not rotate. Default value: auto.
Frame capturing method. keyframe: Capture the last keyframeMode

before the specified time point. exactframe: Capture the frame at a
specified time point. Default value: exactframe.

Response description
Parameter

Description

Required

Type

Response

HTTP response.

Yes

StructResponse.Header

HTTP response header.

Yes

StructResponse.Body

HTTP response body.

Yes

Struct©2013-2022 Tencent Cloud. All rights reserved.

Page 535 of 1869

Cloud Infinite

File Preview
Querying Document Preview Feature Status：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for querying the document preview feature
status.
API

Description

Querying document preview feature

Queries whether the document preview feature is enabled for a

statusbucket.

Querying Document Preview Feature Status
Feature description
This API ( DescribeDocProcessBuckets ) is used to query whether the document preview feature is enabled fora bucket.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 536 of 1869

Cloud Infinite

func (s *CIService) DescribeDocProcessBuckets(ctx context.Context, opt *DescribeDoc

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 537 of 1869

Cloud Infinite

BucketsOpt := &cos.DescribeDocProcessBucketsOptions{Regions: "ap-shanghai",}res, _, err := c.CI.DescribeDocProcessBuckets(context.Background(), BucketsOpt)

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 538 of 1869

Cloud Infinite

type DescribeDocProcessBucketsOptions struct {Regions
stringBucketNames string
BucketName string
PageNumber int
PageSize

int}
Parameter

Description©2013-2022 Tencent Cloud. All rights reserved.

Type

Page 539 of 1869

Cloud Infinite

Regions

Region abbreviation, such as ap-shanghai and ap-beijing . To

stringspecify multiple regions, separate them with commas (,). For more
information, see Regions and Domains.
BucketNames

Bucket name. To specify multiple bucket names, separate them with commas(,). Exact search is supported.

stringBucketName

Bucket name prefix for prefix searchstringPageNumber

Page number

int

pageSize

Number of entries per pageint

Response description©2013-2022 Tencent Cloud. All rights reserved.

Page 540 of 1869

Cloud Infinite

type DescribeDocProcessBucketsResult struct {RequestId
stringTotalCount
int
PageNumber
int
PageSize
int
DocBucketList []DocProcessBucket}
type DocProcessBucket struct {BucketId
stringNamestringRegionstring©2013-2022 Tencent Cloud. All rights reserved.

Page 541 of 1869

Cloud Infinite

CreateTime
stringAliasBucketId string}
Parameter

Description

Type

RequestId

Unique request ID

stringTotalCount

Total number of buckets with document preview enabled

int

PageNumber

Current page number, which is the same as pageNumber in the request

int

PageSize

Number of entries per page, which is the same as pageSize in the request

int

DocBucketList

List of buckets with document preview enabled

Container

BucketId

Bucket ID

stringName

Bucket name, which is the same as BucketId

stringRegionRegionstringCreateTime

Creation time

stringAliasBucketId

Bucket alias

string©2013-2022 Tencent Cloud. All rights reserved.

Page 542 of 1869

Cloud Infinite

Sync Request API：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for sync requests for document preview.
API

Description

Sync request API

Submits a sync request for document preview.

Sync Request API
Feature description
This API is used to submit a sync request for document preview.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 543 of 1869

Cloud Infinite

func (s *CIService) DocPreview(ctx context.Context, name string, opt *DocPreviewOpt

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 544 of 1869

Cloud Infinite

opt := &cos.DocPreviewOptions{
Page: 1,}
resp, err := c.CI.DocPreview(context.Background(), "form.pdf", opt)

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 545 of 1869

Cloud Infinite

type DocPreviewOptions struct {SrcTypestringPage
int
ImageParams
stringSheet
int
DstTypestringPassword
stringComment
int
ExcelPaperDirection int
Quality
int
Zoom
int

©2013-2022 Tencent Cloud. All rights reserved.

Page 546 of 1869

Cloud Infinite}
Parameter

Description

Type

name

Object name, such as folder/document.pdf

String

SrcType

Source data type. Currently, the document conversion feature
determines the source data type according to the file extension of theString

COS object. If the object has no extension, you can set this value.

page

Number of the document page to be converted, which is counted from
1 by default.
For spreadsheets, page indicates the number of the part in theint

specified sheet to be converted.
Processing parameters for the output image. All parameters of basic
image processing are supported. To specify multiple parameters,
ImageParams

Sheet

DstTypeseparate them with pipeline operators. In this way, the image can beprocessed based on multiple parameters in sequence in the same
request.
Spreadsheet parameter, indicating the number of the sheet to beconverted. Default value: 1
Output file extension. Valid values:
png
jpg

Stringint

Stringpdf
If the specified value cannot be recognized, jpg is used.
Password

Comment

ExcelPaperDirection

Quality

Password to open the Office document. If you need to convert apassword-protected document, set this parameter.
Whether to hide comments and tracked changes.
0 (default): Hide comments and tracked changes.
1: Show comments and tracked changes.
Paper orientation of the spreadsheet. 0 (default): Vertical; other values:
Horizontal
Quality of the generated preview image. Value range: [1-100]. Default
value: 100.
For example, if the value is 100 , the quality of the generated image

String

int

int

int

will be 100%.
Zoom

Scaling parameter of the preview image. Value range: [10-200].
Default value: 100.

©2013-2022 Tencent Cloud. All rights reserved.

int

Page 547 of 1869

Cloud Infinite

For example, if the value is 200 , the image will be zoomed in(enlarged) by 200%.

©2013-2022 Tencent Cloud. All rights reserved.

Page 548 of 1869

Cloud Infinite

Async Processing Queue APIs：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for file preview queues.
API

Operation

Description

DescribeDocProcessQueues

Querying file preview queues

Queries specified file preview queues.

UpdateDocProcessQueue

Updating file preview queue

Updates specified file preview queue.

Querying File Preview Queue
Feature description
This API ( DescribeDocProcessQueues ) is used to query file preview queues.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 549 of 1869

Cloud Infinite

func (s *CIService) DescribeDocProcessQueues(ctx context.Context, opt *DescribeDocP

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 550 of 1869

Cloud Infinite

DescribeQueueOpt := &cos.DescribeDocProcessQueuesOptions{
QueueIds: "p111a8dd208104ce3b11c78398f658ca8,p4318f85d2aa14c43b1dba6f9b78be9b3,
PageNumber: 1,
PageSize:
2,}res, _, err := c.CI.DescribeDocProcessQueues(context.Background(), DescribeQueueOpt

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 551 of 1869

Cloud Infinite

type DescribeDocProcessQueuesOptions struct {QueueIds
string `url:"queueIds,omitempty"`Statestring `url:"state,omitempty"`
PageNumber int`url:"pageNumber,omitempty"`
PageSize
int`url:"pageSize,omitempty"`}
Parameter

Description

Type

QueueIds

Queue ID. If you enter multiple IDs, separate them by comma.

String©2013-2022 Tencent Cloud. All rights reserved.

Page 552 of 1869

Cloud InfiniteState

1. Active: Jobs in the queue will be scheduled and executed by the file preview

Stringservice.
2. Paused: The queue is paused, and jobs in it will no longer be scheduled andexecuted. All jobs in the queue will remain in the Paused status, while jobs being
executed will continue without being affected.
PageNumber

Page number.

int

PageSize

Number of entries per page.

int

Response description©2013-2022 Tencent Cloud. All rights reserved.

Page 553 of 1869

Cloud Infinite

type DescribeDocProcessQueuesResult struct {XMLNamexml.Name
RequestId
stringTotalCount
int
PageNumber
int
PageSize
int
QueueList[]DocProcessQueue
NonExistPIDs []string}
type DocProcessQueue struct {QueueId
string©2013-2022 Tencent Cloud. All rights reserved.

Page 554 of 1869

Cloud Infinite

NamestringStatestringMaxSize
int
MaxConcurrent int
UpdateTime
stringCreateTime
stringNotifyConfig *DocProcessQueueNotifyConfig}
type DocProcessQueueNotifyConfig struct {UrlstringState string
Type string
Event string}
Parameter

Description

Type

RequestId

Unique ID of the request

StringTotalCount

Total number of queues

Int

PageNumber

Current page number, which is the same as pageNumber in the request.

Int

PageSize

Number of entries per page, which is the same as pageSize in therequest.

Int

QueueList

Queue array

Container

NonExistPIDs

List of IDs of non-existent queues

String array

QueueId

Queue ID

StringName

Queue name

StringState

Current status: Active or Paused .

StringNotifyConfig

Callback configuration

Container

MaxSize

Maximum length of the queue

Int

MaxConcurrent

Maximum number of concurrent jobs in the current queueInt

UpdateTime

Update time

StringCreateTime

Creation time

StringUrl

Callback address

String©2013-2022 Tencent Cloud. All rights reserved.

Page 555 of 1869

Cloud Infinite

State

Switch status: On or Off .

StringType

Callback type: Url .

String

Event

The event that triggers the callback

StringUpdating File Preview Queue
Feature description
This API ( UpdateDocProcessQueue ) is used to update a file preview queue.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 556 of 1869

Cloud Infinite

func (s *CIService) UpdateDocProcessQueue(ctx context.Context, opt *UpdateDocProces

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 557 of 1869

Cloud Infinite

updateQueueOpt := &cos.UpdateDocProcessQueueOptions{Name:"queue-doc-process-1",
QueueID: "p111a8dd208104ce3b11c78398f658ca8",State:"Active",
NotifyConfig: &cos.DocProcessQueueNotifyConfig{
State: "Off",},}res, _, err := c.CI.UpdateDocProcessQueue(context.Background(), updateQueueOpt)©2013-2022 Tencent Cloud. All rights reserved.

Page 558 of 1869

Cloud Infinite

Parameter description

type UpdateDocProcessQueueOptions struct {XMLNamexml.NameNamestringQueueID
stringStatestringNotifyConfig *DocProcessQueueNotifyConfig}
Parameter

Description©2013-2022 Tencent Cloud. All rights reserved.

Type

Page 559 of 1869

Cloud Infinite

Name

Queue name

StringQueueID

Queue ID

StringState

Queue status

StringNotifyConfig

Notification channel. For more information, see
DocProcessQueue.NotifyConfig .

Container

Response description©2013-2022 Tencent Cloud. All rights reserved.

Page 560 of 1869

Cloud Infinite

type UpdateDocProcessQueueResult struct {XMLNamexml.Name
RequestId string
Queue*DocProcessQueue}
Parameter

Description

Type

RequestId

Unique ID of the request

StructQueue

Queue information. For more information, see
DescribeDocProcessQueuesResult.QueueList .

©2013-2022 Tencent Cloud. All rights reserved.

StructPage 561 of 1869

Cloud Infinite

Async Processing Job APIs：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for file preview jobs.
API

Operation

Description

CreateDocProcessJobs

Submitting file preview job

Submits file preview job.

DescribeDocProcessJob

Querying file preview job

Queries specified file preview job.

DescribeDocProcessJobs

Pulling file preview jobs

Pulls eligible file preview jobs.

Submitting File Preview Job
Feature description
This API ( CreateDocProcessJobs ) is used to submit a file preview job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 562 of 1869

Cloud Infinite

func (s *CIService) CreateDocProcessJobs(ctx context.Context, opt *CreateDocProcess

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 563 of 1869

Cloud Infinite

createJobOpt := &cos.CreateDocProcessJobsOptions{Tag: "DocProcess",
Input: &cos.DocProcessJobInput{
Object: "form.pdf",},
Operation: &cos.DocProcessJobOperation{
Output: &cos.DocProcessJobOutput{
Region: "ap-guangzhou",Object: "test-doc${Number}",
Bucket: "examplebucket-1250000000",},©2013-2022 Tencent Cloud. All rights reserved.

Page 564 of 1869

Cloud Infinite

DocProcess: &cos.DocProcessJobDocProcess{TgtType:"png",StartPage:
1,
EndPage:-1,
ImageParams: "watermark/1/image/aHR0cDovL3Rlc3QwMDUtMTI1MTcwNDcwOC5jb3M},},
QueueId: "p111a8dd208104ce3b11c78398f658ca8",}
res, _, err := c.CI.CreateDocProcessJobs(context.Background(), createJobOpt)

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 565 of 1869

Cloud Infinite

type CreateDocProcessJobsOptions struct {XMLNamexml.NameTagstring
Input*DocProcessJobInput
Operation *DocProcessJobOperation
QueueId
string}type DocProcessJobInput struct {Object string}
type DocProcessJobOperation struct {©2013-2022 Tencent Cloud. All rights reserved.

Page 566 of 1869

Cloud Infinite

Output*DocProcessJobOutput
DocProcess*DocProcessJobDocProcess
DocProcessResult *DocProcessJobDocProcessResult}type DocProcessJobOutput struct {Region string
Bucket string
Object string}
type DocProcessJobDocProcess struct {SrcTypestringTgtTypestringSheetId
StartPage
EndPage
ImageParams

int
int
int
string

DocPassword
stringComments
int
PaperDirection int
Quality
Zoom

int
int

}
Parameter

Description

Type

Tag

Job type, which currently can only be DocProcess .

StringInput

The object to be processed

Container

Operation

Operation ruleContainer

QueueId

ID of the queue which the job is in

StringObjectFile URL in COS. Bucket is specified by Host .

StringOutputResult output address

Container

DocProcess

Job type parameter, which takes effect only if Tag is
DocProcess .

Container

RegionBucket region

StringBucketResult storage bucket

StringObjectOutput file path. For non-spreadsheet files, the output file name

Stringmust include the ${Number} or ${Page} parameter. If there
are multiple output files, ${Number} indicates that serial numbers©2013-2022 Tencent Cloud. All rights reserved.

Page 567 of 1869

Cloud Infinite

start from 1, and ${Page} indicates that serial numbers are thesame as preview page numbers. ${Number} indicates that serial
numbers start from 1 for multiple output files; for example, if the input
parameter is abc_${Number}.jpg to preview pages 5–6 in the file,then output file names will be abc_1.jpg and abc_2.jpg .
${Page} indicates that serial numbers are the same as preview
page numbers for multiple output files; for example, if the input
parameter is abc_${Page}.jpg to preview pages 5–6 in the file,then the output file names will be abc_5.jpg and abc_6.jpg .
For spreadsheet files, the output file path must include the${SheetID} placeholder, and the output file name must
include the ${Number} parameter. For example, if the input
parameter is /${SheetID}/abc_${Number}.jpg , then thecorresponding number of folders will be generated first based on thenumber of Excel sheets to be converted, and then the corresponding
number of image files will be generated in these folders.

SrcType

Source data type. Currently, the file conversion feature determines thesource data type based on the file extension of the COS object. If theStringobject has no extension, you can set this value.
Type of the output target image file. Valid values: png , jpg ,TgtTypepdf . If the input file format cannot be recognized, the jpg format

Stringwill be used by default.
SheetId

Sheet parameter, indicating to convert the xth sheet. Default value: 1 .
If this value is set to 0 , all sheets will be converted.

Int

Starts conversion from page X. A spreadsheet file may be split into
StartPage

multiple pages, with multiple images generated, and StartPage
indicates to start the conversion from page X of the specifiedInt

SheetId . Default value: 1.

EndPageEnds conversion on page X. A spreadsheet file may be split into multiple
pages, with multiple images generated, and EndPage indicates to
end the conversion on page X of the specified SheetId . DefaultIntvalue: -1 (converting all pages).
Processing parameters for the output image. All parameters of basic
ImageParams

DocPassword

image processing are supported. To specify multiple parameters,
separate them by pipeline operator. In this way, the image can beprocessed by multiple parameters in sequence in the same request.
Password to open the Office file. If you need to convert a passwordprotected file, set this field.

©2013-2022 Tencent Cloud. All rights reserved.

StringStringPage 568 of 1869

Cloud Infinite

Comments

Whether to hide comments and apply track changes. 0: hide comments
and apply track changes; 1: show comments and track changes. DefaultIntvalue: 0.
PaperDirection

Quality

Paper orientation of the spreadsheet. 0: vertical; other values:
horizontal. Default value: 0.
Quality of the generated preview image. Value range: [1-100]. Default
value: 100. For example, if the value is 100, the quality of the generated

Int

Int

image will be 100%.

Zoom

Zooming parameter of the preview image. Value range: [10-200].
Default value: 100. For example, if the value is 200, the image will bezoomed in (enlarged) by 200%.

Int

Response description©2013-2022 Tencent Cloud. All rights reserved.

Page 569 of 1869

Cloud Infinite

type CreateDocProcessJobsResult struct {JobsDetail DocProcessJobDetail}type DocProcessJobDetail struct {CodestringMessagestringJobId
stringTag
stringStatestringCreationTime string
QueueId
string©2013-2022 Tencent Cloud. All rights reserved.

Page 570 of 1869

Cloud Infinite

Input
Operation*DocProcessJobInput*DocProcessJobOperation}
Parameter

Description

Type

JobsDetailJob details

Container

CodeError code, which will be returned only if State is Failed .

StringMessage

Error message, which will be returned only if State is Failed .

String

JobId

Job ID

StringTag

Job type: DocProcess

StringState

Job status. Valid values: Submitted , Running , Success ,Failed , Pause , Cancel .

StringCreationTime

Job creation time

StringQueueId

ID of the queue which the job is in

String

Input

Path of the input file for this job. For more information, see
CreateDocProcessJobsOptions.Input .

Container

Operation

Operation rule. For more information, see
CreateDocProcessJobsOptions.Operation .

Container

Querying Specified File Preview Job
Feature description
This API ( DescribeDocProcessJob ) is used to query a specified file preview job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 571 of 1869

Cloud Infinite

func (s *CIService) DescribeDocProcessJob(ctx context.Context, jobid string) (*Desc

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 572 of 1869

Cloud Infinite

jobid := "<jobid>"
res, _, err := c.CI.DescribeDocProcessJob(context.Background(), jobid)Parameter description
Parameter

Description

Type

jobid

File preview job ID

StringResponse description©2013-2022 Tencent Cloud. All rights reserved.

Page 573 of 1869

Cloud Infinite

type DescribeDocProcessJobResult struct {JobsDetail*DocProcessJobDetail
NonExistJobIds string}
Parameter
JobsDetail

Description
Job details. Same as Response.JobsDetail in
CreateDocProcessJobs .

©2013-2022 Tencent Cloud. All rights reserved.

Type
Container

Page 574 of 1869

Cloud Infinite

NonExistJobIds

List of non-existing job IDs queried. If all jobs exist, this node will not be
returned.

StringPulling Eligible File Preview Jobs
Feature description
The API ( DescribeDocProcessJobs ) is used to pull file preview jobs that meet specified conditions.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 575 of 1869

Cloud Infinite

func (s *CIService) DescribeDocProcessJobs(ctx context.Context, opt *DescribeDocPro

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 576 of 1869

Cloud Infinite

DescribeJobsOpt := &cos.DescribeDocProcessJobsOptions{
QueueId: "p111a8dd208104ce3b11c78398f658ca8",
Tag:"DocProcess",}
res, _, err := c.CI.DescribeDocProcessJobs(context.Background(), DescribeJobsOpt)

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 577 of 1869

Cloud Infinite

type DescribeDocProcessJobsOptions struct {QueueId
stringTag
stringOrderByTime
stringNextToken
stringSize
intStatesstringStartCreationTime string
EndCreationTime
string}©2013-2022 Tencent Cloud. All rights reserved.

Page 578 of 1869

Cloud Infinite

Parameter

Description

Type

QueueId

ID of the queue from which jobs are pulled

StringTag

Job type: DocProcess

StringOrderByTime

Desc (default) or Asc

StringNextToken

Context token for pagination

StringSize

Maximum number of jobs that can be pulled. The default value is 10. The
maximum value is 100.

Int

StatesStatus of the jobs to pull. If you enter multiple job statuses, separate themby comma. Valid values: All (default value), Submitted ,String

Running , Success , Failed , Pause , Cancel .
StartCreationTime

EndCreationTime

Start time of the time range for job pulling in the format of %Y-%m%dT%H:%m:%S%z .
End time of the time range for job pulling in the format of %Y-%m%dT%H:%m:%S%z .

StringStringResponse description©2013-2022 Tencent Cloud. All rights reserved.

Page 579 of 1869

Cloud Infinite

type DescribeDocProcessJobsResult struct {JobsDetail []DocProcessJobDetail
NextToken string}
Parameter
JobsDetail

Description
Job details. Same as Response.JobsDetail in
CreateDocProcessJobs .

©2013-2022 Tencent Cloud. All rights reserved.

Type
Container

Page 580 of 1869

Cloud Infinite

NextToken

Context token for pagination©2013-2022 Tencent Cloud. All rights reserved.

StringPage 581 of 1869

Cloud Infinite

File-to-HTML Conversion：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for sync requests for file preview.
API
File-toHTML
conversion

Description
The file-to-HTML conversion feature allows you to generate HTML pages for preview frommultiple types of files. It enables easy online file preview on PC, app, and other terminals. It is
widely suitable for diverse use cases, such as online education, enterprise OA, online knowledge
base, and online file preview.

File-to-HTML Conversion
Feature description
This API is used to convert files in various formats to HTML for preview.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 582 of 1869

Cloud Infinite

func (s *CIService) DocPreviewHTML(ctx context.Context, name string, opt *DocPrevie

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 583 of 1869

Cloud Infinite

opt := &cos.DocPreviewHTMLOptions{
DstType: "html",
SrcType: "ppt",
Copyable: "1",
HtmlParams: &cos.HtmlParams{
CommonOptions: &cos.HtmlCommonParams{
IsShowTopArea: false,},
PptOptions: &cos.HtmlPptParams{
IsShowBottomStatusBar: true,},©2013-2022 Tencent Cloud. All rights reserved.

Page 584 of 1869

Cloud Infinite},
Htmlwaterword:"5pWw5o2u5LiH6LGhLeaWh+aho+mihOiniA==",

Htmlfillstyle: "cmdiYSgxMDIsMjA0LDI1NSwwLjMp", // rgba(102,204,255,0.3)
Htmlfront:"Ym9sZCAyNXB4IFNlcmlm",// bold 25px Serif
Htmlrotate:"315",
Htmlhorizontal: "50",
Htmlvertical:"100",}
resp, err := c.CI.DocPreviewHTML(context.Background(), "form.pdf", opt)

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 585 of 1869

Cloud Infinite

type DocPreviewHTMLOptions struct {DstTypestring`url:"dstType,omitempty"`
SrcTypestring`url:"srcType,omitempty"`
Sign
string`url:"sign,omitempty"`
Copyablestring`url:"copyable,omitempty"`
HtmlParams*HtmlParams `url:"htmlParams,omitempty"`
Htmlwaterword string`url:"htmlwaterword,omitempty"`
Htmlfillstyle string`url:"htmlfillstyle,omitempty"`
Htmlfront
stringHtmlrotate
stringHtmlhorizontal string`url:"htmlfront,omitempty"``url:"htmlrotate,omitempty"``url:"htmlhorizontal,omitempty"`©2013-2022 Tencent Cloud. All rights reserved.

Page 586 of 1869

Cloud Infinite

Htmlverticalstring`url:"htmlvertical,omitempty"`}
type HtmlParams struct {CommonOptions *HtmlCommonParams `json:"commonOptions,omitempty"`
WordOptions*HtmlWordParams`json:"wordOptions,omitempty"`
PdfOptions*HtmlPdfParams`json:"pdfOptions,omitempty"`
PptOptions*HtmlPptParams`json:"pptOptions,omitempty"`}
type HtmlCommonParams struct {IsShowTopArea
bool `json:"isShowTopArea"`
IsShowHeaderbool `json:"isShowHeader"`IsBrowserViewFullscreen bool `json:"isBrowserViewFullscreen"`
IsIframeViewFullscreen bool `json:"isIframeViewFullscreen"`}type HtmlWordParams struct {IsShowDocMapbool `json:"isShowDocMap"`
IsBestScalebool `json:"isBestScale"`
IsShowBottomStatusBar bool `json:"isShowBottomStatusBar"`}
type HtmlPdfParams struct {IsShowCommentbool `json:"isShowComment"`
IsInSafeModebool `json:"isInSafeMode"`
IsShowBottomStatusBar bool `json:"isShowBottomStatusBar"`}
type HtmlPptParams struct {IsShowBottomStatusBar bool `json:"isShowBottomStatusBar"`}

Parameter
DstType
SrcTypeDescription
Output target file type, which is fixed at html for HTMLpreview.
Source file type as listed in Getting Started.

Type

Required

StringYes

StringNo

StringNo

StringNo

Object download signature, which must be URL-encoded. If
Sign

the previewed object is privately readable, the signatureneeds to be passed in. For more information, see Request
Signature.

Copyable

Whether the file content is copyable. Valid values: 1 (yes),©2013-2022 Tencent Cloud. All rights reserved.

Page 587 of 1869

Cloud Infinite

0 (no).
Custom configuration parameters in JSON structure, whichmust be URL-safe Base64-encoded as described in FAQs.
HtmlParams

Htmlwaterword

HtmlfillstyleHtmlfront

Default configuration: { commonOptions: { isShowTopArea:
true, isShowHeader: true } }. For supported configurations,see Custom Configuration Overview.
Watermark text, which must be URL-safe Base64-encoded
as described in FAQs and is empty by default.
Watermark RGBA (color and transparency), which must be
URL-safe Base64-encoded as described in FAQs and isrgba(192,192,192,0.6) by default.
Watermark text style, which must be URL-safe Base64encoded as described in FAQs and is bold 20px

StringNo

StringNo

StringNo

StringNo

StringNo

StringNo

String

No

Serif by default.
Htmlrotate

Htmlhorizontal

Htmlvertical

Rotation angle of the watermark text in degrees. Value range:
0–360. Default value: 315 .
Horizontal spacing of the watermark text in px. Default value:
50 .
Vertical spacing of the watermark text in px. Default value:
100 .

©2013-2022 Tencent Cloud. All rights reserved.

Page 588 of 1869

Cloud Infinite

Content Moderation
Image Moderation：

Last updated 2024-02-29 16:52:32

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for image moderation.
API

Description

Moderating single image

Leverages CI's content moderation API to scan existing data stored in COS for
porn, illegal, and advertising images.

Batch moderating images
Querying image
moderation job result

Leverages CI's content moderation API to scan existing data stored in COS for
porn, illegal, and advertising images.
Queries the details of a specified image moderation job.

Single image moderation
Feature description
The existing data scan feature of image moderation leverages CI's persistent processing API to scan existing datastored in COS for porn, illegal, and advertising images. Image moderation requests are GET requests.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 589 of 1869

Cloud Infinite// Basic operations
func (s *CIService) ImageRecognition(ctx context.Context, name string, DetectType s// You can specify more parameters.
func (s *CIService) ImageAuditing(ctx context.Context, name string, opt *ImageRecog

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 590 of 1869

Cloud Infinite

DetectType := "porn,ads"
name := "test.jpg"
res, _, err := c.CI.ImageRecognition(context.Background(), name, DetectType)opt := &cos.ImageRecognitionOptions{
CIProcess: "sensitive-content-recognition",
DetectType: "porn,ads",
DetectUrl:"http://www.example.com/test.jpg",
BizType:"ce25f391a72e11eb99f********",}©2013-2022 Tencent Cloud. All rights reserved.

Page 591 of 1869

Cloud Infinite

res, _, err := c.CI.ImageAuditing(context.Background(), "", opt)

Parameter description

type ImageRecognitionOptions struct {CIProcessstringDetectType
stringDetectUrl
stringInterval
int
MaxFrames
int
BizTypestring©2013-2022 Tencent Cloud. All rights reserved.

Page 592 of 1869

Cloud Infinite

LargeImageDetect int
DataIdstringAsync
int
Callback
string}Parameter

Description

Type

Required

StringYes

StringYes

StringNo

StringNo

String

No

IntegerNo

IntegerNo

Name of the image file in the COS bucket. The COS bucket is
specified by Host . For example, if the file is img.jpg in
the test directory in the examplebucket-1250000000
namebucket in Beijing, then Host is examplebucket1250000000.cos.ap-beijing.myqcloud.com , andObjectKey is test/img.jpg . If the
ImageAuditing API is used to moderate an image URL,
pass in an empty string.

CIProcessThis field identifies the data processing feature, which issensitive-content-recognition for content
moderation.

BizType

Moderation policy. If this parameter is not specified, the default
policy will be used. The policy can be configured in the console.
For more information, see Setting Moderation Policy.
Moderation type, such as porn (pornography) and ads(advertising). You can select multiple types; for example,

DetectType

detect-type=porn,ads indicates to moderate the image
for porn and advertising information. If you need to moderate
more scenes, use the BizType parameter.
You can enter a detect-url value to moderate an image
accessible over the public network. If detect-url is not
specified, the backend will moderate by ObjectKey by

DetectUrl

default. If detect-url is specified, the backend will
moderate by detect-url , and there will be no need to enter
ObjectKey . Sample detect-url :http://www.example.com/abc.jpg .
For GIF image moderation, you can use this parameter toIntervalconfigure the frame capturing interval. The default value is 5 ,indicating to capture a frame every five frames starting from thefirst frame (included).

MaxFrames

The maximum number of frames to be captured for GIF image
moderation, which must be greater than 0. The default value is©2013-2022 Tencent Cloud. All rights reserved.

Page 593 of 1869

Cloud Infinite

5 , indicating to capture five frames at most.
Whether to compress the image that exceeds the size limit
before moderation. Valid values: 0 (no), 1 (yes). Default
LargeImageDetectvalue: 0 . Note: Images up to 32 MB in size can becompressed, and image compression fees will be charged. For

IntegerNo

StringNo

StringNo

StringNolarge animated images such as GIF, the compression time islong, which may cause the moderation to fail due to timeout.
DataIdImage ID. This field will return the original content in the result,which can contain up to 512 bytes.
Whether to moderate asynchronously. Valid values: 0 (returns

Async

the result synchronously); 1 (moderates asynchronously).
Default value: 0 .
The moderation result (in Detail mode) can be sent to yourcallback address in the form of a callback. This parameter takes

Callback

effect for async moderation. Addresses starting with
http:// or https:// are supported, such as
http://www.callback.com .

Response description
Calling the ImageRecognition or ImageAuditing function will parse the XML content returned by the API
into the ImageRecognitionResult structure. For specific response parameters, see Single Image Moderation.

Batch image moderation
Feature description
The batch image moderation API adopts a sync POST request method. You can use this API to perform content
moderation on multiple image files.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 594 of 1869

Cloud Infinite// Batch image moderation
func (s *CIService) BatchImageAuditing(ctx context.Context, opt *BatchImageAuditing

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 595 of 1869

Cloud Infinite// Replace `examplebucket-1250000000` and `COS_REGION` with the actual information// For CI jobs, you need to provide the CIURL.
bu, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")cu, _ := url.Parse("https://examplebucket-1250000000.ci.COS_REGION.myqcloud.com")
b := &cos.BaseURL{BucketURL: bu, CIURL: cu}
c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("SECRETID"),
SecretKey: os.Getenv("SECRETKEY"),},})©2013-2022 Tencent Cloud. All rights reserved.

Page 596 of 1869

Cloud Infinite

opt := &cos.BatchImageAuditingOptions{
Input: []cos.ImageAuditingInputOptions{cos.ImageAuditingInputOptions{
DataId: "1",
Object: "test.jpg",},cos.ImageAuditingInputOptions{
DataId: "2",
Url: "http://www.example.com/test.jpg",},},
Conf: &cos.ImageAuditingJobConf{
DetectType: "Porn,Ads",},}
res, _, err := c.CI.BatchImageAuditing(context.Background(), opt)

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 597 of 1869

Cloud Infinite

type ImageAuditingInputOptions struct {DataIdstringObjectstringUrlstringInterval
int
MaxFrames
int
LargeImageDetect int
UserInfo*UserExtraInfo}
type UserExtraInfo struct {TokenId string©2013-2022 Tencent Cloud. All rights reserved.

Page 598 of 1869

Cloud Infinite

Nickname string
DeviceId string
AppId
stringRoomstringIPstringTypestring}type ImageAuditingJobConf struct {DetectType string
BizTypestringAsync
int
Callback
string}type BatchImageAuditingOptions struct {Input[]ImageAuditingInputOptions
Conf*ImageAuditingJobConf}

Parameter
DataIdObjectDescription
Image ID. This field will return the original content in the result,which can contain up to 512 bytes.
Name of the image file stored in the COS bucket; for example, if
the file is image.jpg in the test directory, then thefilename is test/image.jpg . Either Object or Url

Type

Required

StringNo

StringNo

String

No

IntegerNo

IntegerNo

StringNo

can be selected at a time.

Url

Full URL of the image file, such as
http://examplebucket-1250000000.cos.apshanghai.myqcloud.com/image.jpg . Either Object
or Url can be selected at a time.

Interval

Frame capturing frequency, which takes effect for GIF images
only. The default value is 5 , indicating to capture a frame
every five frames starting from the first frame (included).

MaxFrames

BizType

The maximum number of frames to be captured, which takes
effect for GIF images only. The default value is 5 , indicating
to capture only five frames of the GIF image for moderation.
The parameter value must be greater than 0.
Moderation policy. If this parameter is not specified, the default
policy will be used. The policy can be configured in the console.
For more information, see Setting Moderation Policy.

©2013-2022 Tencent Cloud. All rights reserved.

Page 599 of 1869

Cloud Infinite

DetectType

The scene to be moderated, such as Porn (pornography)

StringNo

StringNo

String

No

IntegerNo

ObjectNo

and Ads (advertising). You can pass in multiple types andseparate them by comma, such as Porn,Ads . If you need tomoderate more scenes, use the BizType parameter.
Whether to moderate asynchronously. Valid values: 0
Async(returns the result synchronously); 1 (moderates
asynchronously). Default value: 0 .
The moderation result (in Detail mode) can be sent to your

Callback

callback address in the form of a callback. This parameter
takes effect for async moderation. Addresses starting with
http:// or https:// are supported, such as
http://www.callback.com .
Whether to compress the image that exceeds the size limit
before moderation. Valid values: 0 (no), 1 (yes). Default

LargeImageDetect

UserInfovalue: 0 . Note: Images up to 32 MB in size can becompressed, and image compression fees will be charged. For
large animated images such as GIF, the compression time islong, which may cause the moderation to fail due to timeout.
Business field.

Response description
Calling the BatchImageAuditing function will parse the XML content returned by the API into the
BatchImageAuditingJobResult structure. For specific response parameters, see Batch Image Moderation.

Querying image moderation job result
Feature description
This API is used to query the result of an image moderation job. The API request is a GET request.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 600 of 1869

Cloud Infinite// Image moderation - job queryfunc (s *CIService) GetImageAuditingJob(ctx context.Context, jobid string) (*GetIma

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 601 of 1869

Cloud Infinite

jobId := "iace25f391a72e11eb99f********"
res, _, err := c.CI.GetImageAuditingJob(context.Background(), jobId)

Parameter description
Parameter

Description

Type

jobId

Job ID

StringResponse description©2013-2022 Tencent Cloud. All rights reserved.

Page 602 of 1869

Cloud Infinite

Calling the GetImageAuditingJob function will parse the XML content returned by the API into the
GetImageAuditingJobResult structure. For specific response parameters, see Querying Image Moderation
Job Result.

©2013-2022 Tencent Cloud. All rights reserved.

Page 603 of 1869

Cloud Infinite

Video Moderation：

Last updated 2024-02-29 16:52:32

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for video moderation.
API

Description

Submitting video moderation job

Submits a video moderation job.

Querying video moderation job result

Queries the result of a specified video moderation job.

Creating a Job
This API ( PutVideoAuditingJob ) is used to submit a video moderation job. You can receive the moderation
result by setting the callback address or querying by JobId .
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 604 of 1869

Cloud Infinite

func (s *CIService) PutVideoAuditingJob(ctx context.Context, opt *PutVideoAuditingJ

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 605 of 1869

Cloud Infinite// Replace examplebucket-1250000000 and COS_REGION with the actual information.
// For CI jobs, you need to provide the CIURL.
bu, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")cu, _ := url.Parse("https://examplebucket-1250000000.ci.COS_REGION.myqcloud.com")
b := &cos.BaseURL{BucketURL: bu, CIURL: cu}
c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("SECRETID"),
SecretKey: os.Getenv("SECRETKEY"),}})©2013-2022 Tencent Cloud. All rights reserved.

Page 606 of 1869

Cloud Infinite

opt := &cos.PutVideoAuditingJobOptions{
InputObject: "demo.mp4",
Conf: &cos.VideoAuditingJobConf{
DetectType: "Porn,Ads",
Snapshot: &cos.PutVideoAuditingJobSnapshot{
Mode:"Interval",
TimeInterval: 50.5,
Count:
100,},},}
res, _, err := c.CI.PutVideoAuditingJob(context.Background(), opt)

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 607 of 1869

Cloud Infinite

type PutVideoAuditingJobOptions struct {InputObject
stringInputUrlstringInputDataId
stringInputUserInfo *UserExtraInfo
Conf*VideoAuditingJobConf
Type
string}type UserExtraInfo struct {TokenId string
Nickname string©2013-2022 Tencent Cloud. All rights reserved.

Page 608 of 1869

Cloud Infinite

DeviceId string
AppId
string
Room
IP
Type

stringstringstring}type VideoAuditingJobConf struct {DetectType
stringSnapshot*PutVideoAuditingJobSnapshot
Callback
stringCallbackVersion string
CallbackType
int
BizTypestringDetectContent
int}
type PutVideoAuditingJobSnapshot struct {ModestringCount
int
TimeInterval float32}
Parameter

Description

Type

Name of the video file in the COS bucket; for example, if the file is
InputObject

video.mp4 in the test directory, then the filename istest/video.mp4 . Either Object or Url can be selected at a

Stringtime.
Full URL of the video file, such as http://examplebucketInputUrl

1250000000.cos.ap-shanghai.myqcloud.com/test.mp4 . Either

StringObject or Url can be selected at a time.
InputDataId

Video ID. This field will return the original content in the result, which cancontain up to 512 bytes.

StringInputUserInfo

Business field.

ObjectType

Moderation job type, which is fixed at live_video for live stream
moderation.

StringConf

Moderation rule configuration.

Struct

BizType

Moderation policy. If this parameter is not specified, the default policy will
be used. The policy can be configured in the console as instructed in

StringSetting Moderation Policy.
DetectType

The scene to be moderated, such as Porn (pornography) and Ads©2013-2022 Tencent Cloud. All rights reserved.

StringPage 609 of 1869

Cloud Infinite(advertising). You can pass in multiple types and separate them by comma,
such as Porn,Ads . If you need to moderate more scenes, use the
BizType parameter.
Video image moderation is implemented by taking a certain number ofSnapshotscreenshots based on the video frame capturing capability and thenmoderating the screenshots one by one. This parameter is used to specify
the configuration of video frame capturing.

Struct

The moderation result can be sent to your callback address in the form of a
Callback

callback. Addresses starting with http:// or https:// areStringsupported, such as http://www.callback.com .
Structure of the callback content. Valid values: Simple (the callback
CallbackVersion

content contains basic information), Detail (the callback content

Stringcontains detailed information). Default value: Simple .
Callback segment type. Valid values: 1 (calls back all captured frames
CallbackTypeand audio segments); 2 (calls back only non-compliant captured frames

Integer

and audio segments). Default value: 1 .
Whether to moderate video sound. Valid values: 0 (moderates the video
DetectContent

image only), 1 (moderates both the video image and video sound).

Integer

Default value: 0 .
Frame capturing mode. Valid values: Interval (interval mode),
Average (average mode), Fps (fixed frame rate mode). Default
value: Interval . Interval mode: The TimeInterval andCount parameters take effect. If Count is set but TimeInterval
Mode

is not, all frames will be captured to generate a total of Count images.

StringAverage mode: The Count parameter takes effect, indicating tocapture a total of Count images at an average interval in the entire
video. Fps mode: TimeInterval indicates how many frames tocapture per second. If TimeInterval is not set, all frames will be
captured to generate a total of Count images.

Count

The number of captured frames. Value range: (0, 10000].

Integer

TimeIntervalVideo frame capturing frequency. Value range: (0.000, 60.000] seconds.
The value supports the float format, accurate to the millisecond.

Float

Response description
Calling the PutVideoAuditingJob function will parse the XML content returned by the API into the
PutVideoAuditingJobResult structure. For specific response parameters, see Submitting Video Moderation©2013-2022 Tencent Cloud. All rights reserved.

Page 610 of 1869

Cloud Infinite

Job.

Querying a Job
This API ( GetVideoAuditingJob ) is used to query the result of the specified video moderation job by JobId .
Method prototype

func (s *CIService) GetVideoAuditingJob(ctx context.Context, jobid string) (*GetVid©2013-2022 Tencent Cloud. All rights reserved.

Page 611 of 1869

Cloud Infinite

Sample request// Replace examplebucket-1250000000 and COS_REGION with the actual information.
// For CI jobs, you need to provide the CIURL.
bu, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")cu, _ := url.Parse("https://examplebucket-1250000000.ci.COS_REGION.myqcloud.com")
b := &cos.BaseURL{BucketURL: bu, CIURL: cu}
c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("SECRETID"),©2013-2022 Tencent Cloud. All rights reserved.

Page 612 of 1869

Cloud Infinite

SecretKey: os.Getenv("SECRETKEY"),}})
jobId := "avce25f391a72e11eb99f********"
res, _, err := c.CI.GetVideoAuditingJob(context.Background(), jobId)

Parameter description
Parameter

Description

Type

jobId

Job ID

StringResponse description
Calling the GetVideoAuditingJob function will parse the XML content returned by the API into the
GetVideoAuditingJobResult structure. For specific response parameters, see Querying Video Moderation
Job Result.

©2013-2022 Tencent Cloud. All rights reserved.

Page 613 of 1869

Cloud Infinite

Audio Moderation：

Last updated 2024-02-29 16:52:32

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for audio moderation.
API

Description

Submitting audio moderation job

Submits an audio moderation job.

Querying audio moderation job result

Queries the result of a specified audio moderation job.

Creating a Job
This API ( PutAudioAuditingJob ) is used to submit an audio moderation job. You can receive the moderation
result by setting the callback address or querying by JobId .
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 614 of 1869

Cloud Infinite

func (s *CIService) PutAudioAuditingJob(ctx context.Context, opt *PutAudioAuditingJ

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 615 of 1869

Cloud Infinite// Replace examplebucket-1250000000 and COS_REGION with the actual information.
// For CI jobs, you need to provide the CIURL.
bu, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")cu, _ := url.Parse("https://examplebucket-1250000000.ci.COS_REGION.myqcloud.com")
b := &cos.BaseURL{BucketURL: bu, CIURL: cu}
c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("SECRETID"),
SecretKey: os.Getenv("SECRETKEY"),}})©2013-2022 Tencent Cloud. All rights reserved.

Page 616 of 1869

Cloud Infinite

opt := &cos.PutAudioAuditingJobOptions{
InputObject: "test.mp3",
Conf: &cos.AudioAuditingJobConf{
DetectType: "Porn,Ads",},}
res, _, err := c.CI.PutAudioAuditingJob(context.Background(), opt)

Parameter description

type PutAudioAuditingJobOptions struct {©2013-2022 Tencent Cloud. All rights reserved.

Page 617 of 1869

Cloud Infinite

InputObject
stringInputUrlstringInputDataId
stringInputUserInfo *UserExtraInfo
Conf*AudioAuditingJobConf}
type UserExtraInfo struct {TokenId string
Nickname string
DeviceId string
AppId
stringRoomstringIPType

stringstring}type AudioAuditingJobConf struct {DetectType
stringCallback
stringCallbackVersion string
BizTypestring}Parameter

Description

Type

InputObject

Name of the audio file stored in the COS bucket; for example, if the file isaudio.mp3 in the test directory, then the filename isStringtest/audio.mp3 . Either Object or Url can be selected at a time.
Full URL of the audio file, such as http://examplebucketInputUrl

1250000000.cos.ap-shanghai.myqcloud.com/audio.mp3 . Either

StringObject or Url can be selected at a time.
InputDataId

Audio ID. This field will return the original content in the result, which cancontain up to 512 bytes.

StringInputUserInfo

Business field.

ObjectConf

Moderation rule configuration.

Struct

BizType

Moderation policy. If this parameter is not specified, the default policy will be
used. The policy can be configured in the console as instructed in Setting
Moderation Policy.

StringDetectType

The scene to be moderated, such as Porn (pornography) and Ads

String(advertising). You can pass in multiple types and separate them by comma,
such as Porn,Ads . If you need to moderate more scenes, use the
BizType parameter.

©2013-2022 Tencent Cloud. All rights reserved.

Page 618 of 1869

Cloud Infinite

Callback

The moderation result can be sent to your callback address in the form of acallback. Addresses starting with http:// or https:// are supported,

Stringsuch as http://www.callback.com .
Structure of the callback content. Valid values: Simple (the callback
CallbackVersion

content contains basic information), Detail (the callback content contains

Stringdetailed information). Default value: Simple .

Response description
Calling the PutAudioAuditingJob function will parse the XML content returned by the API into the
PutAudioAuditingJobResult structure. For specific response parameters, see Submitting Audio Moderation
Job.

Querying a Job
This API ( GetAudioAuditingJob ) is used to query the result of the specified audio moderation job by JobId .
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 619 of 1869

Cloud Infinite

func (s *CIService) GetAudioAuditingJob(ctx context.Context, jobid string) (*GetAud

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 620 of 1869

Cloud Infinite// Replace examplebucket-1250000000 and COS_REGION with the actual information.
// For CI jobs, you need to provide the CIURL.
bu, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")cu, _ := url.Parse("https://examplebucket-1250000000.ci.COS_REGION.myqcloud.com")
b := &cos.BaseURL{BucketURL: bu, CIURL: cu}
c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("SECRETID"),
SecretKey: os.Getenv("SECRETKEY"),}})©2013-2022 Tencent Cloud. All rights reserved.

Page 621 of 1869

Cloud Infinite

jobId := "sace25f391a72e11eb99f********"
res, _, err := c.CI.GetAudioAuditingJob(context.Background(), jobId)

Parameter description
Parameter

Description

Type

jobId

Job ID.

StringResponse description
Calling the GetAudioAuditingJob function will parse the XML content returned by the API into the
GetAudioAuditingJobResult structure. For specific response parameters, see Querying Audio Moderation
Job Result.

©2013-2022 Tencent Cloud. All rights reserved.

Page 622 of 1869

Cloud Infinite

Text Moderation：

Last updated 2024-02-29 16:52:32

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for text moderation.
API

Description

Submitting text moderation job

Submits a text moderation job.

Querying text moderation job result

Queries the result of a specified text moderation job.

Creating a Job
This API ( PutTextAuditingJob ) is used to submit a text moderation job. If the text content is moderated, theresponse body will directly return the moderation result. If the text object is moderated, the job summary will be
returned. You can receive the moderation result by setting the callback address or querying by JobId .
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 623 of 1869

Cloud Infinite

func (s *CIService) PutTextAuditingJob(ctx context.Context, opt *PutTextAuditingJob

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 624 of 1869

Cloud Infinite// Replace examplebucket-1250000000 and COS_REGION with the actual information.
// For CI jobs, you need to provide the CIURL.
bu, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")cu, _ := url.Parse("https://examplebucket-1250000000.ci.COS_REGION.myqcloud.com")
b := &cos.BaseURL{BucketURL: bu, CIURL: cu}
c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("SECRETID"),
SecretKey: os.Getenv("SECRETKEY"),}})©2013-2022 Tencent Cloud. All rights reserved.

Page 625 of 1869

Cloud Infinite

opt := &cos.PutTextAuditingJobOptions{
InputObject: "test.txt",
Conf: &cos.TextAuditingJobConf{
DetectType: "Porn,Ads",},}
res, _, err := c.CI.PutTextAuditingJob(context.Background(), opt)

Parameter description

type PutTextAuditingJobOptions struct {©2013-2022 Tencent Cloud. All rights reserved.

Page 626 of 1869

Cloud Infinite

InputObject
InputUrlstringstringInputContent string
InputDataId
stringInputUserInfo *UserExtraInfo
Conf*TextAuditingJobConf}
type UserExtraInfo struct {TokenId string
Nickname string
DeviceId string
AppId
stringRoomstringIPstringTypestring}type TextAuditingJobConf struct {DetectType
stringCallback
stringCallbackVersion string
BizTypestring}Parameter

Description

Type

Name of the text file stored in the current COS bucket; for example, if the file istest.txt in the test directory, then the filename is
InputObject

test/test.txt . Only text files in UTF-8 and GBK encodings are

Stringsupported, and the file size cannot exceed 1 MB. You can select only one
parameter among Object , Url , and Content at a time.
When the input content is plain text, it needs to be Base64-encoded first. The
length of the original text before encoding cannot exceed 10,000 UTF-8
InputContent

characters. If the length limit is exceeded, the API will report an error. You canselect only one parameter among Object , Url , and Content at a

Stringtime.
Full URL of the text file, such as http://examplebucketInputUrl

1250000000.cos.ap-shanghai.myqcloud.com/test.txt . You canselect only one parameter among Object , Url , and Content at a

Stringtime.
InputDataId
InputUserInfo

Text ID. This field will return the original content in the result, which can containup to 512 bytes.
Business field.

©2013-2022 Tencent Cloud. All rights reserved.

StringObjectPage 627 of 1869

Cloud Infinite

Conf

Moderation rule configuration.

StructModeration policy. If this parameter is not specified, the default policy will be
BizTypeused. The policy can be configured in the console as instructed in Setting
Moderation Policy.

String

The scene to be moderated. Valid values: Porn (pornography), Ads
DetectType(advertising), Illegal (law violation), and Abuse (abuse). You canpass in multiple types and separate them by comma, such as Porn,Ads . If

Stringyou need to moderate more scenes, use the BizType parameter.

Callback

The moderation result can be sent to your callback address in the form of acallback. Addresses starting with http:// or https:// are supported,
such as http://www.callback.com . If Input is Content , thisStringparameter will not take effect, and the result will be returned directly.
Structure of the callback content. Valid values: Simple (the callback
CallbackVersion

content contains basic information), Detail (the callback content contains

Stringdetailed information). Default value: Simple .

Response description
Calling the PutTextAuditingJob function will parse the XML content returned by the API into the
PutTextAuditingJobResult structure. For specific response parameters, see Submitting Text Moderation
Job.

Querying a Job
This API ( GetTextAuditingJob ) is used to query the result of the specified text moderation job by JobId .
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 628 of 1869

Cloud Infinite

func (s *CIService) GetTextAuditingJob(ctx context.Context, jobid string) (*GetText

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 629 of 1869

Cloud Infinite// Replace examplebucket-1250000000 and COS_REGION with the actual information.
// For CI jobs, you need to provide the CIURL.
bu, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")cu, _ := url.Parse("https://examplebucket-1250000000.ci.COS_REGION.myqcloud.com")
b := &cos.BaseURL{BucketURL: bu, CIURL: cu}
c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("SECRETID"),
SecretKey: os.Getenv("SECRETKEY"),}})©2013-2022 Tencent Cloud. All rights reserved.

Page 630 of 1869

Cloud Infinite

jobId := "stce25f391a72e11eb99f********"
res, _, err := c.CI.GetTextAuditingJob(context.Background(), jobId)

Parameter description
Parameter

Description

Type

jobId

Job ID.

StringResponse description
Calling the GetTextAuditingJob function will parse the XML content returned by the API into the
GetTextAuditingJobResult structure. For specific response parameters, see Querying Text Moderation Job
Result.

©2013-2022 Tencent Cloud. All rights reserved.

Page 631 of 1869

Cloud Infinite

AI-Based Content Recognition
Image QR Code：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for image QR codes.
API

Description

QR codeRecognizes the location and content of valid QR codes in an image, outputs the text information

recognition(URL or text) contained in the QR codes, and pixelates the recognized QR codes.

QR codegeneration

Generates QR codes or barcodes based on the specified text information (URL or text).

QR Code Recognition
Feature description
CI's QR code recognition feature recognizes the location and content of valid QR codes in an image, outputs the text
information (URL or text) contained in the QR codes, and pixelates the recognized QR codes.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 632 of 1869

Cloud Infinite

func (s *CIService) GetQRcode(ctx context.Context, name string, cover int, opt *Obj

Sample request 1: Recognizing during upload©2013-2022 Tencent Cloud. All rights reserved.

Page 633 of 1869

Cloud Infinite

opt := &cos.ObjectPutOptions{nil,&cos.ObjectPutHeaderOptions{
XOptionHeader: &http.Header{},},}pic := &cos.PicOperations{
IsPicInfo: 1,
Rules: []cos.PicOperationsRules{{
FileId: "format.jpg",©2013-2022 Tencent Cloud. All rights reserved.

Page 634 of 1869

Cloud Infinite

Rule:"QRcode/cover/1",},},}
opt.XOptionHeader.Add("Pic-Operations", cos.EncodePicOperations(pic))
name := "test.jpg"
filepath := "./QRcode.jpg"
res, _, err := c.CI.PutFromFile(context.Background(), name, filepath, opt)

Sample request 2: Recognizing during download©2013-2022 Tencent Cloud. All rights reserved.

Page 635 of 1869

Cloud Infinitename := "test.jpg"
res, _, err := c.CI.GetQRcode(context.Background(), name, 1, nil)Parameter description
Parameter
cover

Description
Pixelates the recognized QR code. Valid values: 0 (no), 1 (yes).
Default value: 0 .

TypeRequiredint

Yes

Response description
The returned result of recognition during download is as follows:©2013-2022 Tencent Cloud. All rights reserved.

Page 636 of 1869

Cloud Infinite

type GetQRcodeResult struct {CodeStatus int
QRcodeInfo *QRcodeInfo
ResultImage string}
type QRcodeInfo struct {CodeUrl
stringCodeLocation *CodeLocation}
type CodeLocation struct {Point []string©2013-2022 Tencent Cloud. All rights reserved.

Page 637 of 1869

Cloud Infinite}
Parameter

Description

Type

CodeStatus

Whether QR codes are recognized. 0 : No; 1 : Yes.

int

QRcodeInfo

Recognized QR code. There may be multiple ones.

StructResultImage

Base64-encoded image data, which is returned if the request parameter coveris 1.

stringCodeUrl

QR code content. Content may not be recognized.

stringCodeLocation

Location coordinates of the QR code recognized in the image.

StructPoint

QR code coordinates (X,Y).

Array

QR Code Generation
Feature description
CI's QR code generation feature generates QR codes or barcodes based on the specified text information (URL ortext).
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 638 of 1869

Cloud Infinite

func (s *CIService) GenerateQRcode(ctx context.Context, opt *GenerateQRcodeOptions)func (s *CIService) GenerateQRcodeToFile(ctx context.Context, filePath string, opt

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 639 of 1869

Cloud Infinite

opt := &cos.GenerateQRcodeOptions{
QRcodeContent: "<https://www.example.com>"Mode:
0,
Width:
200,}// Case 1. Generate a QR code
res, _, err := c.CI.GenerateQRcode(context.Background(), opt)// Case 2. Generate a QR code and save it as a file
filepath := "example.jpg"
res, _, err := c.CI.GenerateQRcodeToFile(context.Background(), filepath, opt)

©2013-2022 Tencent Cloud. All rights reserved.

Page 640 of 1869

Cloud Infinite

Parameter description

type GenerateQRcodeOptions struct {QRcodeContent string
Mode
int
Width
int
}
Parameter

Description©2013-2022 Tencent Cloud. All rights reserved.

Type

Page 641 of 1869

Cloud Infinite

QRcodeContent
Mode

Width

Recognizable QR code text information

stringType of the QR code to be generated. Valid values: 0 (QR code), 1

int(barcode). Default value: 0 .
Width of the QR code or barcode to be generated. The height will be compressed
proportionally.

int

Response description

type GenerateQRcodeResult struct {©2013-2022 Tencent Cloud. All rights reserved.

Page 642 of 1869

Cloud Infinite

ResultImage string}
Parameter

Description

Type

ResultImage

Base64-encoded QR code image data

string©2013-2022 Tencent Cloud. All rights reserved.

Page 643 of 1869

Cloud Infinite

File Processing
File Decompression：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for file decompression in CI.
API

Description

Submitting a file decompression job

Submits a file decompression job.

Querying the file decompression result

Queries the result of a specified file decompression job.

Submitting a File Decompression Job
Feature description
This API is used to submit a job to perform file decompression and asynchronously return decompressed files.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 644 of 1869

Cloud Infinite

func (s *CIService) CreateFileProcessJob(ctx context.Context, opt *FileProcessJobOp

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 645 of 1869

Cloud Infinite

createJobOpt := &cos.FileProcessJobOptions{Tag: "FileUncompress",
Input: &cos.FileProcessInput{
Object: "294028.zip",},
Operation: &cos.FileProcessJobOperation{
FileUncompressConfig: &cos.FileUncompressConfig{
Prefix:"uncomp",PrefixReplaced: "1",},Output: &cos.FileProcessOutput{©2013-2022 Tencent Cloud. All rights reserved.

Page 646 of 1869

Cloud Infinite

Region: "ap-beijing",
Bucket: "test-1250000000",}},
QueueId: "p111a8dd208104ce3b11c78398f658ca8",}
res, _, err := c.CI.CreateFileProcessJob(context.Background(), createJobOpt)

Parameter description

type FileProcessJobOptions struct {©2013-2022 Tencent Cloud. All rights reserved.

Page 647 of 1869

Cloud Infinite

XMLNamexml.NameTagstring
Input*FileProcessInput
Operation*FileProcessJobOperation
QueueId
stringCallBackFormat
stringCallBackType
stringCallBack
stringCallBackMqConfig *NotifyConfigCallBackMqConfig}
type FileProcessInput struct {RegionstringBucketObjectstringstring}type FileProcessJobOperation struct {FileHashCodeConfig*FileHashCodeConfig
FileHashCodeResult*FileHashCodeResult
FileUncompressConfig *FileUncompressConfig
FileUncompressResult *FileUncompressResult
FileCompressConfig*FileCompressConfig
FileCompressResult*FileCompressResult
Output*FileProcessOutput
UserData
string}type FileHashCodeConfig struct {Typestring
AddToHeader bool}
type FileHashCodeResult struct {MD5
stringSHA1stringSHA256
stringFileSizeint
LastModified string
Etag
string}type FileUncompressConfig struct {PrefixstringPrefixReplaced string}
type FileUncompressResult struct {RegionstringBucketstring
FileCount string}
type FileCompressConfig struct {©2013-2022 Tencent Cloud. All rights reserved.

Page 648 of 1869

Cloud Infinite

Flatten string
Format string
UrlList string
Prefix stringKey
string}type FileCompressResult struct {RegionstringBucketstringObjectstring}type FileProcessOutput struct {RegionBucketObjectstringstringstring}type NotifyConfigCallBackMqConfig struct {MqModestringMqRegion string
MqNamestring}Parameter

Description

Type

RequiredTag

Job type, which currently can only be
FileUncompress .

StringYes

The object to be processed. For more
Input

information, see Submitting Hash Calculation
Job.

Container

Yes

Operation

Operation ruleContainer

Yes

Operation.FileUncompressConfig

File decompression rule. For more information,see Submitting File Decompression Job.

Container

Yes

ContainerNo

Container

Yes

StringNo

File decompression result, which will not be
Operation.FileUncompressResult

returned when the job is not completed. For
more information, see Submitting File
Decompression Job.
Address where the output file is stored. For

Operation.Output

Operation.UserData

more information, see Submitting Multi-File
Zipping Job.
The user information passed through, which isprintable ASCII codes of up to 1,024 in length.

©2013-2022 Tencent Cloud. All rights reserved.

Page 649 of 1869

Cloud Infinite

QueueId

ID of the queue where the job is in.

StringYes

StringNo

StringNo

StringNo

ContainerNo

Job callback format, which can be JSON or
CallBackFormat

XML (default). It takes priority over that of
the queue.
Job callback type, which can be Url

CallBackType(default) or TDMQ . It takes priority over thatof the queue.

CallBack

CallBackMqConfig

Job callback address. It takes priority over thatof the queue.
TDMQ configuration for job callback as
described in Structure, which is required if
CallBackType is TDMQ .

Response description©2013-2022 Tencent Cloud. All rights reserved.

Page 650 of 1869

Cloud Infinite

type FileProcessJobResult struct {JobsDetail FileProcessJobResult}type FileProcessJobResult struct {CodestringMessagestringJobId
stringTag
stringStatestringCreationTime string
StartTimestring©2013-2022 Tencent Cloud. All rights reserved.

Page 651 of 1869

Cloud Infinite

EndTimeQueueId

stringstring

Input
Operation*FileProcessInput*FileProcessJobOperation}
Parameter

Description

Type

JobsDetailJob details

Container

CodeError code, which will be returned only if State is Failed .

StringMessage

Error message, which will be returned only if State is Failed .

String

JobId

Job ID

StringTag

Job tag: FileUncompress

StringState

Job status. Valid values: Submitted , Running , Success ,Failed , Pause , Cancel .

StringCreationTime

Job creation time

StringStartTimeJob start time

String

EndTimeJob end time

StringQueueId

ID of the queue where the job is in

String

Input

Path of the input file for this job. For more information, see
FileProcessJobOptions.Input .

Container

Operation

Operation rule. For more information, see
FileProcessJobOptions.Operation .

Container

Querying File Decompression Result
Feature description
This API is used to query the details of a file processing job by job ID.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 652 of 1869

Cloud Infinite

func (s *CIService) DescribeFileProcessJob(ctx context.Context, jobid string) (*Fil

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 653 of 1869

Cloud Infinite

jobid := "<jobid>"
res, _, err := c.CI.DescribeFileProcessJob(context.Background(), jobid)Parameter description
Parameter

Description

Type

RequiredjobidFile processing job ID

StringYes

Response description©2013-2022 Tencent Cloud. All rights reserved.

Page 654 of 1869

Cloud Infinite

type FileProcessJobResult struct {JobsDetail *FileProcessJobsDetail}Parameter
JobsDetail

Description
Job details, which is the same as Response.JobsDetail in theCreateFileProcessJob API.

©2013-2022 Tencent Cloud. All rights reserved.

Type
Container

Page 655 of 1869

Cloud Infinite©2013-2022 Tencent Cloud. All rights reserved.

Page 656 of 1869

Cloud Infinite

Multi-File Zipping：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for file compression in CI.
API

Description

Submitting a multi-file zipping job

Submits a multi-file zipping job.

Querying the multi-file zipping result

Queries the result of a specified multi-file zipping job.

Submitting a Multi-File Zipping Job
Feature description
The multi-file zipping feature uses a request to zip multiple files into a compressed file such as a ZIP file. You can
submit a job to zip multiple files and asynchronously return the compressed file.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 657 of 1869

Cloud Infinite

func (s *CIService) CreateFileProcessJob(ctx context.Context, opt *FileProcessJobOp

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 658 of 1869

Cloud Infinite

createJobOpt := &cos.FileProcessJobOptions{Tag: "FileCompress",
Operation: &cos.FileProcessJobOperation{
FileCompressConfig: &cos.FileCompressConfig{
Format: "zip",
Flatten: "0",Key:[]string{"1.mp3", "2.jpg"},},
Output: &cos.FileProcessOutput{
Region: "ap-shanghai",
Bucket: "test-1250000000",©2013-2022 Tencent Cloud. All rights reserved.

Page 659 of 1869

Cloud Infinite

Object: "vvvvxxxzz.zip",},},
QueueId: "p111a8dd208104ce3b11c78398f658ca8",}
res, _, err := c.CI.CreateFileProcessJob(context.Background(), createJobOpt)

Parameter description

type FileProcessJobOptions struct {XMLNamexml.Name©2013-2022 Tencent Cloud. All rights reserved.

Page 660 of 1869

Cloud Infinite

Tagstring
Input*FileProcessInput
Operation*FileProcessJobOperation
QueueId
stringCallBackFormat
stringCallBackType
stringCallBack
stringCallBackMqConfig *NotifyConfigCallBackMqConfig}
type FileProcessInput struct {RegionstringBucketstringObjectstring}type FileProcessJobOperation struct {FileHashCodeConfig*FileHashCodeConfig
FileHashCodeResult*FileHashCodeResult
FileUncompressConfig *FileUncompressConfig
FileUncompressResult *FileUncompressResult
FileCompressConfig*FileCompressConfig
FileCompressResult*FileCompressResult
Output*FileProcessOutput
UserData
string}type FileHashCodeConfig struct {Typestring
AddToHeader bool}
type FileHashCodeResult struct {MD5
stringSHA1stringSHA256
stringFileSizeint
LastModified string
Etag
string}type FileUncompressConfig struct {PrefixstringPrefixReplaced string}
type FileUncompressResult struct {RegionstringBucketstring
FileCount string}
type FileCompressConfig struct {Flatten string©2013-2022 Tencent Cloud. All rights reserved.

Page 661 of 1869

Cloud Infinite

Format string
UrlList string
Prefix stringKey[]string}
type FileCompressResult struct {RegionstringBucketstringObjectstring}type FileProcessOutput struct {RegionstringBucketstringObjectstring}type NotifyConfigCallBackMqConfig struct {MqModestringMqRegion string
MqNamestring}Parameter

Description

Type

RequiredTag

Job type, which currently can only be
FileCompress .

StringYes

The object to be processed. For more
Input

information, see Submitting Hash Calculation
Job.

Container

Yes

Operation

Operation ruleContainer

Yes

Operation.FileCompressConfig

File zipping rule. For more information, see
Submitting Multi-File Zipping Job.

Container

Yes

ContainerNo

Container

Yes

String

No

Operation.FileCompressResult

Multi-file zipping result, which will not be returned
when the job is not completed. For more
information, see Submitting Multi-File Zipping
Job.
Address where the output file is stored. For more

Operation.Output

Operation.UserData

information, see Submitting Multi-File ZippingJob.
The user information passed through, which isprintable ASCII codes of up to 1,024 in length.

©2013-2022 Tencent Cloud. All rights reserved.

Page 662 of 1869

Cloud Infinite

QueueId

ID of the queue where the job is in.

StringYes

StringNo

StringNo

StringNo

ContainerNo

Job callback format, which can be JSON or
CallBackFormat

XML (default). It takes priority over that of thequeue.
Job callback type, which can be Url (default)

CallBackTypeor TDMQ . It takes priority over that of thequeue.

CallBack

CallBackMqConfig

Job callback address. It takes priority over that of
the queue.
TDMQ configuration for job callback as
described in Structure, which is required if
CallBackType is TDMQ .

Response description©2013-2022 Tencent Cloud. All rights reserved.

Page 663 of 1869

Cloud Infinite

type FileProcessJobResult struct {JobsDetail FileProcessJobResult}type FileProcessJobResult struct {CodestringMessagestringJobId
stringTag
stringStatestringCreationTime string
StartTimestring©2013-2022 Tencent Cloud. All rights reserved.

Page 664 of 1869

Cloud Infinite

EndTimeQueueId

stringstring

Input
Operation*FileProcessInput*FileProcessJobOperation}
Parameter

Description

Type

JobsDetailJob details

Container

CodeError code, which will be returned only if State is Failed .

StringMessage

Error message, which will be returned only if State is Failed .

String

JobId

Job ID

StringTag

Job tag: FileCompress

StringState

Job status. Valid values: Submitted , Running , Success ,Failed , Pause , Cancel .

StringCreationTime

Job creation time

StringStartTimeJob start time

String

EndTimeJob end time

StringQueueId

ID of the queue where the job is in

String

Input

Path of the input file for this job. For more information, see
FileProcessJobOptions.Input .

Container

Operation

Operation rule. For more information, see
FileProcessJobOptions.Operation .

Container

Querying Multi-File Zipping Result
Feature description
This API is used to query the details of a file processing job by job ID.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 665 of 1869

Cloud Infinite

func (s *CIService) DescribeFileProcessJob(ctx context.Context, jobid string) (*Fil

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 666 of 1869

Cloud Infinite

jobid := "<jobid>"
res, _, err := c.CI.DescribeFileProcessJob(context.Background(), jobid)Parameter description
Parameter

Description

Type

RequiredjobidFile processing job ID

StringYes

Response description©2013-2022 Tencent Cloud. All rights reserved.

Page 667 of 1869

Cloud Infinite

type FileProcessJobResult struct {JobsDetail *FileProcessJobsDetail}Parameter
JobsDetail

Description
Job details, which is the same as Response.JobsDetail in theCreateFileProcessJob API.

©2013-2022 Tencent Cloud. All rights reserved.

Type
Container

Page 668 of 1869

Cloud Infinite©2013-2022 Tencent Cloud. All rights reserved.

Page 669 of 1869

Cloud Infinite

Hash Calculation：

Last updated 2024-02-29 16:52:32

Overview
This document provides an overview of APIs and SDK code samples for hash calculation in CI.
API

Description

Submitting a sync request for hashcalculation

Uses a sync request to perform hash calculation and return a calculated
hash value in real time.

Submitting a hash calculation job

Submits a hash calculation job.

Querying the hash calculation
resultQueries the result of a specified hash calculation job.

Sync Request for Hash Calculation
Feature description
This API uses a sync request to perform hash calculation and return a calculated hash value.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 670 of 1869

Cloud Infinite

func (s *CIService) GetFileHash(ctx context.Context, name string, opt *GetFileHashO

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 671 of 1869

Cloud Infinite

opt := &cos.GetFileHashOptions{
CIProcess: "filehash",Type:"md5",}
res, _, err := c.CI.GetFileHash(context.Background(), "test.jpg", opt)

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 672 of 1869

Cloud Infinite

type GetFileHashOptions struct {CIProcessstringTypestring
AddToHeader bool}
Parameter

Description

Type

Required

name

Full path of the file to be operated on

StringYes

CIProcessOperation type. It is fixed at filehash for hash calculation.

StringYes©2013-2022 Tencent Cloud. All rights reserved.

Page 673 of 1869

Cloud Infinite

Type

AddToHeader

Supported hash algorithm. Valid values: md5 , sha1 ,sha256 .
Whether to automatically add the calculated hash value to thecustom header in the file. Format: x-cos-meta-md5/sha1/sha256.
Valid values: true , false . If this parameter is left empty, it isString

Yes

Bool

No

false by default.

Response description©2013-2022 Tencent Cloud. All rights reserved.

Page 674 of 1869

Cloud Infinite

type GetFileHashResult struct {FileHashCodeResult *FileHashCodeResult
Input*FileProcessInput}
Parameter

Description

Type

FileHashCodeResult

Hash calculation result. For more information, see
FileProcessJobOptions.Input .

Container

Input

Basic information of the input file. For more information, see
FileProcessJobOptions.Operation.FileHashCodeResult .

Container

Submitting a Hash Calculation Job
Feature description
This API is used to submit a job to perform hash calculation and asynchronously return a calculated hash value.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 675 of 1869

Cloud Infinite

func (s *CIService) CreateFileProcessJob(ctx context.Context, opt *FileProcessJobOp

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 676 of 1869

Cloud Infinite

createJobOpt := &cos.FileProcessJobOptions{Tag: "FileHashCode",
Input: &cos.FileProcessInput{
Object: "294028.zip",},
Operation: &cos.FileProcessJobOperation{
FileHashCodeConfig: &cos.FileHashCodeConfig{Type:"sha1",
AddToHeader: true,},},©2013-2022 Tencent Cloud. All rights reserved.

Page 677 of 1869

Cloud Infinite

QueueId: "p111a8dd208104ce3b11c78398f658ca8",}
res, _, err := c.CI.CreateFileProcessJob(context.Background(), createJobOpt)

Parameter description

type FileProcessJobOptions struct {XMLNamexml.NameTagstring
Input*FileProcessInput
Operation*FileProcessJobOperation©2013-2022 Tencent Cloud. All rights reserved.

Page 678 of 1869

Cloud Infinite

QueueId
stringCallBackFormat
stringCallBackType
stringCallBack
stringCallBackMqConfig *NotifyConfigCallBackMqConfig}
type FileProcessInput struct {RegionstringBucketstringObjectstring}type FileProcessJobOperation struct {FileHashCodeConfig*FileHashCodeConfig
FileHashCodeResult*FileHashCodeResult
FileUncompressConfig *FileUncompressConfig
FileUncompressResult *FileUncompressResult
FileCompressConfig
FileCompressResult
OutputUserData*FileCompressConfig*FileCompressResult*FileProcessOutput
string}type FileHashCodeConfig struct {Typestring
AddToHeader bool}
type FileHashCodeResult struct {MD5
stringSHA1stringSHA256
stringFileSizeint
LastModified string
Etag
string}type FileUncompressConfig struct {PrefixstringPrefixReplaced string}
type FileUncompressResult struct {RegionstringBucketstring
FileCount string}
type FileCompressConfig struct {Flatten string
Format string
UrlList string
Prefixstring©2013-2022 Tencent Cloud. All rights reserved.

Page 679 of 1869

Cloud InfiniteKeystring}type FileCompressResult struct {RegionstringBucketstringObjectstring}type FileProcessOutput struct {RegionstringBucketObjectstringstring}type NotifyConfigCallBackMqConfig struct {MqModestringMqRegion string
MqNamestring}Parameter

Description

Type

RequiredTag

Job type, which currently can only be
FileHashCode .

StringYes

The object to be processed. For more
Input

information, see Submitting Hash Calculation
Job.

Container

Yes

Operation

Operation ruleContainer

Yes

Operation.FileHashCodeConfig

Hash calculation rule. For more information, see
Submitting Hash Calculation Job.

Container

Yes

ContainerNo

The calculated hash value, which will not be
Operation.FileHashCodeResult

returned when the job is not completed. For more
information, see Submitting Hash Calculation
Job.

Operation.UserData

The user information passed through, which isprintable ASCII codes of up to 1,024 in length.

String

No

QueueId

ID of the queue where the job is in.

StringYes

StringNo

StringNo

Job callback format, which can be JSON or
CallBackFormat

XML (default). It takes priority over that of thequeue.

CallBackType

Job callback type, which can be Url (default)©2013-2022 Tencent Cloud. All rights reserved.

Page 680 of 1869

Cloud Infinite

or TDMQ . It takes priority over that of thequeue.
CallBack

Job callback address. It takes priority over that of
the queue.

StringNo

Container

No

TDMQ configuration for job callback as
CallBackMqConfig

described in Structure, which is required if
CallBackType is TDMQ .

Response description©2013-2022 Tencent Cloud. All rights reserved.

Page 681 of 1869

Cloud Infinite

type FileProcessJobResult struct {JobsDetail FileProcessJobResult}type FileProcessJobResult struct {CodestringMessagestringJobId
stringTag
stringStatestringCreationTime string
StartTimestring©2013-2022 Tencent Cloud. All rights reserved.

Page 682 of 1869

Cloud Infinite

EndTimeQueueId

stringstring

Input
Operation*FileProcessInput*FileProcessJobOperation}
Parameter

Description

Type

JobsDetailJob details

Container

CodeError code, which will be returned only if State is Failed .

StringMessage

Error message, which will be returned only if State is Failed .

String

JobId

Job ID

StringTag

Job tag: FileHashCode

StringState

Job status. Valid values: Submitted , Running , Success ,Failed , Pause , Cancel .

StringCreationTime

Job creation time

StringStartTimeJob start time

String

EndTimeJob end time

StringQueueId

ID of the queue where the job is in

String

Input

Path of the input file for this job. For more information, see
FileProcessJobOptions.Input .

Container

Operation

Operation rule. For more information, see
FileProcessJobOptions.Operation .

Container

Querying Hash Calculation Result
Feature description
This API is used to query the details of a file processing job by job ID.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 683 of 1869

Cloud Infinite

func (s *CIService) DescribeFileProcessJob(ctx context.Context, jobid string) (*Fil

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 684 of 1869

Cloud Infinite

jobid := "<jobid>"
res, _, err := c.CI.DescribeFileProcessJob(context.Background(), jobid)Parameter description
Parameter

Description

Type

jobid

File processing job ID

StringResponse description©2013-2022 Tencent Cloud. All rights reserved.

Page 685 of 1869

Cloud Infinite

type FileProcessJobResult struct {JobsDetail *FileProcessJobsDetail}Parameter
JobsDetail

Description
Job details, which is the same as Response.JobsDetail in
the CreateFileProcessJob API.

©2013-2022 Tencent Cloud. All rights reserved.

Type

RequiredContainer

Yes

Page 686 of 1869

Cloud Infinite©2013-2022 Tencent Cloud. All rights reserved.

Page 687 of 1869

Cloud Infinite

COS iOS SDKContent Moderation
Image Moderation：

Last updated 2024-02-29 16:06:23

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for image moderation.
API
Moderating single image

Description
Scans existing data stored in COS for pornographic, illegal, andadvertising images.

Batch moderating images

Moderates multiple images in batches.

Querying the image moderation job
resultQueries the result of the specified image moderation job.

SDK API References
For parameters and method description of all APIs in the SDK, see SDK API Reference.

Single Image Moderation
Feature description
This API ( QCloudSyncImageRecognitionRequest ) is used to submit an image moderation job. You canreceive the moderation result by setting the callback address or querying by JobId .
Note:©2013-2022 Tencent Cloud. All rights reserved.

Page 688 of 1869

Cloud Infinite

The COS iOS SDK version must be at least v6.0.9.
Sample request
Objective-C

QCloudSyncImageRecognitionRequest * request = [[QCloudSyncImageRecognitionRequest a// Bucket name in the format of BucketName-APPID
request.bucket = @"bucket";// File region©2013-2022 Tencent Cloud. All rights reserved.

Page 689 of 1869

Cloud Infinite

request.regionName = @"regionName";// Object key, i.e., the full path of a COS object. If the object is in a directory
request.object = @"***.jpg";// Moderation type, such as `porn` (pornography) and `ads` (advertising).
// You can select multiple types; for example, `detect-type=porn,ads` indicates to// You can use multiple parameters together, such as `QCloudRecognitionPorn | QClou
request.detectType = QCloudRecognitionPorn | QCloudRecognitionTerrorist | QCloudRec[request setFinishBlock:^(QCloudImageRecognitionResult * _Nullable result, NSError// `outputObject` is the moderation result. For detailed fields, see the API docume// `QCloudImageRecognitionResult` class}];[[QCloudCOSXMLService defaultCOSXML] SyncImageRecognition:request];

Note:
For more complete samples, visit GitHub.
Swift©2013-2022 Tencent Cloud. All rights reserved.

Page 690 of 1869

Cloud Infinite

let request : QCloudSyncImageRecognitionRequest = QCloudSyncImageRecognitionRequest// Bucket name in the format of BucketName-APPID
request.bucket = "bucket";// File region
request.regionName = "regionName";// Object key, i.e., the full path of a COS object. If the object is in a directory
request.object = "***.jpg";©2013-2022 Tencent Cloud. All rights reserved.

Page 691 of 1869

Cloud Infinite// Moderation type, such as `porn` (pornography) and `ads` (advertising).
// You can select multiple types; for example, `detect-type=porn,ads` indicates to// You can use multiple parameters together, such as `QCloudRecognitionPorn | QClou
request.detectType = QCloudRecognitionEnum(rawValue: QCloudRecognitionEnum.porn.raw
request.finishBlock = { (result, error) in// `outputObject` is the moderation result. For detailed fields, see the AP// `QCloudImageRecognitionResult` class}
QCloudCOSXMLService.defaultCOSXML().syncImageRecognition(request);
Note:
For more complete samples, visit GitHub.

Batch Image Moderation
Feature description
The batch image moderation API adopts a sync POST request method. You can use this API to perform content
moderation on multiple image files.
Note:
The COS iOS SDK version must be at least v6.0.9.
Sample request
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 692 of 1869

Cloud Infinite

QCloudBatchimageRecognitionRequest * request = [[QCloudBatchimageRecognitionRequest
request.bucket = @"bucket";// File region
request.regionName = @"regionName";
NSMutableArray * input = [NSMutableArray new];// The image object to be moderated
QCloudBatchRecognitionImageInfo * input1 = [QCloudBatchRecognitionImageInfo new];©2013-2022 Tencent Cloud. All rights reserved.

Page 693 of 1869

Cloud Infinite

input1.Object = @"***.jpg";[input addObject:input1];
QCloudBatchRecognitionImageInfo * input2 = [QCloudBatchRecognitionImageInfo new];
input2.Object = @"***.jpg";[input addObject:input2];// The array of image objects to be moderated
request.input = input;
request.detectType = QCloudRecognitionPorn | QCloudRecognitionTerrorist | QCloudRec[request setFinishBlock:^(QCloudBatchImageRecognitionResult * _Nullable result, NSE// `outputObject` is the moderation result. For detailed fields, see the API docume// `QCloudBatchImageRecognitionResult` class}];[[QCloudCOSXMLService defaultCOSXML] BatchImageRecognition:request];

Note:
For more complete samples, visit GitHub.
Swift©2013-2022 Tencent Cloud. All rights reserved.

Page 694 of 1869

Cloud Infinite

let request = QCloudBatchimageRecognitionRequest();request.bucket = "bucket";// File region
request.regionName = "regionName";// The image object to be moderated
let input1 = QCloudBatchRecognitionImageInfo();
input1.object = "***.jpg";
let input2 = QCloudBatchRecognitionImageInfo();©2013-2022 Tencent Cloud. All rights reserved.

Page 695 of 1869

Cloud Infinite

input2.object = "***.jpg";// The array of image objects to be moderated
request.input = [input1,input2];
request.detectType = QCloudRecognitionEnum(rawValue: QCloudRecognitionEnum.porn.raw
request.setFinish { outputObject, error in// `outputObject` is the moderation result. For detailed fields, see the API docume// `QCloudBatchImageRecognitionResult` class}
QCloudCOSXMLService.defaultCOSXML().batchImageRecognition(request);
Note:
For more complete samples, visit GitHub.

Querying Image Moderation Job Result
Feature description
This API ( QCloudGetImageRecognitionRequest ) is used to query the result of the specified sync or batch
image moderation job by JobId .
Note:
The COS iOS SDK version must be at least v6.0.9.
Sample request
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 696 of 1869

Cloud Infinite

QCloudGetImageRecognitionRequest * request = [[QCloudGetImageRecognitionRequest all// Bucket name in the format of BucketName-APPID
request.bucket = @"examplebucket-1250000000";// File region
request.regionName = @"regionName";// The `jobid` of the sync or batch moderation job
request.jobId = @"jobid";©2013-2022 Tencent Cloud. All rights reserved.

Page 697 of 1869

Cloud Infinite

request.finishBlock = ^(QCloudImageRecognitionResult * outputObject, NSError *error// The moderation result `outputObject` contains the job ID used for query. For// `QCloudImageRecognitionResult` class};[[QCloudCOSXMLService defaultCOSXML] GetImageRecognition:request];
Note:
For more complete samples, visit GitHub.
Swift

let request = QCloudGetImageRecognitionRequest();©2013-2022 Tencent Cloud. All rights reserved.

Page 698 of 1869

Cloud Infinite// Bucket name in the format of BucketName-APPID
request.bucket = "examplebucket-1250000000";
request.regionName = "regionName";// The `jobid` of the sync or batch moderation job
request.jobId = "jobid";
request.setFinish { outputObject, error in// The moderation result `outputObject` contains the job ID used for query. For// `QCloudWebRecognitionResult` class};
QCloudCOSXMLService.defaultCOSXML().getImageRecognition(request);
Note:
For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 699 of 1869

Cloud Infinite

Video Moderation：

Last updated 2024-02-29 16:06:22

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for video moderation.
API

Description

Submitting a video moderation job

Submits a video moderation job.

Querying the video moderation job result

Queries the result of the specified video moderation job.

SDK API References
For parameters and method description of all APIs in the SDK, see SDK API Reference.

Creating a Task
Feature description
This API ( QCloudPostVideoRecognitionRequest ) is used to submit a video moderation job. You can receive
the moderation result by setting the callback address or querying by JobId .
Note:
The COS iOS SDK version must be at least v6.0.9.
Sample request
Objective-C
Swift©2013-2022 Tencent Cloud. All rights reserved.

Page 700 of 1869

Cloud Infinite

QCloudPostVideoRecognitionRequest * request = [[QCloudPostVideoRecognitionRequest a// Object key, i.e., the full path of a COS object. If the object is in a directory
request.object = @"exampleobject";// File region
request.regionName = @"regionName";// Bucket name in the format of BucketName-APPID
request.bucket = @"examplebucket-1250000000";©2013-2022 Tencent Cloud. All rights reserved.

Page 701 of 1869

Cloud Infinite// Moderation type, such as `porn` (pornography) and `ads` (advertising).
// You can select multiple types; for example, `detect-type=porn,ads` indicates to// You can use multiple parameters together, such as `QCloudRecognitionPorn | QClou
request.detectType = QCloudRecognitionPorn | QCloudRecognitionAds;// Frame capturing mode. Valid values: `Interval` (interval mode), `Average` (avera// `Interval` mode: The `TimeInterval` and `Count` parameters take effect. If `Coun// `Average` mode: The `Count` parameter takes effect, indicating to capture a tota// `Fps` mode: `TimeInterval` indicates how many frames to capture per second, andrequest.mode = QCloudVideoRecognitionModeFps;// Video frame capturing frequency. Value range: (0.000, 60.000] seconds. The value
request.timeInterval = 1;// The number of captured frames. Value range: (0, 10000].
request.count = 10;// Moderation policy. If this parameter is not specified, the default policy will brequest.bizType = @"BizType";// Specify whether to moderate video sound. Valid values: `0` (moderates the video
request.detectContent = YES;
request.finishBlock = ^(QCloudPostVideoRecognitionResult * outputObject, NSError *e// The moderation result `outputObject` contains the job ID used for query. For det// `QCloudPostVideoRecognitionResult` class};[[QCloudCOSXMLService defaultCOSXML] PostVideoRecognition:request];

Note: For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 702 of 1869

Cloud Infinite

let request : QCloudPostVideoRecognitionRequest = QCloudPostVideoRecognitionRequest// Object key, i.e., the full path of a COS object. If the object is in a directory
request.object = "exampleobject";// File region
request.regionName = "regionName";// Bucket name in the format of BucketName-APPID
request.bucket = "examplebucket-1250000000";©2013-2022 Tencent Cloud. All rights reserved.

Page 703 of 1869

Cloud Infinite// Moderation type, such as `porn` (pornography) and `ads` (advertising).
// You can select multiple types; for example, `detect-type=porn,ads` indicates to// You can use multiple parameters together, such as `QCloudRecognitionPorn | QClou
request.detectType = QCloudRecognitionEnum(rawValue: QCloudRecognitionEnum.porn.raw// Frame capturing mode. Valid values: `Interval` (interval mode), `Average` (avera// `Interval` mode: The `TimeInterval` and `Count` parameters take effect. If `Coun// `Average` mode: The `Count` parameter takes effect, indicating to capture a tota// `Fps` mode: `TimeInterval` indicates how many frames to capture per second, andrequest.mode = QCloudVideoRecognitionMode.fps;// Video frame capturing frequency. Value range: (0.000, 60.000] seconds. The value
request.timeInterval = 1;// The number of captured frames. Value range: (0, 10000].
request.count = 10;// Moderation policy. If this parameter is not specified, the default policy will brequest.bizType = "BizType";// Specify whether to moderate video sound. Valid values: `0` (moderates the video
request.detectContent = true;
request.finishBlock = { (result, error) in// The moderation result `outputObject` contains the job ID used for query.
// `QCloudPostVideoRecognitionResult` class}
QCloudCOSXMLService.defaultCOSXML().postVideoRecognition(request);
Note: For more complete samples, visit GitHub.

Querying Job
Feature description
This API ( QCloudGetVideoRecognitionRequest ) is used to query the result of the specified video moderation
job by job ID.
Note:
The COS iOS SDK version must be at least v6.0.9.
Sample request
Objective-C
Swift©2013-2022 Tencent Cloud. All rights reserved.

Page 704 of 1869

Cloud Infinite

QCloudGetVideoRecognitionRequest * request = [[QCloudGetVideoRecognitionRequest all// Bucket name in the format of BucketName-APPID
request.bucket = @"examplebucket-1250000000";// The `jobid` returned by the `QCloudPostVideoRecognitionRequest` API
request.jobId = @"jobid";[request setFinishBlock:^(QCloudVideoRecognitionResult * _Nullable result, NSError// The moderation result `outputObject` contains the job ID used for query. For// `QCloudVideoRecognitionResult` class}];©2013-2022 Tencent Cloud. All rights reserved.

Page 705 of 1869

Cloud Infinite[[QCloudCOSXMLService defaultCOSXML] GetVideoRecognition:request];

Note: For more complete samples, visit GitHub.

let request : QCloudGetVideoRecognitionRequest = QCloudGetVideoRecognitionRequest()// Bucket name in the format of BucketName-APPID
request.bucket = "examplebucket-1250000000";// The `jobid` returned by the `QCloudPostVideoRecognitionRequest` API
request.jobId = "jobid";©2013-2022 Tencent Cloud. All rights reserved.

Page 706 of 1869

Cloud Infinite

request.finishBlock = { (result, error) in// The moderation result `outputObject` contains the job ID used for query. For// `QCloudVideoRecognitionResult` class}
QCloudCOSXMLService.defaultCOSXML().getVideoRecognition(request);
Note: For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 707 of 1869

Cloud Infinite

Audio Moderation：

Last updated 2024-02-29 16:06:22

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for audio moderation.
API

Description

Submitting an audio moderation job

Submits an audio moderation job.

Querying the audio moderation job result

Queries the result of the specified audio moderation job.

Creating a Task
Feature description
This API ( QCloudPostAudioRecognitionRequest ) is used to submit an audio moderation job. You canreceive the moderation result by setting the callback address or querying by JobId .
Note:
The COS iOS SDK version must be at least v6.0.9.
Sample request
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 708 of 1869

Cloud Infinite

QCloudPostAudioRecognitionRequest * request = [[QCloudPostAudioRecognitionRequest a// Object key, i.e., the full path of a COS object. If the object is in a directory
request.object = @"exampleobject";// File region
request.regionName = @"regionName";// Bucket name in the format of BucketName-APPID
request.bucket = @"examplebucket-1250000000";©2013-2022 Tencent Cloud. All rights reserved.

Page 709 of 1869

Cloud Infinite// Moderation type, such as `porn` (pornography), `terrorist` (terrorism), `politic// You can select multiple types; for example, `detect-type=porn,ads` indicates to// You can use multiple parameters together, such as `QCloudRecognitionPorn | QClou
request.detectType = QCloudRecognitionPorn | QCloudRecognitionAds;
request.bizType = BizType;request.finishBlock = ^(QCloudPostAudioRecognitionResult * outputObject, NSError *e// The moderation result `outputObject` contains the job ID used for query. For// `QCloudPostAudioRecognitionResult` class};[[QCloudCOSXMLService defaultCOSXML] PostAudioRecognition:request];
Note:
For more complete samples, visit GitHub.
Swift©2013-2022 Tencent Cloud. All rights reserved.

Page 710 of 1869

Cloud Infinite

let request = QCloudPostAudioRecognitionRequest();// Object key, i.e., the full path of a COS object. If the object is in a directory
request.object = "exampleobject";// File region
request.regionName = "regionName";// Bucket name in the format of BucketName-APPID
request.bucket = "examplebucket-1250000000";©2013-2022 Tencent Cloud. All rights reserved.

Page 711 of 1869

Cloud Infinite// Moderation type, such as `porn` (pornography), `terrorist` (terrorism), `politic// You can select multiple types; for example, `detect-type=porn,ads` indicates to// You can use multiple parameters together, such as `QCloudRecognitionPorn | QClou
request.detectType = QCloudRecognitionEnum(rawValue: QCloudRecognitionEnum.porn.raw
request.bizType = BizType;request.setFinish { outputObject, error in// The moderation result `outputObject` contains the job ID used for query. For// `QCloudPostAudioRecognitionResult` class};
QCloudCOSXMLService.defaultCOSXML().postAudioRecognition(request);
Note:
For more complete samples, visit GitHub.

Querying Job
Feature description
This API ( QCloudGetAudioRecognitionRequest ) is used to query the result of the specified audio
moderation job by JobId .
Note:
The COS iOS SDK version must be at least v6.0.9.
Sample request
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 712 of 1869

Cloud Infinite

QCloudGetAudioRecognitionRequest * request = [[QCloudGetAudioRecognitionRequest all// Bucket name in the format of BucketName-APPID
request.bucket = @"examplebucket-1250000000";// File region
request.regionName = @"regionName";// The `jobid` returned by the `QCloudPostAudioRecognitionRequest` API
request.jobId = @"jobid";©2013-2022 Tencent Cloud. All rights reserved.

Page 713 of 1869

Cloud Infinite

request.finishBlock = ^(QCloudAudioRecognitionResult * outputObject, NSError *error// The moderation result `outputObject` contains the job ID used for query. For// `QCloudAudioRecognitionResult` class};[[QCloudCOSXMLService defaultCOSXML] GetAudioRecognition:request];
Note:
For more complete samples, visit GitHub.
Swift

let request = QCloudGetAudioRecognitionRequest();©2013-2022 Tencent Cloud. All rights reserved.

Page 714 of 1869

Cloud Infinite// Bucket name in the format of BucketName-APPID
request.bucket = "examplebucket-1250000000";// File region
request.regionName = "regionName";// The `jobid` returned by the `QCloudPostAudioRecognitionRequest` API
request.jobId = "jobid";
request.setFinish { outputObject, error in// The moderation result `outputObject` contains the job ID used for query. For// `QCloudAudioRecognitionResult` class}
QCloudCOSXMLService.defaultCOSXML().getAudioRecognition(request);
Note:
For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 715 of 1869

Cloud Infinite

Text Moderation：

Last updated 2024-02-29 16:06:23

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for text moderation.
API

Description

Submitting a text moderation job

Submits a text moderation job.

Querying the text moderation job result

Queries the result of the specified text moderation job.

SDK API References
For parameters and method description of all APIs in the SDK, see SDK API Reference.

Creating a Task
Feature description
This API ( QCloudPostTextRecognitionRequest ) is used to submit a text moderation job. You can receive
the moderation result by setting the callback address or querying by JobId .
Note:
The COS iOS SDK version must be at least v6.0.9.
Sample request
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 716 of 1869

Cloud Infinite

QCloudPostTextRecognitionRequest * request = [[QCloudPostTextRecognitionRequest all// Object key, i.e., the full path of a COS object. If the object is in a directory
request.object = @"exampleobject";// Bucket name in the format of BucketName-APPID
request.bucket = @"examplebucket-1250000000";// File region
request.regionName = @"regionName";©2013-2022 Tencent Cloud. All rights reserved.

Page 717 of 1869

Cloud Infinite// Moderation type, such as `porn` (pornography), `terrorist` (terrorism), `politic// You can select multiple types; for example, `detect-type=porn,ads` indicates to// You can use multiple parameters together, such as `QCloudRecognitionPorn | QClou
request.detectType = QCloudRecognitionPorn | QCloudRecognitionAds | QCloudRecogniti// Moderation policy. If this parameter is not specified, the default policy will brequest.bizType = BizType;request.finishBlock = ^(QCloudPostTextRecognitionResult * outputObject, NSError *er// The moderation result `outputObject` contains the job ID used for query. For// `QCloudPostTextRecognitionResult` class};[[QCloudCOSXMLService defaultCOSXML] PostTextRecognition:request];
Note:
For more complete samples, visit GitHub.
Swift©2013-2022 Tencent Cloud. All rights reserved.

Page 718 of 1869

Cloud Infinite

let request = QCloudPostTextRecognitionRequest();// Object key, i.e., the full path of a COS object. If the object is in a directory
request.object = "exampleobject";// Bucket name in the format of BucketName-APPID
request.bucket = "examplebucket-1250000000";// File region
request.regionName = "regionName";©2013-2022 Tencent Cloud. All rights reserved.

Page 719 of 1869

Cloud Infinite// Moderation type, such as `porn` (pornography), `terrorist` (terrorism), `politic// You can select multiple types; for example, `detect-type=porn,ads` indicates to// You can use multiple parameters together, such as `QCloudRecognitionPorn | QClou
request.detectType = QCloudRecognitionEnum(rawValue: QCloudRecognitionEnum.porn.raw// Moderation policy. If this parameter is not specified, the default policy will brequest.setFinish { outputObject, error in// The moderation result `outputObject` contains the job ID used for query. For// `QCloudPostTextRecognitionResult` class}
QCloudCOSXMLService.defaultCOSXML().postTextRecognition(request);
Note:
For more complete samples, visit GitHub.

Querying Job
Feature description
This API ( QCloudGetTextRecognitionRequest ) is used to query the result of the specified text moderation
job by JobId .
Note:
The COS iOS SDK version must be at least v6.0.9.
Sample request
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 720 of 1869

Cloud Infinite

QCloudGetTextRecognitionRequest * request = [[QCloudGetTextRecognitionRequest alloc// Bucket name in the format of BucketName-APPID
request.bucket = @"examplebucket-1250000000";// File region
request.regionName = @"regionName";// The `jobid` returned by the `QCloudPostTextRecognitionRequest` API
request.jobId = @"jobid";©2013-2022 Tencent Cloud. All rights reserved.

Page 721 of 1869

Cloud Infinite

request.finishBlock = ^(QCloudTextRecognitionResult * outputObject, NSError *error)// The moderation result `outputObject` contains the job ID used for query. For// `QCloudTextRecognitionResult` class};[[QCloudCOSXMLService defaultCOSXML] GetTextRecognition:request];
Note:
For more complete samples, visit GitHub.
Swift

let request = QCloudGetTextRecognitionRequest();©2013-2022 Tencent Cloud. All rights reserved.

Page 722 of 1869

Cloud Infinite// Bucket name in the format of BucketName-APPID
request.bucket = "examplebucket-1250000000";// File region
request.regionName = "regionName";// The `jobid` returned by the `QCloudPostTextRecognitionRequest` API
request.jobId = "jobid";
request.setFinish { outputObject, error in// The moderation result `outputObject` contains the job ID used for query. For// `QCloudTextRecognitionResult` class};
QCloudCOSXMLService.defaultCOSXML().getTextRecognition(request);
Note:
For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 723 of 1869

Cloud Infinite

File Moderation：

Last updated 2024-02-29 16:06:23

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for file moderation.
API

Description

Submitting a file moderation job

Submits a file moderation job.

Querying the file moderation job result

Queries the result of the specified file moderation job.

SDK API References
For parameters and method description of all APIs in the SDK, see SDK API Reference.

Creating a Task
Feature description
This API ( QCloudPostDocRecognitionRequest ) is used to submit a file moderation job. You can receive themoderation result by setting the callback address or querying by JobId .
Note:
The COS iOS SDK version must be at least v6.0.9.
Sample request
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 724 of 1869

Cloud Infinite

QCloudPostDocRecognitionRequest * request = [[QCloudPostDocRecognitionRequest alloc// Object key, i.e., the full path of a COS object. If the object is in a directory
request.object = @"exampleobject";// File region
request.regionName = @"regionName";// Bucket name in the format of BucketName-APPID
request.bucket = @"examplebucket-1250000000";©2013-2022 Tencent Cloud. All rights reserved.

Page 725 of 1869

Cloud Infinite

request.type = @"doc";// Moderation type, such as `porn` (pornography), `terrorist` (terrorism), `politic// You can select multiple types; for example, `detect-type=porn,ads` indicates to// You can use multiple parameters together, such as `QCloudRecognitionPorn | QClou
request.detectType = QCloudRecognitionPorn | QCloudRecognitionAds | QCloudRecogniti// Moderation policy. If this parameter is not specified, the default policy will brequest.bizType = BizType;request.finishBlock = ^(QCloudPostDocRecognitionResult * outputObject, NSError *err// The moderation result `outputObject` contains the job ID used for query. For// `QCloudPostDocRecognitionResult` class};[[QCloudCOSXMLService defaultCOSXML] PostDocRecognition:request];
Note:
For more complete samples, visit GitHub.
Swift©2013-2022 Tencent Cloud. All rights reserved.

Page 726 of 1869

Cloud Infinite

let request = QCloudPostDocRecognitionRequest();// Object key, i.e., the full path of a COS object. If the object is in a directory
request.object = "exampleobject";// File region
request.regionName = "regionName";// Bucket name in the format of BucketName-APPID
request.bucket = "examplebucket-1250000000";©2013-2022 Tencent Cloud. All rights reserved.

Page 727 of 1869

Cloud Infinite

request.type = "doc";// Moderation type, such as `porn` (pornography), `terrorist` (terrorism), `politic// You can select multiple types; for example, `detect-type=porn,ads` indicates to// You can use multiple parameters together, such as `QCloudRecognitionPorn | QClou
request.detectType = QCloudRecognitionEnum(rawValue: QCloudRecognitionEnum.porn.raw// Moderation policy. If this parameter is not specified, the default policy will brequest.setFinish { outputObject, error in// The moderation result `outputObject` contains the job ID used for query. For// `QCloudPostDocRecognitionResult` class}
QCloudCOSXMLService.defaultCOSXML().postDocRecognition(request);
Note:
For more complete samples, visit GitHub.

Querying Job
Feature description
This API ( QCloudGetDocRecognitionRequest ) is used to query the result of the specified file moderation job
by JobId .
Note:
The COS iOS SDK version must be at least v6.0.9.
Sample request
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 728 of 1869

Cloud Infinite

QCloudGetDocRecognitionRequest * request = [[QCloudGetDocRecognitionRequest alloc]i// Bucket name in the format of BucketName-APPID
request.bucket = @"examplebucket-1250000000";// File region
request.regionName = @"regionName";// The `jobid` returned by the `QCloudPostDocRecognitionRequest` API
request.jobId = @"jobid";©2013-2022 Tencent Cloud. All rights reserved.

Page 729 of 1869

Cloud Infinite

request.finishBlock = ^(QCloudDocRecognitionResult * outputObject, NSError *error)// The moderation result `outputObject` contains the job ID used for query. For// `QCloudDocRecognitionResult` class};[[QCloudCOSXMLService defaultCOSXML] GetDocRecognition:request];
Note:
For more complete samples, visit GitHub.
Swift

let request = QCloudGetDocRecognitionRequest();©2013-2022 Tencent Cloud. All rights reserved.

Page 730 of 1869

Cloud Infinite// Bucket name in the format of BucketName-APPID
request.bucket = "examplebucket-1250000000";// File region
request.regionName = "regionName";// The `jobid` returned by the `QCloudPostDocRecognitionRequest` API
request.jobId = "jobid";
request.setFinish { outputObject, error in// The moderation result `outputObject` contains the job ID used for query. For// `QCloudDocRecognitionResult` class};
QCloudCOSXMLService.defaultCOSXML().getDocRecognition(request);
Note:
For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 731 of 1869

Cloud Infinite

Webpage Moderation：

Last updated 2024-02-29 16:06:23

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for webpage moderation.
API

Description

Submitting a webpage moderation job

Submits a webpage moderation job.

Querying the webpage moderation job result

Queries the result of the specified webpage moderation job.

SDK API References
For parameters and method description of all APIs in the SDK, see SDK API Reference.

Creating a Task
Feature description
This API ( QCloudPostWebRecognitionRequest ) is used to submit a webpage moderation job. The job can bequeried by JobId .
Note:
The COS iOS SDK version must be at least v6.0.9.
Sample request
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 732 of 1869

Cloud Infinite

QCloudPostWebRecognitionRequest * request = [[QCloudPostWebRecognitionRequest alloc// Bucket name in the format of BucketName-APPID
request.bucket = @"examplebucket-1250000000";// File region
request.regionName = @"regionName";request.url = @"www.****.com";// Moderation type, such as `porn` (pornography), `terrorist` (terrorism), `politic// You can select multiple types; for example, `detect-type=porn,ads` indicates to©2013-2022 Tencent Cloud. All rights reserved.

Page 733 of 1869

Cloud Infinite// You can use multiple parameters together, such as `QCloudRecognitionPorn | QClou
request.detectType = QCloudRecognitionPorn | QCloudRecognitionAds | QCloudRecogniti// Moderation policy. If this parameter is not specified, the default policy will brequest.bizType = BizType;request.finishBlock = ^(QCloudPostWebRecognitionResult * outputObject, NSError *err// The moderation result `outputObject` contains the job ID used for query. For// `QCloudPostTextRecognitionResult` class};[[QCloudCOSXMLService defaultCOSXML] PostWebRecognition:request];
Note:
For more complete samples, visit GitHub.
Swift©2013-2022 Tencent Cloud. All rights reserved.

Page 734 of 1869

Cloud Infinite

let request = QCloudPostWebRecognitionRequest();// Object key, i.e., the full path of a COS object. If the object is in a directory
request.url = "www.***.com";// File region
request.regionName = "regionName";// Bucket name in the format of BucketName-APPID
request.bucket = "examplebucket-1250000000";©2013-2022 Tencent Cloud. All rights reserved.

Page 735 of 1869

Cloud Infinite// Moderation type, such as `porn` (pornography), `terrorist` (terrorism), `politic// You can select multiple types; for example, `detect-type=porn,ads` indicates to// You can use multiple parameters together, such as `QCloudRecognitionPorn | QClou
request.detectType = QCloudRecognitionEnum(rawValue: QCloudRecognitionEnum.porn.raw// Moderation policy. If this parameter is not specified, the default policy will brequest.setFinish { outputObject, error in// The moderation result `outputObject` contains the job ID used for query. For// `QCloudPostTextRecognitionResult` class}
QCloudCOSXMLService.defaultCOSXML().postWebRecognition(request);
Note:
For more complete samples, visit GitHub.

Querying Job
Feature description
This API ( QCloudGetWebRecognitionRequest ) is used to query the result of the specified webpage
moderation job by JobId .
Note:
The COS iOS SDK version must be at least v6.0.9.
Sample request
Objective-C©2013-2022 Tencent Cloud. All rights reserved.

Page 736 of 1869

Cloud Infinite

QCloudGetWebRecognitionRequest * request = [[QCloudGetWebRecognitionRequest alloc]i// Bucket name in the format of BucketName-APPID
request.bucket = @"examplebucket-1250000000";// File region
request.regionName = @"regionName";// The `jobid` returned by the `QCloudPostWebRecognitionRequest` API
request.jobId = @"jobid";©2013-2022 Tencent Cloud. All rights reserved.

Page 737 of 1869

Cloud Infinite

request.finishBlock = ^(QCloudWebRecognitionResult * outputObject, NSError *error)// The moderation result `outputObject` contains the job ID used for query. For// `QCloudWebRecognitionResult` class};[[QCloudCOSXMLService defaultCOSXML] GetWebRecognition:request];
Note:
For more complete samples, visit GitHub.
Swift

let request = QCloudGetWebRecognitionRequest();©2013-2022 Tencent Cloud. All rights reserved.

Page 738 of 1869

Cloud Infinite// Bucket name in the format of BucketName-APPID
request.bucket = "examplebucket-1250000000";// File region
request.regionName = "regionName";// The `jobid` returned by the `QCloudPostWebRecognitionRequest` API
request.jobId = "jobid";
request.setFinish { outputObject, error in// The moderation result `outputObject` contains the job ID used for query. For// `QCloudWebRecognitionResult` class};
QCloudCOSXMLService.defaultCOSXML().getWebRecognition(request);
Note:
For more complete samples, visit GitHub.

©2013-2022 Tencent Cloud. All rights reserved.

Page 739 of 1869

Cloud Infinite

Java SDK
Getting Started：

Last updated 2024-02-29 17:31:27

Overview
CI's media processing and file preview APIs are integrated into the COS XML Java SDK.

Download and Installation
Relevant resources
Download the COS XML Java SDK source code here.
Download the XML Java SDK here.
Download the demo here.
For all the code samples, visit GitHub.
Environmental dependencies
The SDK supports JDK v1.8 and later.
For the JDK installation, see Java Installation and Configuration.
Note
For the definitions of terms such as SecretId , SecretKey , and bucket, see Introduction.
You can find common classes for the COS Java SDK in the following packages:
The classes related to client configuration are in the com.qcloud.cos.* package.
The classes related to permissions are in the com.qcloud.cos.auth.* sub-package.
The classes related to exceptions are in the com.qcloud.cos.exception.* sub-package.
The classes related to requests are in the com.qcloud.cos.model.* sub-package.
The classes related to regions are in the com.qcloud.cos.region.* sub-package.
The classes related to advanced APIs are in the com.qcloud.cos.transfer.* sub-package.
Installing SDK
You can install the Java SDK using Maven or source code:
Using Maven
Add required dependencies to the pom.xml file of your Maven project as follows:©2013-2022 Tencent Cloud. All rights reserved.

Page 740 of 1869

Cloud Infinite<dependency><groupId>com.qcloud</groupId><artifactId>cos_api</artifactId><version>5.6.133</version></dependency>
Note
Dependency coordinates may not be on the latest version. Click here to get the latest version.
Using source code
Download the source code from GitHub or here, and import it using Maven. For example, to import it into Eclipse,©2013-2022 Tencent Cloud. All rights reserved.

Page 741 of 1869

Cloud Infinite

select File > Import > Maven > Existing Maven Projects.
Uninstalling SDK
Uninstall the SDK by removing the POM dependencies or source code.

Directions
The section below describes how to use the Java SDK to perform basic operations, such as initializing a client,creating a bucket, querying a bucket list, uploading an object, querying an object list, downloading an object, ordeleting an object. CI's media processing APIs are integrated into the COS XML Java SDK, where you can perform
operations related to templates, jobs, workflows, and queues.

Importing classes
The COS Java SDK package is named com.qcloud.cos.* . You can import the classes required for running
your program through your IDE, such as Eclipse and IntelliJ.

Initializing the client
Before making any request for COS services, you need to generate a COSClient class object for calling the COS
APIs.
Note
COSClient is a thread-safe class that allows multi-thread access to the same instance. Because an instance maintains
a connection pool internally, creating multiple instances may lead to resource exhaustion. Make sure that there is
only one instance in the program lifecycle, and call the shutdown method to turn off the instance when it is nolonger needed. If you need to create a new instance, shut down the previous instance first.
If you use a permanent key to initialize COSClient, you need to obtain your SecretId and SecretKey on the API KeyManagement page in the CAM Console. A permanent key can be used for most application scenarios. Below is asample:©2013-2022 Tencent Cloud. All rights reserved.

Page 742 of 1869

Cloud Infinite// 1. Initialize the user credentials (secretId, secretKey).
String secretId = "COS_SECRETID";
String secretKey = "COS_SECRETKEY";
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);// 2. Set the bucket region. For abbreviations of COS regions, see https://www.tenc// `clientConfig` contains the set methods to set region, HTTPS (HTTP by default),
Region region = new Region("COS_REGION");
ClientConfig clientConfig = new ClientConfig(region);// 3. Generate a COS client.
COSClient cosClient = new COSClient(cred, clientConfig);©2013-2022 Tencent Cloud. All rights reserved.

Page 743 of 1869

Cloud Infinite

You can also use a temporary key to initialize the COSClient. For more information on how to generate and use atemporary key, see Generating and Using Temporary Keys. An example is shown below:// 1. Pass in the obtained temporary key (tmpSecretId, tmpSecretKey, sessionToken).
String tmpSecretId = "COS_SECRETID";
String tmpSecretKey = "COS_SECRETKEY";
String sessionToken = "COS_TOKEN";
BasicSessionCredentials cred = new BasicSessionCredentials(tmpSecretId, tmpSecretKe// 2. Set the bucket region. For abbreviations of COS regions, see https://www.tenc// `clientConfig` contains the set methods to set region, HTTPS (HTTP by default),
Region region = new Region("COS_REGION");©2013-2022 Tencent Cloud. All rights reserved.

Page 744 of 1869

Cloud Infinite

ClientConfig clientConfig = new ClientConfig(region);// 3. Generate a COS client
COSClient cosClient = new COSClient(cred, clientConfig);
The ClientConfig class is a configuration class containing the following main members:
Member Name

Setting Method

Description

TyperegionConstructor or set
methodBucket region. For the abbreviations of COS
regions, see Regions and Access Domain
Names.

Region

httpProtocol

Set method

The protocol used by the request. By default,
HTTP is used to interact with COS.

HttpProtocol

signExpired

Set method

Validity period (in seconds) of the request
signature. Default value: 3600 .

intconnectionTimeout

Set method

socketTimeout

Set method

Timeout period in milliseconds for the client toread data. Default value: 30000 .

int

httpProxyIp

Set method

Proxy server IP

String

httpProxyPort

Set method

Proxy server port

int

Timeout period in milliseconds for connection
with COS. Default value: 30000 .

int

Querying the list of buckets with media processing enabledThis API is used to query buckets with media processing enabled under the current account.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 745 of 1869

Cloud Infinite//1. Create a template request object
MediaBucketRequest request = new MediaBucketRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("examplebucket-1250000000");//3. Call the API to get the bucket response object
MediaBucketResponse response = client.describeMediaBuckets(request);

Creating a job
This API is used to create a media processing job.

©2013-2022 Tencent Cloud. All rights reserved.

Page 746 of 1869

Cloud Infinite

Sample request//1. Create a job request object
MediaJobsRequest request = new MediaJobsRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("examplebucket-1250000000");
request.setTag("Transcode");request.getInput().setObject("1.mp4");
request.getOperation().setTemplateId("t0e09a9456d4124542b1f0e44d501*****");
request.getOperation().getOutput().setBucket("examplebucket-1250000000");
request.getOperation().getOutput().setRegion("ap-chongqing");©2013-2022 Tencent Cloud. All rights reserved.

Page 747 of 1869

Cloud Infinite

request.getOperation().getOutput().setObject("2.mp4");
request.setQueueId("p9900025e4ec44b5e8225e70a521*****");//3. Call the API to get the job response object
MediaJobResponse response = client.createMediaJobs(request);

Canceling a job
Feature description
This API is used to cancel a job that is not in progress.

©2013-2022 Tencent Cloud. All rights reserved.

Page 748 of 1869

Cloud Infinite

MediaJobsRequest request = new MediaJobsRequest();request.setBucketName("examplebucket-1250000000");
request.setJobId("jae776cb4ec3011eab2cdd3817d4*****");
Boolean response = client.cancelMediaJob(request);

Querying a job
This API is used to query the details of a job by job ID.

//1. Create a job request object©2013-2022 Tencent Cloud. All rights reserved.

Page 749 of 1869

Cloud Infinite

MediaJobsRequest request = new MediaJobsRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("examplebucket-1250000000");
request.setJobId("j29a82fea08ba11ebb54bc9d1c05*****");//3. Call the API to get the job response object
MediaJobResponse response = client.describeMediaJob(request);

Querying job list
This API is used to query the list of jobs in the queue.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 750 of 1869

Cloud Infinite

MediaJobsRequest request = new MediaJobsRequest();request.setBucketName("examplebucket-1250000000");
request.setQueueId("p9900025e4ec44b5e8225e70a521*****");
request.setTag("Transcode");MediaListJobResponse response = client.describeMediaJobs(request);
List<MediaJobObject> jobsDetail = response.getJobsDetail();

Shutting down the client
Shut down the COSClient and release the server threads connected over HTTP with the following code:©2013-2022 Tencent Cloud. All rights reserved.

Page 751 of 1869

Cloud Infinite// Close the client (release server threads).
cosClient.shutdown();©2013-2022 Tencent Cloud. All rights reserved.

Page 752 of 1869

Cloud Infinite

FAQs：

Last updated 2024-02-29 17:31:27

What do I do if the client network is normal, while the access to COS over HTTP is very slow,
or the error message "Connection reset" is reported?
In some regions, ISPs may hijack COS endpoints. Therefore, we recommend you access COS over HTTPS.

What do I do if java.lang.NoSuchMethodError is reported when I run the SDK?
Cause: This is usually caused by a JAR package conflict. For example, if the JAR package the SDK depends on uses
method A, but the JAR package in the HttpClient library of your project does not have method A, then the HttpClient
library will be loaded in the runtime loading order, reporting NoSuchMethodError .
Solution:
Solution 1: Change the version of the package in your project that has caused NoSuchMethodError to theversion of the corresponding library in pom.xml in the SDK.
Solution 2: Replace cos-java-sdk with cos_api-bundle . In this case, all dependencies of cos-javasdk are installed independently, so more space will be used.

©2013-2022 Tencent Cloud. All rights reserved.

Page 753 of 1869

Cloud Infinite<groupId>com.qcloud</groupId><artifactId>cos_api-bundle</artifactId><version>5.6.35</version>

What is the default timeout duration of the Java SDK?
Both the default connection and read/write timeout periods of the Java SDK are 30,000 ms. You can use the
SetConnectionTimeoutMs and setSocketTimeout methods in the SDK to adjust them respectively.

©2013-2022 Tencent Cloud. All rights reserved.

Page 754 of 1869

Cloud Infinite

What do I do if the upload with the Java SDK is slow and IOException is frequently
printed in the log?
Troubleshoot the problem as follows:
1. Check whether you are accessing COS over the public network.
Currently, CVM instances in the same region as COS generally access COS over the private network (the IP ranges
resolved by the private endpoint are 10, 100, and 169). For more information on COS endpoints, see Regions andAccess Endpoints. If the public network is used, check whether the egress bandwidth is too small or whether
bandwidth resources are occupied by other programs.
2. Check that the logs in the production environment are not set to DEBUG level. The INFO level is recommended.
3. If IOException is printed in WARN logs, it can be ignored, and the SDK will retry. IOException may becaused by a slow network connection. For solutions, see steps 1 and 2 above.

What do I do if there is a plus sign (+) in the requested upload path, throwing "403SignatureDoesNotMatch"?
Possible cause: The version of HttpClient in the Java environment leads to a URL-encoding error.
Solution:
Solution 1: Use HttpClient 4.5.3.

©2013-2022 Tencent Cloud. All rights reserved.

Page 755 of 1869

Cloud Infinite<groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.3</version>
Solution 2: Replace cos-java-sdk with cos_api-bundle . In this case, all dependencies of cos-javasdk are installed independently, so more space will be used.

©2013-2022 Tencent Cloud. All rights reserved.

Page 756 of 1869

Cloud Infinite<groupId>com.qcloud</groupId><artifactId>cos_api-bundle</artifactId><version>5.6.35</version>

What should I do if the Java SDK reports an error indicating that a certain dependency
version is too low?
Cause: The dependency version of your Java environment conflicts with that required by the Java SDK.
Solution:©2013-2022 Tencent Cloud. All rights reserved.

Page 757 of 1869

Cloud Infinite

Solution 1: Upgrade the dependency to the required version as prompted.
Solution 2: Replace cos-java-sdk with cos_api-bundle . In this case, all dependencies of cos-javasdk are installed independently, so more space will be used.

<groupId>com.qcloud</groupId><artifactId>cos_api-bundle</artifactId><version>5.6.35</version>

How do I create a COS file directory in the SDK?

©2013-2022 Tencent Cloud. All rights reserved.

Page 758 of 1869

Cloud Infinite

In COS, both files and directories are objects, where directories are objects that end with / . When creating a file,
you don't need to create a directory. For example, when you create a file with the object key ofxxx/yyy/zzz.txt , set the key to xxx/yyy/zzz.txt instead of creating the object xxx/yyy/ .
Directories are separated by / to show the hierarchy when displayed in the console. To create a directory object,
use the following sample code:

String bucketName = "examplebucket-1250000000";
String key = "folder/images/";// A directory object is an empty file that ends with /, where a byte stream with a
InputStream input = new ByteArrayInputStream(new byte[0]);©2013-2022 Tencent Cloud. All rights reserved.

Page 759 of 1869

Cloud Infinite

ObjectMetadata objectMetadata = new ObjectMetadata();objectMetadata.setContentLength(0);PutObjectRequest putObjectRequest =new PutObjectRequest(bucketName, key, input, objectMetadata);
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

How do I use HTTPS in the SDK?
In the SDK, relevant configuration items are put in the ClientConfig class. Below is the sample code:©2013-2022 Tencent Cloud. All rights reserved.

Page 760 of 1869

Cloud Infinite// Initialize user authentication information (`secretId` and `secretKey`).
String secretId = "COS_SECRETID";
String secretKey = "COS_SECRETKEY";
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);// Set the bucket region. For abbreviations of COS regions, please visit https://wwClientConfig clientConfig = new ClientConfig(new Region("ap-beijing-1"));// Configure HTTPS.
clientConfig.setHttpProtocol(HttpProtocol.https);// Generate a COS client.
COSClient cosClient = new COSClient(cred, clientConfig);

How do I use a proxy in the SDK?
If you need to use a proxy to access COS or CI, you can configure a proxy IP (or domain name) and port in the
ClientConfig class. Below is the sample code:©2013-2022 Tencent Cloud. All rights reserved.

Page 761 of 1869

Cloud Infinite// Initialize user authentication information (`secretId` and `secretKey`).
String secretId = "COS_SECRETID";
String secretKey = "COS_SECRETKEY";
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);// Set the bucket region. For abbreviations of COS regions, please visit https://wwClientConfig clientConfig = new ClientConfig(new Region("ap-beijing-1"));// Configure a proxy (both the IP and port need to be set).
// Set the proxy IP (or pass an endpoint).
clientConfig.setHttpProxyIp("192.168.2.3");// Set the proxy port.
clientConfig.setHttpProxyPort(8080);©2013-2022 Tencent Cloud. All rights reserved.

Page 762 of 1869

Cloud Infinite// Generate a COS client.
COSClient cosClient = new COSClient(cred, clientConfig);

How do I set up custom EndpointBuilder ?
In scenarios where the endpoint needs to be specified for an API request, you need to implement thebuildGeneralApiEndpoint and buildGetServiceApiEndpoint functions in the
EndpointBuilder API to specify the remote endpoints for general API requests and GETService requests
respectively. Below is the sample code:©2013-2022 Tencent Cloud. All rights reserved.

Page 763 of 1869

Cloud Infinite// Step 1. Implement the two functions in the EndpointBuilder API.
class SelfDefinedEndpointBuilder implements EndpointBuilder {@Override
public String buildGeneralApiEndpoint(String bucketName) {return String.format("%s.%s", bucketName, "mytest.com");}@Override
public String buildGetServiceApiEndpoint() {return "service.mytest.com";}}// Step 2. Initialize the client.
String secretId = "COS_SECRETID";
String secretKey = "COS_SECRETKEY";
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
SelfDefinedEndpointBuilder selfDefinedEndpointBuilder = new SelfDefinedEndpointBuil
ClientConfig clientConfig = new ClientConfig(new Region("ap-beijing"));clientConfig .setEndpointBuilder(selfDefinedEndpointBuilder);COSClient cosClient = new COSClient(cred, clientConfig);

Do I need to add the / prefix to key values used in SDK operations such as upload,
download, and batch delete?
The key value does not need to be prefixed with / for COS objects. For example, if you set the key value of a COS
object to exampleobject , you can access it using the http://cos.apguangzhou.myqcloud.com/exampleobject URL.
Note:
Do not pass in a key prefixed with / in a batch deletion request; otherwise, object deletion will fail.

What should I do if the error message "please make sure bucket name must contain legal
appid when appid is missing. example: bucektname-1250000000" is reported when I use theJava SDK to upload files?
COS Java SDK on an earlier version supports only APPID values starting with 125. If you are using an APPID startingwith 130, we recommend you update the SDK to the latest version. For more information on how to download andinstall the Java SDK, see Getting Started.

What should I do if the Java SDK reports an error when I upload large files?
To upload files larger than 5 GB by using the Java SDK, we recommend you use the advanced upload API. It
automatically determines whether to use simple or multipart upload based on the length and data type of your file.

©2013-2022 Tencent Cloud. All rights reserved.

Page 764 of 1869

Cloud Infinite

How do I obtain the file upload progress in the Java SDK?
To get the file upload progress, we recommend you use the advanced upload API. You can use thegetProgress() method of Upload to get the TransferProgress class.

Can Java SDK use persistent connections?
The Java SDK uses persistent connections by default.

How to use the Java SDK to get all the paths to the specified directory and determine
whether the paths are files or folders?
You can use the feature of querying the object list in the Java SDK to list all objects in a bucket. You can use theprefix parameter to specify the directory prefix.

What should I do if the Java SDK reports the error "java.lang.IllegalStateException:
Connection pool shut down"?
1. COSClient is a thread-safe class that allows multi-thread access to the same instance.
Because an instance maintains a connection pool internally, creating multiple instances may lead to resource
exhaustion. Make sure that there is only one instance in the program lifecycle, and call the
COSClient.shutdown() method to shut down the instance when it is no longer needed.
If you need to create a new instance, shut down the previous one first. We recommend you use only one
COSClient in a thread and call COSClient.shutdown() after all programs end and exit.
2. COSClient is also used in the TransferManager encapsulation class of advanced APIs. We recommend you callTransferManager.shutdownNow(false) after all programs end and exit.
In addition, if another COSClient is reused when a TransferManager instance is created, add the parameter false(i.e., TransferManager.shutdownNow(false) ) when closing the instance. This avoids closing the reused
COSClients and thus causing errors in other places where it is used.

©2013-2022 Tencent Cloud. All rights reserved.

Page 765 of 1869

Cloud Infinite

Image Processing
Basic Image Processing：

Last updated 2024-02-29 17:31:27

Overview
COS has integrated Cloud Infinite (CI), a one-stop professional multimedia solution that offers the image processing
features outlined below. For more information, see Image Processing Overview.
ServiceFeatureDescription

Scaling

Proportional scaling, scaling image to target width and height

Cropping

Basic image
processing

Regular cropping, cropping and scaling, cropping to circle,
smart face cropping

Rotation

Adaptive rotation, regular rotation

Format conversion

Format conversion, GIF format optimization, progressive
display

Quality change

Quality change for JPG and WebP images

Gaussian blurring

Image blurring

Sharpening

Image sharpening

Watermarking

Image watermark, text watermark

Image informationacquisition

Basic information, EXIF information, average hue

Metadata removal

Including EXIF information

Quick thumbnail
template

Quick image format conversion, scaling, and cropping for
thumbnail generation

Basic Image Processing©2013-2022 Tencent Cloud. All rights reserved.

Page 766 of 1869

Cloud Infinite

When performing basic image processing, you need to specify the image processing rule. For more information, see
Image Processing Overview.
For all the code samples, visit GitHub.
Below are some examples:

Scaling

String bucketName = "examplebucket-1250000000";
String key = "qrcode.png";
GetObjectRequest getObj = new GetObjectRequest(bucketName, key);©2013-2022 Tencent Cloud. All rights reserved.

Page 767 of 1869

Cloud Infinite// Scale the width and height to 50% of the input image
String rule = "imageMogr2/thumbnail/!50p";
getObj.putCustomQueryParameter(rule, null);cosClient.getObject(getObj, new File("qrcode-50p.png"));Cropping

String bucketName = "examplebucket-1250000000";
String key = "qrcode.png";
GetObjectRequest getObj = new GetObjectRequest(bucketName, key);©2013-2022 Tencent Cloud. All rights reserved.

Page 768 of 1869

Cloud Infinite// Crop the radius of an inscribed circle to an integer greater than zero and less
String rule = "imageMogr2/iradius/150";
getObj.putCustomQueryParameter(rule, null);cosClient.getObject(getObj, new File("qrcode-cropping.png"));Rotation

String bucketName = "examplebucket-1250000000";
String key = "qrcode.png";
GetObjectRequest getObj = new GetObjectRequest(bucketName, key);©2013-2022 Tencent Cloud. All rights reserved.

Page 769 of 1869

Cloud Infinite// Rotate clockwise by 90 degrees
String rule = "imageMogr2/rotate/90";
getObj.putCustomQueryParameter(rule, null);cosClient.getObject(getObj, new File("qrcode-rotate.png"));©2013-2022 Tencent Cloud. All rights reserved.

Page 770 of 1869

Cloud Infinite

Persistent Image Processing：

Last updated 2024-02-29 17:31:27

Overview
This document describes how to automatically process an image when you upload it to COS.
When the image is uploaded successfully, COS will save both the original and the processed images. You can later
obtain the processing results by using a general download request.

Persistent Image Processing During Upload
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 771 of 1869

Cloud Infinite// The bucket name must contain `appid`.
// For the API description, visit https://cloud.tencent.com/document/product/436/54
String bucketName = "examplebucket-1250000000";
String key = "test.jpg";
File localFile = new File("E://test.jpg");
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile
PicOperations picOperations = new PicOperations();
picOperations.setIsPicInfo(1);// Add image processing rules
List<PicOperations.Rule> ruleList = new LinkedList<>();©2013-2022 Tencent Cloud. All rights reserved.

Page 772 of 1869

Cloud Infinite

PicOperations.Rule rule1 = new PicOperations.Rule();rule1.setBucket(bucketName);
rule1.setFileId("test-1.jpg");
rule1.setRule("imageMogr2/rotate/90");
ruleList.add(rule1);
PicOperations.Rule rule2 = new PicOperations.Rule();rule2.setBucket(bucketName);
rule2.setFileId("test-2.jpg");
rule2.setRule("imageMogr2/rotate/180");
ruleList.add(rule2);
picOperations.setRules(ruleList);
putObjectRequest.setPicOperations(picOperations);
try {PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
CIUploadResult ciUploadResult = putObjectResult.getCiUploadResult();
System.out.println(putObjectResult.getRequestId());
System.out.println(ciUploadResult.getOriginalInfo().getEtag());
for(CIObject ciObject:ciUploadResult.getProcessResults().getObjectList()) {System.out.println(ciObject.getLocation());
System.out.println(ciObject.getEtag());}} catch (CosServiceException e) {e.printStackTrace();} catch (CosClientException e) {e.printStackTrace();}Parameter description
The PicOperations class is used to record image operations. Its main members are as described below:
MemberDescription

Type

isPicInfo

Whether to return the input image information. Valid values: 0 (no), 1 (yes). Default
value: 0.

int

rules

Processing rules (up to five rules are supported). Each rule corresponds to one
processing result. If this parameter is not specified, images will not be processed.

List

Response parameter description
The CIUploadResult class is used to return the image processing result. Its main members are as described
below:
MemberDescription

TypeoriginalInfo

Input image information

OriginalInfo©2013-2022 Tencent Cloud. All rights reserved.

Page 773 of 1869

Cloud Infinite

processResults

Image processing result

ProcessResults

The OriginalInfo class is used to record the input image information. Its main members are as described
below:
MemberDescription

Type

key

Name of the input image

Stringlocation

Image path

StringimageInfo

Input image information

ImageInfo

etag

ETag of the input image. If the output image overwrites the input image, theStringvalue of ETag will be that of the output image.

The ImageInfo class is used to record the input image information. Its main members are as described below:
MemberDescriptionTypeformatFormatStringwidth

Image width

IntegerheightImage height

Integerquality

Image quality

Integerave

Image average hue

Stringorientation

Image rotation angle

Integer

The ProcessResults class is used to record the image processing results. Its main members are as described
below:
MemberDescriptionTypeobjectList

Processing result of each image

List

The CIObject class is used to record the processing result of a single image. Its main members are as described
below:
MemberDescription

Type

key

Filename

String©2013-2022 Tencent Cloud. All rights reserved.

Page 774 of 1869

Cloud Infinite

location

Image path

StringformatImage format

Stringwidth

Image width

IntegerheightImage height

Integersize

Image size

Integerquality

Image quality

Integeretag

ETag of the output image

StringProcessing In-Cloud Image
The following example shows how to process an image stored in COS and save the processing result to COS.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 775 of 1869

Cloud Infinite

String bucketName = "examplebucket-1250000000";
String key = "test.jpg";
ImageProcessRequest imageReq = new ImageProcessRequest(bucketName, key);
PicOperations picOperations = new PicOperations();
picOperations.setIsPicInfo(1);List<PicOperations.Rule> ruleList = new LinkedList<>();
PicOperations.Rule rule1 = new PicOperations.Rule();rule1.setBucket(bucketName);
rule1.setFileId("test-1.jpg");
rule1.setRule("imageMogr2/rotate/90");©2013-2022 Tencent Cloud. All rights reserved.

Page 776 of 1869

Cloud Infinite

ruleList.add(rule1);
PicOperations.Rule rule2 = new PicOperations.Rule();rule2.setBucket(bucketName);
rule2.setFileId("test-2.jpg");
rule2.setRule("imageMogr2/rotate/180");
ruleList.add(rule2);
picOperations.setRules(ruleList);
imageReq.setPicOperations(picOperations);
CIUploadResult result = cosClient.processImage(imageReq);
result.getProcessResults();
result.getOriginalInfo();try {CIUploadResult ciUploadResult = cosClient.processImage(imageReq);
System.out.println(ciUploadResult.getOriginalInfo().getEtag());
for(CIObject ciObject:ciUploadResult.getProcessResults().getObjectList()) {System.out.println(ciObject.getLocation());
System.out.println(ciObject.getEtag());}} catch (CosServiceException e) {e.printStackTrace();} catch (CosClientException e) {e.printStackTrace();}©2013-2022 Tencent Cloud. All rights reserved.

Page 777 of 1869

Cloud Infinite

Image Advanced Compression：

Last updated 2024-02-29 17:31:27

Overview
This document provides an overview of APIs and SDK code samples for image advanced compression.
API

Description

Imageadvanced

The image advanced compression feature allows you to easily convert images into formats thatprovide a high compression ratio, such as TPG and HEIF. This effectively reduces thecompression

transmission time, loading time, and the use of bandwidth and traffic.

Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 778 of 1869

Cloud Infinite

GetObjectRequest getObj = new GetObjectRequest(bucketName, key);// The following are sample parameters for image compression. For more information,
String compress = "imageMogr2/format/tpg";
getObj.putCustomQueryParameter(compress, null);©2013-2022 Tencent Cloud. All rights reserved.

Page 779 of 1869

Cloud Infinite

Blind Watermark：

Last updated 2024-02-29 17:31:27

Overview
This document provides an overview of APIs and SDK code samples for blind watermarking.
API

Description

Blindwatermarking

Adds blind watermark to or extracts blind watermark from local image and uploads it tobucket.

Adding Blind Watermark
Feature description
You can add a blind watermark when uploading or downloading an object.
Sample: Adding a blind watermark during upload©2013-2022 Tencent Cloud. All rights reserved.

Page 780 of 1869

Cloud Infinite// The bucket name must contain `appid`.
// For the API description, visit https://www.tencentcloud.com/document/product/436
String bucketName = "examplebucket-1250000000";
String key = "test.png";
File localFile = new File("E://test.png");
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile
PicOperations picOperations = new PicOperations();
picOperations.setIsPicInfo(1);List<PicOperations.Rule> ruleList = new LinkedList<>();
PicOperations.Rule rule = new PicOperations.Rule();©2013-2022 Tencent Cloud. All rights reserved.

Page 781 of 1869

Cloud Infinite

rule.setBucket(bucketName);rule.setFileId("test-watermark.png");
rule.setRule("watermark/3/type/3/text/dGVuY2VudCBjbG91ZA==");
ruleList.add(rule);
picOperations.setRules(ruleList);
putObjectRequest.setPicOperations(picOperations);
try {PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
CIUploadResult ciUploadResult = putObjectResult.getCiUploadResult();
System.out.println(putObjectResult.getRequestId());
System.out.println(ciUploadResult.getOriginalInfo().getEtag());
for(CIObject ciObject:ciUploadResult.getProcessResults().getObjectList()) {System.out.println(ciObject.getLocation());}} catch (CosServiceException e) {e.printStackTrace();} catch (CosClientException e) {e.printStackTrace();}Parameter description
The PicOperations class is used to record image operations. Its main members are as described below:
MemberDescription

Type

isPicInfo

Whether to return the input image information. Valid values: 0 (no), 1 (yes). Default
value: 0.

int

rules

Processing rules (up to five rules are supported). Each rule corresponds to one
processing result. If this parameter is not specified, images will not be processed.

List

Response parameter description
The CIUploadResult class is used to return the image processing result. Its main members are as described
below:
MemberDescription

TypeoriginalInfo

Input image information

OriginalInfo

processResults

Image processing result

ProcessResults

The OriginalInfo class is used to record the input image information. Its main members are as described
below:
MemberDescription©2013-2022 Tencent Cloud. All rights reserved.

Type

Page 782 of 1869

Cloud Infinite

key

Name of the input image

Stringlocation

Image path

StringimageInfo

Input image information

ImageInfoThe ImageInfo class is used to record the input image information. Its main members are as described below:
MemberDescriptionTypeformatFormatStringwidth

Image width

IntegerheightImage height

Integerquality

Image quality

Integerave

Image average hue

Stringorientation

Image rotation angle

Integer

The ProcessResults class is used to record the image processing results. Its main members are as described
below:
MemberDescriptionTypeobjectList

Processing result of each image

List

The CIObject class is used to record the processing result of a single image. Its main members are as described
below:
MemberDescription

Type

key

Filename

Stringlocation

Image path

StringformatImage format

Stringwidth

Image width

IntegerheightImage height

Integersize

Image size

Integerquality

Image quality

Integer©2013-2022 Tencent Cloud. All rights reserved.

Page 783 of 1869

Cloud Infinite

Sample: Adding a blind watermark during download

GetObjectRequest getObj = new GetObjectRequest(bucketName, key);// The following are blind watermarking rules. For more information, see the API de
String rule = "watermark/3/type/3/text/dGVuY2VudCBjbG91ZA==";
getObj.putCustomQueryParameter(rule, null);cosClient.getObject(getObj);©2013-2022 Tencent Cloud. All rights reserved.

Page 784 of 1869

Cloud Infinite

Extracting Blind Watermark
The following example shows how to extract a blind watermark from an image.
Sample code

String bucketName = "examplebucket-1250000000";
String key = "qrcode-watermark.png";
File localFile = new File("E://qrcode-watermark.png");
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile©2013-2022 Tencent Cloud. All rights reserved.

Page 785 of 1869

Cloud Infinite

PicOperations picOperations = new PicOperations();
picOperations.setIsPicInfo(1);List<PicOperations.Rule> ruleList = new LinkedList<>();
PicOperations.Rule rule = new PicOperations.Rule();rule.setBucket(bucketName);rule.setFileId("qrcode-watermark-extract.png");
rule.setRule("watermark/4/type/2/image/aHR0cDovL2V4YW1wbGVidWNrZXQtMTI1MDAwMDAwMC5j
ruleList.add(rule);
picOperations.setRules(ruleList);
putObjectRequest.setPicOperations(picOperations);
try {PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
CIUploadResult ciUploadResult = putObjectResult.getCiUploadResult();
System.out.println(putObjectResult.getRequestId());
System.out.println(ciUploadResult.getOriginalInfo().getEtag());
for(CIObject ciObject:ciUploadResult.getProcessResults().getObjectList()) {System.out.println(ciObject.getLocation());
System.out.println(ciObject.getWatermarkStatus());}} catch (CosServiceException e) {e.printStackTrace();} catch (CosClientException e) {e.printStackTrace();}Parameter description
The PicOperations class is used to record image operations. Its main members are as described below:
MemberDescription

Type

isPicInfo

Whether to return the input image information. Valid values: 0 (no), 1 (yes). Default
value: 0.

int

rules

Processing rules (up to five rules are supported). Each rule corresponds to one
processing result. If this parameter is not specified, images will not be processed.

List

Response parameter description
The CIUploadResult class is used to return the image processing result. Its main members are as described
below:
MemberDescription

TypeoriginalInfo

Input image information

OriginalInfo

processResults

Image processing result

ProcessResults©2013-2022 Tencent Cloud. All rights reserved.

Page 786 of 1869

Cloud Infinite

The OriginalInfo class is used to record the input image information. Its main members are as described
below:
MemberDescription

Type

key

Name of the input image

Stringlocation

Image path

StringimageInfo

Input image information

ImageInfoThe ImageInfo class is used to record the input image information. Its main members are as described below:
MemberDescriptionTypeformatFormatStringwidth

Image width

IntegerheightImage height

Integerquality

Image quality

Integerave

Image average hue

Stringorientation

Image rotation angle

Integer

The ProcessResults class is used to record the image processing results. Its main members are as described
below:
MemberDescriptionTypeobjectList

Processing result of each image

List

The CIObject class is used to record the processing result of a single image. Its main members are as described
below:
MemberDescription

Type

key

Filename

Stringlocation

Image path

StringformatImage format

Stringwidth

Image width

Integer©2013-2022 Tencent Cloud. All rights reserved.

Page 787 of 1869

Cloud Infinite

heightImage height

Integersize

Image size

Integerquality

Image quality

IntegerThis parameter will be returned if type is set to 2 , indicating thewatermarkStatusconfidence of the extracted watermark. Value range: 0–100. If the value isabove 75, there is a confirmed blind watermark. If the value is between 60 andInteger

75, there is a suspected blind watermark. If the value is below 60, no blind
watermark is extracted.

©2013-2022 Tencent Cloud. All rights reserved.

Page 788 of 1869

Cloud Infinite

AI-Based Content Recognition
Image Tagging：

Last updated 2024-02-29 17:31:27

Overview
This document provides an overview of APIs and SDK code samples for image tagging.
API

Description

Tagging image

Recognizes tags in an image stored in COS.

Image Tagging
Feature description
The image tagging feature recognizes tags in images stored in COS by using the persistent processing API of CI and
returns tags with a high confidence. Image tagging requests are GET requests and need to carry a signature.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 789 of 1869

Cloud Infinite

ImageLabelResponse getImageLabel(ImageLabelRequest request);

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 790 of 1869

Cloud Infinite//1. Create a job request object
ImageLabelRequest request = new ImageLabelRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("demo-123456789");
request.setObjectKey("1.png");//3. Call the API to get the job response object
ImageLabelResponse response = client.getImageLabel(request);

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 791 of 1869

Cloud Infinite

Request has the following sub-nodes:
Node Name

Parent(Keyword)NodebucketName

RequestobjectKey

RequestDescription
Bucket name in the format of BucketName-APPID .
For more information, see Bucket Overview.
Location of the image in the bucket

Type

Required

StringYes

StringYes

Response description
Success: An ImageLabelResponse instance is returned upon success, which contains the result.
Failure: An error (such as the bucket does not exist) occurs, reporting the CosClientException or
CosServiceException exception. For more information, see Troubleshooting.

©2013-2022 Tencent Cloud. All rights reserved.

Page 792 of 1869

Cloud Infinite

Vehicle Recognition：

Last updated 2024-02-29 17:31:27

Overview
This document provides an overview of APIs and SDK code samples for vehicle recognition.
API

Description

Vehicle and license plate detection

Recognizes vehicles in images.

Vehicle and License Plate Detection
Feature description
This feature uses a sync GET request to detect a vehicle in an image and recognize its brand, color, location, andlicense plate information.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 793 of 1869

Cloud Infinite

DetectCarResponse detectCar(DetectCarRequest request);

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 794 of 1869

Cloud Infinite//1. Create a job request object
DetectCarRequest request = new DetectCarRequest();//2. Add request parameters as detailed in the API documentation//2.1 Set the request bucket
request.setBucketName("demobucket-1234567890");//2.2 Set the image location in the bucket
request.setObjectKey("car.jpg");
DetectCarResponse response = client.detectCar(request);

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 795 of 1869

Cloud Infinite

Request has the following sub-nodes:
Node Name(Keyword)

ParentNodebucketName

RequestobjectKey

RequestDescription
Bucket name in the format of BucketName-APPID .
For more information, see Bucket Overview.
Location of the image in the bucket

Type

Required

StringYes

StringYes

Response description
Success: The DetectCarResponse job result object is returned upon success.
Failure: An error (such as the bucket does not exist) occurs, reporting the CosClientException or
CosServiceException exception. For more information, see Troubleshooting.

©2013-2022 Tencent Cloud. All rights reserved.

Page 796 of 1869

Cloud Infinite

Media Processing
Template Operations：

Last updated 2024-02-29 17:31:27

Overview
This document provides an overview of APIs and SDK code samples for media processing jobs in CI, with theanimated image job as an example.
API

Operation

Description

CreateMediaTemplate

Creating template

Creates template

DeleteMediaTemplate

Deleting template

Deletes template

DescribeMediaTemplates

Querying templates

Queries template list

UpdateMediaTemplate

Modifying template

Modifies template

Basic Operations
Creating template
Feature description
This API is used to create a template.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 797 of 1869

Cloud Infinite

public MediaTemplateResponse createMediaTemplate(MediaTemplateRequest request);

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

Parent
Node

Tag

RequestDescription

Type

RequiredTemplate type: Animation (animated image);Snapshot (screenshot); Transcode (transcoding);

StringYes©2013-2022 Tencent Cloud. All rights reserved.

Page 798 of 1869

Cloud Infinite

Watermark (watermark); SmartCover (intelligent
thumbnail)
Name

RequestTemplate name, which can contain letters, digits,
underscores (_), hyphens (-), and asterisks (*).

StringYes

Container

RequestContainer format

Container

Yes

Video

RequestVideo information

Container

No

TimeInterval

RequestTime interval

ContainerNo

Snapshot

RequestScreenshot

Container

No

WatermarkRequestWatermarkContainer

No

Audio

RequestAudio information

Container

No

TransConfig

RequestTranscoding configuration

Container

No

Type

Required

StringYes

Container has the following sub-nodes:
Node
Name

Parent NodeDescription(Keyword)
FormatRequest.Container

Container format. Valid values: gif ,hgif (higher-definition GIF), webp .

Video has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

Default
Value

Constraints

Codec

Request.Video

Codec
formatStringYes

None

gif, webp
Value range: [128, 409

WidthRequest.Video

Width

StringNo

Original
video
width

Unit: px
If only Width is set, Hei
calculated according tooriginal video aspect ra

HeightRequest.Video

Height©2013-2022 Tencent Cloud. All rights reserved.

StringNo

Original
video

Value range: [128, 409
Unit: pxheightIf only Height is set, Wi
calculated according toPage 799 of 1869

Cloud Infinite

original video aspect ra
Value range: (0, 60]

Fps

Request.Video

Frame rate

StringNo

Original
video
frame
rate

Unit: fps
This parameter is optio
it is not set, the video isplayed at the speed as
the original timestamp.
parameter specifies therate for animated image
playback.

AnimateOnly
KeepKeyFrame

Keep only
keyframes
Request.Videoforanimated
imagesValid values: true, false
StringNo

NoneSpecifies whether to ke
only keyframes for anim
imagesValue range: (0, video

AnimateTime
IntervalOfFrame

Request.Video

Frame
sampling
interval foranimated

StringNo

Noneimagesduration]
Frame sampling interva
animated images
The value of this param
must be less than the v
TimeInterval.Duration i
TimeInterval.Duration i
Value range: (0, video f
rate)
Frame sampling frequeNumber offramesAnimateFrames
PerSecond

Quality

Request.Video

Request.Video

sampledper secondforanimated
imagesRelative
qualityStringString

No

No

None

None

for animated images
Priority:
AnimateFramesPerSec
AnimateOnlyKeepKeyF>
AnimateTimeIntervalO
Value range: [1, 100)
This parameter will tak
effect for WEBP image
is not available for GIF
images.

TimeInterval has the following sub-nodes:©2013-2022 Tencent Cloud. All rights reserved.

Page 800 of 1869

Cloud Infinite

Node
Name
(Keyword)

Start

Parent NodeDescription

Request.TimeIntervalStart time

Type

StringRequiredNo

Default
Value

0

Constraints

Value range: [0,video duration]
Unit: Second
The float format is
supported,
accurate to themillisecond.
Value range: [0,Duration

Request.TimeInterval

Duration

StringNoVideo
durationvideo duration]
Unit: Second
The float format is
supported,
accurate to themillisecond.

Snapshot has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

Default
Value

Mode

Request.Snapshot

Screenshot
mode

StringYes

Interval

Constraints
Valid values:{Interval,
Average}
Interval: Interval
mode. Average:
Average mode
Interval mode:
The Start,
TimeInterval, andCountparameters takeeffect. If Count is
set andTimeInterval is
not set, all frames
will be captured,and the total
number of images
captured will be
specified byCount.

©2013-2022 Tencent Cloud. All rights reserved.

Page 801 of 1869

Cloud Infinite

Average mode:
The Start andCountparameters takeeffect, indicating
to capture a totalof Count images
at an averageinterval from Start
to the end of thevideo.

Start

Request.Snapshot

Start time

StringYes

0

Value range: [0,video duration]
Unit: Second
The float format is
supported,
accurate to themillisecond.
Value range: (0,3600]
Unit: Second

TimeInterval

Request.Snapshot

Screenshot
time interval

String

No

None

The float format is
supported,
accurate to themillisecond.

Count

Request.Snapshot

Number ofscreenshots

StringYes

None(0, 10000]
Value range:[128, 4096]

Width

Request.Snapshot

WidthStringNo

Original

Unit: px
If only Width isvideo

set, Height iswidthcalculated
according to theoriginal video
aspect ratio.

HeightRequest.Snapshot

HeightStringNo

Original

Value range:

video
height[128, 4096]
Unit: px
If only Height isset, Width is©2013-2022 Tencent Cloud. All rights reserved.

Page 802 of 1869

Cloud Infinite

calculated
according to theoriginal video
aspect ratio.

Watermark has the following sub-nodes:
Node
Name

Parent NodeDescription

Type

Required(Keyword)

Type

Request.Watermark

Watermarktype

StringYes

Default
Value

None

Constraints

Text: Text
watermark.
Image: Image
Watermark.
TopRight,

Pos

Request.Watermark

Reference
position

StringYes

None

TopLeft,
BottomRight,
BottomLeft

LocModeRequest.Watermark

Offsetmode

StringYes

None

Relativity:
Proportionally.
Absolute: Fixed
position.
If locMode isRelativity, the unit
is %, and the

Dx

Request.Watermark

Horizontal
offsetStringYes

Nonevalue range is [0,100]If locMode is
Absolute, the unit
is px, and thevalue range is [0,4096].

Dy

Request.Watermark

VerticaloffsetStringYes

None

If locMode isRelativity, the unit
is %, and thevalue range is [0,100]If locMode is
Absolute, the unit
is px, and the©2013-2022 Tencent Cloud. All rights reserved.

Page 803 of 1869

Cloud Infinite

value range is [0,4096].
Value range: [0,video duration]
StartTime

Request.Watermark

Watermarkstart time

StringNo

0

Unit: Second
The float format
is supported,
accurate to themillisecond.
Value range: [0,EndTime

Request.Watermark

Watermarkend time

StringNo

Video

video duration]
Unit: Second

end
time

The float format
is supported,
accurate to themillisecond.

Image
Image

Request.Watermark

watermarknode

Container

No

None

None

Container

No

None

None

Type

Required

Text
Text

Request.Watermark

watermarknode

Image has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Default
Value

Same as thwatermark

Watermark
Url

Request.Watermark.Image

image
address

Constraints

String

Yes

None

image
address ofthe bucket.
Original:
Original siz

ModeRequest.Watermark.Image

Dimension
mode

Proportion:
StringYes

None

Scaledproportiona
Fixed: Fixe
size

©2013-2022 Tencent Cloud. All rights reserved.

Page 804 of 1869

Cloud Infinite

Width

Request.Watermark.Image

Width

StringNo

None

If Mode is
Original, thparameterthewatermarkimage widt
If Mode is
Proportion,
the unit is %and the val
range is [1,100].
If Mode is
Fixed, theunit is px,
and the val
range is [1,4096].
If only Widt
is set, Heig
is calculateaccording t
the originalvideo aspe
ratio.

HeightRequest.Watermark.Image

HeightStringNo

None

If Mode is
Original, thparameterthewatermarkimage heig
If Mode is
Proportion,
the unit is %and the val
range is [1,100].
If Mode is
Fixed, theunit is px,
and the val
range is [1,4096].
If only Heig
is set, Widt

©2013-2022 Tencent Cloud. All rights reserved.

Page 805 of 1869

Cloud Infinite

is calculateaccording t
the originalvideo aspe
ratio.

Transparency

Request.Watermark.Image

Transparency

StringYes

None

Value range[1, 100]. Un%

Watermark position description:

Text has the following sub-nodes:
Node Name(Keyword)
FontSize

Parent NodeDescription

Type

Required

Request.Watermark.Text

Font size

StringYes©2013-2022 Tencent Cloud. All rights reserved.

Default
Value
None

Constraints
Value
range: [5,Page 806 of 1869

Cloud Infinite100]. Unit:
px
FontType

Request.Watermark.Text

Font type

StringYes

None

FontColor

Request.Watermark.Text

Font color

StringYes

None

See thetable below.
Format:0xRRGGBB
Value

Transparency

Request.Watermark.Text

Transparency

StringYes

None

range: [1,100]. Unit:%
The value
can be up to

Text

Request.Watermark.Text

Watermarkcontent

64 letters,
digits,StringYes

Noneunderscores(_), hyphens(-), andasterisks(*).

FontType has the following sub-nodes:
Font Name

Supported Language

Description

simfang.ttf

Chinese/English

FangSong

simhei.ttf

Chinese/English

SimHeisimkai.ttf

Chinese/English

KaiTi

simsun.ttc

Chinese/English

SimSunSTHeiti-Light.ttc

Chinese/English

STHeiti-Light

STHeiti-Medium.ttc

Chinese/English

STHeiti-Medium

youyuan.TTF

Chinese/English

YouYuanariblk.ttf

EnglishNonearial.ttf

EnglishNoneahronbd.ttf

EnglishNone©2013-2022 Tencent Cloud. All rights reserved.

Page 807 of 1869

Cloud Infinite

Helvetica.dfont

EnglishNone

HelveticaNeue.dfont

EnglishNone

Audio/Video formats supported by different container formats are as follows:
Container

Audio Codecs

Video Codecs

flv/mp4/ts/hls

AAC, MP3

H.264

AAC

AAC

Not supported

MP3

MP3

Not supported

Audio has the following sub-nodes:
Node
Name

Parent NodeDescription

Type

Required

Request.Audio

Codec
formatStringNo(Keyword)
Codec

Default
Value

aac

Constraints

Valid values: aac, mp3.
Unit: Hz
Valid values: 11025,

Samplerate

Request.Audio

Sample rate

StringNo

44100

22050, 32000, 44100,
48000, 96000.
Different container
formats support
different MP3 sample
rates, as shown in thetable below.

BitrateRequest.Audio

Original
audio bitrate

StringNo

None

Unit: Kbps
Value range: [8, 1000]
If Codec is aac, theChannelsRequest.Audio

Number of
soundchannels

StringNo

None

StringNo

false

value can be 1, 2, 4, 5,
6, or 8.
If Codec is mp3, thevalue can be 1 or 2.

Whether toRemoveRequest.Audio

delete theaudio
stream©2013-2022 Tencent Cloud. All rights reserved.

Valid values: true, false.

Page 808 of 1869

Cloud Infinite

Y indicates supported, and N indicates unsupported.
Container Format/Audio Sample Rate

11025

22050

32000

44100

48000

96000

flv

Y

Y

N

Y

N

N

mp4

N

Y

Y

Y

Y

N

avi/hls/ts/mp3

Y

Y

Y

Y

Y

N

Type

RequiredTransConfig has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Default
Value

Constraint
Valid valu
crop, pad,If the aspe

Resolution
AdjDarMethod

Request.TransConfig

adjustment
methodStringNonone

the output
different fr
the origina
the resolu
to be adju
accordingparameter
Valid valu
false.

Whether to
IsCheckReso

Request.TransConfig

check theresolution

StringNo

false

If the valu
transcodin
performed
settings.
Valid valu
indicates t
original vid
resolution

ResoAdjMethod

Request.TransConfig

Resolution
adjustment
methodStringNo

indicates t
the transc
failure me

0This paramtake effectwhen IsCh
is true.
IsCheckVideoBitrate

Request.TransConfig

Whether tocheck the©2013-2022 Tencent Cloud. All rights reserved.

StringNo

false

Valid valu
false.

Page 809 of 1869

Cloud Infinite

video
bitrateIf the valu
transcodin
performed
settings.
Valid valu
indicates t
original vid

VideoBitrateAdjMethod

Request.TransConfigVideobitrateadjustment

StringNo

bitrate, anindicates t
the transc
failure me0

methodThis paramtake effectwhen
IsCheckV
is true.

IsCheckAudioBitrate

Request.TransConfig

Whether tocheck theaudio
bitrateStringNo

false

Valid valu
false.
If the valu
transcodin
performed
settings.
Valid valu
indicates t
original au
bitrate, anindicates t

Audio
AudioBitrateAdjMethod

Request.TransConfig

bitrateadjustment
methodStringNo

the transc
failure me
This paramtake effect0

when
IsCheckA
is true.

Video has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeDescription

Type

Required

Codec

Request.Video

Codec format

StringNo©2013-2022 Tencent Cloud. All rights reserved.

Default
Value
H.264

Constraints

H.264

Page 810 of 1869

Cloud Infinite

Width

Request.Video

Width

StringNo

Original
video
width

Value range: [128,4096]
Unit: px
If only Width is set,
Height is calculated
according to theoriginal video aspectratio.

HeightRequest.Video

HeightStringNo

Original
video
heightValue range: [128,4096]
Unit: px
If only Height is set,
Width is calculated
according to theoriginal video aspectratio.

Fps

RemoveRequest.Video

Frame rate

StringNo

None

Value range: (0, 60]
Unit: fps

Request.Video

Whether todelete thevideo stream

StringNo

false

true/false

Valid values: baseline,

ProfileRequest.Video

Encoding
level

main, high.
baseline: Suitable formobile devices.
main: Suitable for
StringNo

highstandard resolution
devices.
high: Suitable for highresolution devices.
Only H.264 supports
this parameter.

BitrateRequest.Video

Bitrate of thevideo output

String

No

None

file

Unit: Kbps
Value range: (0, 51]

Bitrate, which
Crf

Request.Video

is a quality
control factor

String

No

None

Gop

Request.Video

Maximum

StringNo

None©2013-2022 Tencent Cloud. All rights reserved.

Value range: [10,50000]

If Crf is set, the settingof Bitrate will become
invalid.
Value range: [1,Page 811 of 1869

Cloud Infinite

number offramesbetween two
keyframes

100000]

Only H.264 supports
PresetRequest.VideoVideo
algorithm
presetStringNo

mediumthis parameter.
Valid values: veryfast,
fast, medium, slow,
slower.
Value range: [1000,

Bufsize

MaxrateHlsTsTime

PixfmtRequest.Video

Buffer size

Request.Video

Peak video
bitrateRequest.Video

HLS
segment time

Request.Video

Video color
formatStringString

No

No

None

None

128000]
Unit: Kb
Value range: [10,50000]
Unit: Kbps
Value range: (0, video

StringString

No

No

5

None

duration]
Unit: Second
Valid values: yuv420p,
yuv422p, yuv444p,
yuvj420p, yuvj422p,
yuvj444p.

Response description
Success: The MediaTemplateResponse object response information is returned, which contains the details of
the created template.
Failure: An error (such as the bucket does not exist) occurs, reporting the CosClientException or
CosServiceException exception. For more information, see Troubleshooting.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 812 of 1869

Cloud Infinite//1. Create a template request object
MediaTemplateRequest request = new MediaTemplateRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("examplebucket-1250000000");
request.setTag("Animation");request.setName("TestTemplate40");
request.getContainer().setFormat("gif");
request.getVideo().setCodec("gif");
request.getVideo().setWidth("1280");
request.getVideo().setFps("15");
request.getVideo().setAnimateOnlyKeepKeyFrame("true");©2013-2022 Tencent Cloud. All rights reserved.

Page 813 of 1869

Cloud Infinite

request.getTimeInterval().setStart("0");request.getTimeInterval().setDuration("60");//3. Call the API to get the template response object
MediaTemplateResponse response = client.createMediaTemplate(request);

Deleting template
Feature description
This API is used to delete a template.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 814 of 1869

Cloud Infinite

public Boolean deleteMediaTemplate(MediaTemplateRequest request);

Parameter description
Parameter
bucketName
templateId

Description
Bucket name in the format of BucketName-APPID . For more
information, see Bucket Overview.
ID of the template to be canceled©2013-2022 Tencent Cloud. All rights reserved.

Type

Required

StringYes

StringYes

Page 815 of 1869

Cloud Infinite

Response description
Success: A boolean type is returned, which is true upon deletion success.
Failure: If an error (such as authentication failure) occurs, the CosClientException or
CosServiceException exception will be reported. For more information, see Troubleshooting.
Sample request

MediaTemplateRequest request = new MediaTemplateRequest();request.setBucketName("examplebucket-1250000000");
request.setTemplateId("t19c4a60ae1a694621a01f0c7130c*****");©2013-2022 Tencent Cloud. All rights reserved.

Page 816 of 1869

Cloud Infinite

Boolean response = client.deleteMediaTemplate(request);

Querying template list
Feature description
This API is used to query the template list.
Method prototype

public MediaJobResponse describeMediaJob(MediaJobsRequest req);©2013-2022 Tencent Cloud. All rights reserved.

Page 817 of 1869

Cloud Infinite

Parameter description
Parameter
bucketName

tag

category

Description
Bucket name in the format of BucketName-APPID . For more
information, see Bucket Overview.
Template tag: Animation (animated image); Snapshot (screenshot);Transcode (transcoding); Watermark (watermark); SmartCover(intelligent thumbnail)Template category. Valid values: Custom , Official . Default
value: Custom .

Type

Required

StringYes

StringYes

StringNo

ids

Template ID. If you enter multiple IDs, separate them by comma.

StringNo

nameTemplate name prefix

StringNo

pageNumber

Page number

IntegerNo

pageSize

Number of entries per page

IntegerNo

Response description
Success: A template response wrapper class is returned, which contains the template details set templateList .
Failure: If an error (such as authentication failure) occurs, the CosClientException or
CosServiceException exception will be reported. For more information, see Troubleshooting.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 818 of 1869

Cloud Infinite//1. Create a job request object
MediaTemplateRequest request = new MediaTemplateRequest();request.setBucketName("examplebucket-1250000000");
MediaListTemplateResponse response = client.describeMediaTemplates(request);
List<MediaTemplateObject> templateList = response.getTemplateList();Modifying template
Feature description©2013-2022 Tencent Cloud. All rights reserved.

Page 819 of 1869

Cloud Infinite

This API is used to modify a template.
Method prototype

public Boolean updateMediaTemplate(MediaTemplateRequest request);

Parameter description
Node Name(Keyword)

Description©2013-2022 Tencent Cloud. All rights reserved.

Type

RequiredPage 820 of 1869

Cloud Infinite

bucketName

Bucket name in the format of BucketName-APPID . For more

StringYes

StringYes

information, see Bucket Overview.
templateId

ID of the template to be modified

Note:
Other parameters are the same as those of the template creation API as described in Creating Animated Image
Template.
Response description
Success: true is returned upon modification success.
Failure: If an error (such as authentication failure) occurs, the CosClientException or
CosServiceException exception will be reported. For more information, see Troubleshooting.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 821 of 1869

Cloud Infinite

MediaTemplateRequest request = new MediaTemplateRequest();request.setBucketName("examplebucket-1250000000");
request.setTemplateId("t19c4a60ae1a694621a01f0c7130*****");
request.setTag("Animation");request.setName("updateName");request.getContainer().setFormat("gif");
Boolean aBoolean = client.updateMediaTemplate(request);©2013-2022 Tencent Cloud. All rights reserved.

Page 822 of 1869

Cloud Infinite

Workflow Operations：

Last updated 2024-02-29 17:31:27

Overview
This document provides an overview of APIs and SDK code samples for media processing workflows in CI, with theanimated image job as an example.
API

Operation

Description

DeleteWorkflow

Deleting workflow

Deletes workflow

DescribeWorkflow

Querying workflow

Queries workflow

DescribeWorkflowExecution

Querying workflow instance details

Queries workflow instance details

DescribeWorkflowExecutions

Querying workflow details list

Gets workflow instance list

TriggerWorkflowList

Triggering workflow

Executes workflow

Deleting Workflow
Feature description
This API is used to delete a workflow.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 823 of 1869

Cloud Infinite

public Boolean deleteWorkflow(MediaWorkflowListRequest request);

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)bucketName

Description

Type

Required

Bucket name in the format of BucketName-APPID . For more

StringYes

information, see Bucket Overview.

©2013-2022 Tencent Cloud. All rights reserved.

Page 824 of 1869

Cloud Infinite

workflowId

Workflow ID

StringYes

Response description
Success: true is returned upon success.
Failure: An error (such as the bucket does not exist) occurs, throwing the CosClientException or
CosServiceException exception. For more information, see Troubleshooting.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 825 of 1869

Cloud Infinite//1. Create a workflow request object
MediaWorkflowListRequest request = new MediaWorkflowListRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("examplebucket-1250000000");
request.setWorkflowId("aaaa");
Boolean response = client.deleteWorkflow(request);

Querying Workflow
Feature description
This API is used to search for a workflow.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 826 of 1869

Cloud Infinite

public MediaWorkflowListResponse describeWorkflow(MediaWorkflowListRequest request)

Parameter description
Parameter
bucketName
ids

Description
Bucket name in the format of BucketName-APPID . For more
information, see Bucket Overview.
Workflow ID. If you enter multiple IDs, separate them with commas (,).

©2013-2022 Tencent Cloud. All rights reserved.

Type

Required

StringYes

String

No

Page 827 of 1869

Cloud Infinite

nameWorkflow name.

StringNo

pageNumber

Page number.

StringNo

pageSize

Number of entries per page.

StringNo

Response description
Success: A workflow set response object is returned, which contains the workflow object set.
Failure: An error (such as authentication failure) occurs, throwing the "CosClientException" or "CosServiceException"
exception. For more information, see Troubleshooting.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 828 of 1869

Cloud Infinite//1. Create a workflow request object
MediaWorkflowListRequest request = new MediaWorkflowListRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("examplebucket-1250000000");
MediaWorkflowListResponse response = client.describeWorkflow(request);
List<MediaWorkflowObject> mediaWorkflowList = response.getMediaWorkflowList();Querying Workflow Instance Details©2013-2022 Tencent Cloud. All rights reserved.

Page 829 of 1869

Cloud Infinite

Feature description
This API is used to query the details of a workflow instance.
Method prototype

public MediaWorkflowExecutionResponse describeWorkflowExecution(MediaWorkflowListRe

Parameter description
Parameter

Description©2013-2022 Tencent Cloud. All rights reserved.

Type

RequiredPage 830 of 1869

Cloud Infinite

bucketName

Bucket name in the format of BucketName-APPID . For more

StringYes

StringYes

information, see Bucket Overview.
runId

Workflow instance ID

Response description
Success: A workflow instance response wrapper class is returned, which contains the workflow instance details
object.
Failure: An error (such as authentication failure) occurs, throwing the "CosClientException" or "CosServiceException"
exception. For more information, see Troubleshooting.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 831 of 1869

Cloud Infinite//1. Create a workflow request object
MediaWorkflowListRequest request = new MediaWorkflowListRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("examplebucket-1250000000");
request.setRunId("i34bfd8d7eae711ea89fe525400c******");MediaWorkflowExecutionResponse response = client.describeWorkflowExecution(request)

Querying Workflow Details List

©2013-2022 Tencent Cloud. All rights reserved.

Page 832 of 1869

Cloud Infinite

Feature description
This API is used to query the list of workflow details.
Method prototype

public MediaWorkflowExecutionsResponse describeWorkflowExecutions(MediaWorkflowList

Parameter description
Node Name

Description©2013-2022 Tencent Cloud. All rights reserved.

Type

RequiredPage 833 of 1869

Cloud Infinite

bucketName

Bucket name in the format of BucketName-APPID . For more

StringYes

information, see Bucket Overview.
workflowId

Workflow ID

StringYes

name

Filename

StringNoorderByTime

Desc (default) or Asc

StringNo

size

Maximum number of jobs that can be pulled. The default value is
10. The maximum value is 100.

StringNo

StringNo

StringNo

StringNo

StringNo

Workflow instance status. If you enter multiple statuses, separate
statesstartCreationTime

endCreationTime
nextToken

them with commas (,).
Valid values: All, Success, Failed, Running, Cancel. Default
value: All
Start time of the time range for job pulling in the format of %Y%m-%dT%H:%m:%S%z
End time of the time range for job pulling in the format of %Y%m-%dT%H:%m:%S%z
Context token for pagination

Response description
Success: A workflow instance set response object is returned, which contains the workflow object instance set.
Failure: An error (such as authentication failure) occurs, throwing the "CosClientException" or "CosServiceException"
exception. For more information, see Troubleshooting.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 834 of 1869

Cloud Infinite//1. Create a workflow request object
MediaWorkflowListRequest request = new MediaWorkflowListRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("examplebucket-1250000000");
request.setWorkflowId("w4e6963a18e2446ed8bc8f09410e******");MediaWorkflowExecutionsResponse response = client.describeWorkflowExecutions(reques
List<MediaWorkflowExecutionObject> workflowExecutionList = response.getWorkflowExec©2013-2022 Tencent Cloud. All rights reserved.

Page 835 of 1869

Cloud Infinite

Manually Triggering Workflow
Feature description
This API is used to manually trigger a workflow.
Method prototype

public MediaWorkflowListResponse triggerWorkflowList(MediaWorkflowListRequest reque©2013-2022 Tencent Cloud. All rights reserved.

Page 836 of 1869

Cloud Infinite

Sample request//1. Create a workflow request object
MediaWorkflowListRequest request = new MediaWorkflowListRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("DemoBucket-123456789");
request.setWorkflowId("we32f75950afe4a4682463d8158d*****");
request.setObject("1.mp4");
MediaWorkflowListResponse response = client.triggerWorkflowList(request);©2013-2022 Tencent Cloud. All rights reserved.

Page 837 of 1869

Cloud Infinite

Parameter description
Node Name
bucketName

Description
Bucket name in the format of BucketName-APPID . For more
information, see Bucket Overview.

Type

Required

StringYes

objectName of the object that requires workflow processing

StringYes

workflowId

ID of the workflow to trigger

StringYes

name

Name of the existing triggered job, which can contain up to 128
letters, digits, hyphens, and underscores and is empty by default.

StringNo

Response description
Success: The MediaWorkflowListResponse instance is returned.
Failure: An error (such as authentication failure) occurs, throwing the "CosClientException" or "CosServiceException"
exception. For more information, see Troubleshooting.

©2013-2022 Tencent Cloud. All rights reserved.

Page 838 of 1869

Cloud Infinite

Video Frame Capturing：

Last updated 2024-02-29 17:31:27

Overview
This document provides an overview of APIs and SDK code samples related to media file screen capturing in CI.
API

Operation

Description

GenerateSnapshot

Getting a screenshot of a media file atsome time point

Gets a screenshot of a media file at sometime point

Basic operations
Getting a screenshot of a media file at some time point
Feature description
This API is used to get a screenshot of a media file at some time point.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 839 of 1869

Cloud Infinite

public SnapshotResponse generateSnapshot(SnapshotRequest request);

Parameter description
Parameter

Description

Type

RequiredbucketName

Bucket name in the format of BucketName-APPID. For more
information, see Bucket Overview.

StringYes

Input

Media file location information.

Container

Yes©2013-2022 Tencent Cloud. All rights reserved.

Page 840 of 1869

Cloud Infinite

Time

Screenshot time point in seconds.

Float

Yes

OutputScreenshot storage location information.

Container

Yes

Width

Screenshot width. Default value: 0.

Int

No

Screenshot height. Default value: 0.
If Width and Height are both 0, the width and height of the
Heightvideo are used.
If one of them is 0, the other value is used to automatically
adapt to the aspect ratio of the video.

Int

No

FormatScreenshot format. Valid values: jpg, png. Default value: jpg.

StringNo

ModeFrame capturing method.
keyframe: Capture the last keyframe before the specified time
point.

StringNo

StringNoexactframe: Capture the frame at a specified time point.
Default value: exactframe.

RotateImage rotation method.
auto: Rotate automatically according to the video rotation
information.
off: Do not rotate.
Default value: auto.

Input has the following sub-nodes:
Parameter

Parent NodeDescription

Type

Required

ObjectRequest.Input

Filename

StringYes

Output has the following sub-nodes:
Parameter

Parent NodeDescription

Type

RequiredRegionRequest.Output

Bucket region

StringYes

BucketRequest.Output

File bucket

StringYes

ObjectRequest.Output

Filename

StringYes

Response description
Success: The screenshot entity information is returned.

©2013-2022 Tencent Cloud. All rights reserved.

Page 841 of 1869

Cloud Infinite

Failure: An error (such as the bucket does not exist) occurs, throwing the CosClientException or
CosServiceException exception. For more information, see Troubleshooting.
Sample request//1. Create a screenshot request object
SnapshotRequest request = new SnapshotRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("examplebucket-1250000000");
request.getInput().setObject("1.mp4");
request.getOutput().setBucket("examplebucket-1250000000");©2013-2022 Tencent Cloud. All rights reserved.

Page 842 of 1869

Cloud Infinite

request.getOutput().setRegion("ap-chongqing");
request.getOutput().setObject("test/1.jpg");
request.setTime("15");//3. Call the API to get the screenshot response object
SnapshotResponse response = client.generateSnapshot(request);©2013-2022 Tencent Cloud. All rights reserved.

Page 843 of 1869

Cloud Infinite

File Preview
Generating Sync Preview URL：

Last updated 2024-02-29 17:31:27

Overview
This document provides an overview of APIs and SDK code samples for file processing in CI.
API

Description

Generating a sync file-to-image preview URL

Generates a sync file-to-image preview URL.

Generating a sync file-to-HTML preview URL

Generates a sync file-to-HTML preview URL.

Basic operations
Sync file-to-image/HTML preview
Feature description
This API is used to generate a sync file-to-image/HTML preview URL by using different parameters.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 844 of 1869

Cloud Infinite

String GenerateDocPreviewUrl(DocHtmlRequest docJobRequest);

Parameter description
DocHtmlRequest has the following sub-nodes:
Node Name(Keyword)

Description

Type

RequiredbucketName

Bucket name in the format of BucketName-APPID. For more

StringYes

information, see Bucket Overview.

©2013-2022 Tencent Cloud. All rights reserved.

Page 845 of 1869

Cloud Infinite

objectKey

srcType

page

Name of the image file in the COS bucket. The COS bucket is
specified by Host. For example, if the file is img.jpg in the test
directory in the examplebucket-1250000000 bucket in Beijing,then Host is examplebucket-1250000000.cos.apbeijing.myqcloud.com, and ObjectKey is test/img.jpg.
Source data type. Currently, the file conversion feature
determines the source data type according to the file extension of
the COS object. If the object has no extension, you can set thisvalue.
Number of the page to be converted, which is counted from 1 bydefault. For spreadsheets, page indicates to convert the xth
image in the xth sheet.

StringYes

String

No

Int

No

StringNo

String

No

Int

No

String

No

Int

No

Int

No

Int

No

Type of the output target file. Valid values:png (converts to .png image)

dstTypejpg (converts to .jpg image)pdf (converts to .pdf file, where the page number cannot be
selected, and the page parameter does not take effect.)
html (converts to HTML online file)
If the input file format cannot be recognized, the jpg format will
be used by default. The default value for the SDK is html.

passwordcomment

Password to open the Office file. If you need to convert apassword-protected file, set this field.
Whether to hide comments and apply track changes. Default
value:0.
0: Hide comments and apply track changes.
1: Show comments and track changes.
Processing parameters for the output image. All parameters ofbasic image processing are supported. To specify multiple

ImageParams

qualityscale

parameters, separate them with pipeline operators. In this way,
the image can be processed by multiple parameters in sequencein the same request.
Quality of the generated preview image. Value range: [1, 100].
Default value: 100. For example, if the value is 100, the quality of
the generated image will be 100%.
Scaling parameter of the preview image. Value range: [10, 200].
Default value: 100. For example, if the value is 200, the image
will be scaled up (enlarged) by 200%.

imageDpi

Renders the image based on the specified DPI. This parameter©2013-2022 Tencent Cloud. All rights reserved.

Page 846 of 1869

Cloud Infinite

works together with scale. Value range: 96–600. Default value:
96. The width of the output image must be less than 65500 px.

Response description
Success: The preview URL is returned.
Failure: An error (such as the bucket does not exist) occurs, throwing the "CosClientException" or"CosServiceException" exception. For more information, please see Troubleshooting.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 847 of 1869

Cloud Infinite//1. Create a request object
DocHtmlRequest request = new DocHtmlRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("markjrzhang-1251704708");// For conversion to image, `dstType` is `DocHtmlRequest.DocType.jpg`.
request.setDstType(DocHtmlRequest.DocType.html);
request.setObjectKey("1.pptx");
request.setPage("1");//3. Call the API to get the job response object
String previewUrl = client.GenerateDocPreviewUrl(request);
System.out.println(previewUrl);©2013-2022 Tencent Cloud. All rights reserved.

Page 848 of 1869

Cloud Infinite

Content Moderation
Image Moderation：

Last updated 2024-02-29 17:31:27

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for image moderation.
API

Description

Moderating single image

Scans existing data stored in COS for pornographic, illegal, and advertising
images.

Batch moderating
imagesModerates multiple images in batches.

Single Image Moderation
Feature description
The existing data scan feature of image moderation leverages CI's persistent processing API to scan existing datastored in COS for pornographic, illegal, and advertising images.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 849 of 1869

Cloud Infinite

ImageAuditingResponse imageAuditing(ImageAuditingRequest request);

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 850 of 1869

Cloud Infinite//1. Create a job request object
ImageAuditingRequest request = new ImageAuditingRequest();//2. Add request parameters as detailed in the API documentation//2.1 Set the request bucket
request.setBucketName("examplebucket-1250000000");//2.2 Set the moderation type
request.setDetectType("porn,ads");//2.3 Set the image location in the bucket
request.setObjectKey("1.png");//3. Call the API to get the job response object
ImageAuditingResponse response = client.imageAuditing(request);©2013-2022 Tencent Cloud. All rights reserved.

Page 851 of 1869

Cloud Infinite

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

Description

Type

Required

StringNo

StringNo

StringNo

String

No

Int

No

Int

No

Name of the image file in the COS bucket. The COS bucket is
specified by Host . For example, if the file is img.jpg in
ObjectKey

the test directory in the examplebucket-1250000000
bucket in Beijing, then Host is examplebucket1250000000.cos.ap-beijing.myqcloud.com , andObjectKey is test/img.jpg .
Unique identifier of the moderation policy. You can configure thescenes you want to moderate on the moderation policy page inthe console, such as pornographic, adverting, and illegal
information. For configuration guidelines, see Setting

bizType

Moderation Policy. You can get bizType in the console. If
bizType is specified, the moderation request will perform
moderation based on the scenes configured in the moderation
policy. If bizType is not specified, the default moderation
policy will be used automatically.
The scene to be moderated, such as Porn (pornography)
and Ads (advertising). This parameter will no longer be

detectTypemaintained in the future. You can pass in multiple types andseparate them by comma, such as Porn,Ads . If you need tomoderate more scenes, use the bizType parameter.
You can enter a detectUrl value to moderate an image
accessible over the public network. If detectUrl is not
specified, the backend will moderate by ObjectKey bydetectUrl

default. If detectUrl is specified, the backend will
moderate by detectUrl , and there will be no need to enter
ObjectKey . Sample detectUrl :http://www.example.com/abc.jpg .

interval

maxFrames

For GIF image moderation, you can use this parameter toconfigure the frame capturing interval. The default value is 5 ,indicating to capture a frame every five frames starting from thefirst frame (included).
The maximum number of frames to be captured for GIF image
moderation, which must be greater than 0. The default value is©2013-2022 Tencent Cloud. All rights reserved.

Page 852 of 1869

Cloud Infinite

5 , indicating to capture five frames at most.
Whether to compress the image that exceeds the size limit
before moderation. Valid values: 0 (no), 1 (yes). Default
largeImageDetectvalue: 0 . Note: Images up to 32 MB in size can becompressed, and image compression fees will be charged. For
large animated images such as GIF, the compression time is

Int

No

String

No

Int

No

StringNolong, which may cause the moderation to fail due to timeout.
dataIdImage ID. This field will return the original content in the result,which can contain up to 512 bytes.
Whether to moderate asynchronously. Valid values: 0

async(returns the result synchronously); 1 (moderates
asynchronously). Default value: 0 .
The moderation result (in Detail mode) can be sent to yourcallback

callback address in the form of a callback. This parameter takes
effect for async moderation. Addresses starting with
http:// or https:// are supported, such as
http://www.callback.com .

Response description
Success: An ImageAuditingResponse instance is returned upon success, which contains the moderation
result.
Failure: An error (such as the bucket does not exist) occurs, reporting the CosClientException or
CosServiceException exception. For more information, see Troubleshooting.
Content of the ImageAuditingResponse object after it is converted to JSON:©2013-2022 Tencent Cloud. All rights reserved.

Page 853 of 1869

Cloud Infinite{"requestId":"NjJkOTI3YTJfNGNhY2ZhMDlfOWJhOV9hZ*****","jobId":"si461d9f9608de11ed9b3d525400b*****","object":"1.png","compressionResult":"0","result":"0","label":"Normal","category":"","subLabel":"","score":"42","text":"",©2013-2022 Tencent Cloud. All rights reserved.

Page 854 of 1869

Cloud Infinite"state":"Success","pornInfo":{"code":"0","msg":"OK","hitFlag":"0","score":"0","label":"","ocrResults":{"text":"","keywords":""},"category":""}}The response body is as described below:
Parameter

Type

Description

DataIdStringJobId

StringImage moderation job ID.

State

StringStatus of the moderation job. Valid value: Success .

ObjectStringUrl

StringCompressionResult

Int

Image ID. The original content will be returned in the moderation result,which can contain up to 512 bytes.

The name of the image stored in the COS bucket, which will be returned if
ObjectKey is selected during job creation.
The URL of the image file, which will be returned if detect-url isselected during job creation.
Whether the image is compressed. Valid values: 0 (no), 1 (yes).
This field indicates the moderation result. You can perform subsequent
operations based on the result. We recommend you handle different

ResultInt

results based on your business needs. Valid values: 0 (normal), 1(sensitive), and 2 (suspiciously sensitive, with human review
recommended).
This field is used to return the maliciousness tag with the highest
priority in the detection result, which represents the moderation result

Label

Stringsuggested by the model. We recommend you handle different types ofviolations and suggestions based on your business needs. Returned
values: Normal , Porn , Ads , and other types of unsafe orinappropriate content.

Category

StringThis field is a subset of Label , indicating the specific moderation©2013-2022 Tencent Cloud. All rights reserved.

Page 855 of 1869

Cloud Infinite

category hit; for example, Sexy presents the sexy category in the
Porn tag.
SubLabel

StringSecond-level tag hit by the image.
The confidence the moderation result hits the moderation scene. Value

Score

range: 0–100. The higher the value, the more likely the content hits thecurrently returned moderation scene. For example, Porn 99 means

Intthat the content is very likely to be pornographic.
The specific text content recognized by OCR in the image, which will be

TextStringPornInfo

Container

AdsInfo

Container

returned if text content detection is enabled in the moderation policy.
The moderation result of the pornographic information moderation
scene.
The moderation result of the advertising information moderation scene.

The moderation information ( PornInfo and AdsInfo ) has the following sub-nodes:
Parameter

Type

Code

Int

Msg

StringDescription
Error code. 0 indicates a success, while other numbers correspond to different
errors. For more information, see Error Codes.
The specific error message, which will be OK if the moderation result is normal.
The moderation result returned for the moderation scene. Returned values: 0

HitFlagInt(normal); 1 (confirmed as a violation of the current scene); 2 (suspected asa violation of the current scene).
The confidence the moderation result hits the moderation scene. Value range: 0–

Score

Int

100. The higher the value, the more likely the content hits the currently returned
moderation scene. A value in the range of 0–60, 61–90, or 91–100 means theimage is normal, suspiciously sensitive, or sensitive respectively. For example,
Porn 99 means that the content is very likely to be pornographic.

Label

StringCategory

StringThis field indicates the overall result tag of the screenshot, which may be
SubLabel , a person name, etc.
This field is a subset of Label , indicating the specific moderation category hit;for example, Sexy presents the sexy category in the Porn tag.
This field indicates the specific sub-tag hit by the moderation job; for example,

SubLabel

StringSexBehavior is a sub-tag under the Porn tag.
Note: This field may return null, indicating that no specific sub-tags are hit.

©2013-2022 Tencent Cloud. All rights reserved.

Page 856 of 1869

Cloud Infinite

OcrResults

LibResults

Container

This field represents the detailed OCR result, including the text recognition resultArrayand hit keyword. It will be returned if there is non-compliant content.

Container

This field returns results based on recognition against the risk library.

Array

Note: This field will not be returned if no samples in the risk library are hit.

LibResults has the following sub-nodes:
Parameter

Type

Description

ImageId

StringThis field represents the hit image sample ID in the risk library.
This field returns the confidence under the current tag. Value range: 0–100. The

Score

Stringhigher the value, the more likely the image hits a sample in the risk library. For
example, Porn 99 means that the content is very likely to hit a pornographic
sample in the library.

OcrResults has the following sub-nodes:
Parameter

Type

Description

Text

String

The specific text content recognized by OCR in the image.

Keywords

Array

Keywords hit by the current moderation scene.
This parameter is used to return the position (X and Y coordinates of the top-leftLocationContainer

Parameter

Type

Description

Float

This parameter is used to return the pixel position of the abscissa (X) of the
top-left corner of the detection frame. It can be combined with otherX

corner, length, width, and rotation angle) of the OCR detection frame in the image
for quick location of the recognized text.

parameters to uniquely determine the size and position of the detection frame.

Y

Float

This parameter is used to return the pixel position of the ordinate of the topleft corner (Y) of the detection frame. It can be combined with other parameters
to uniquely determine the size and position of the detection frame.
This parameter is used to return the width of the detection frame (the length

Width

Float

HeightFloatstarting from the top-left corner and extending to the right on the X axis). It canbe combined with other parameters to uniquely determine the size and positionof the detection frame.
This parameter is used to return the height of the detection frame (the length
starting from the top-left corner and extending down the Y axis). It can be©2013-2022 Tencent Cloud. All rights reserved.

Page 857 of 1869

Cloud Infinite

combined with other parameters to uniquely determine the size and position of
the detection frame.

RotateFloat

This parameter is used to return the rotation angle of the detection frame.
Valid values: 0–360 (degrees), and the direction is counterclockwise
rotation. This parameter can be combined with the X and Y coordinateparameters to uniquely determine the specific position of the detection frame.

Batch Image Moderation
Feature description
The batch image moderation API adopts a sync POST request method. You can use this API to perform content
moderation on multiple image files.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 858 of 1869

Cloud Infinite

BatchImageAuditingResponse batchImageAuditing(BatchImageAuditingRequest request);

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 859 of 1869

Cloud Infinite//1. Create a job request object
BatchImageAuditingRequest request = new BatchImageAuditingRequest();//2. Add request parameters as detailed in the API documentation//2.1 Set the request bucket
request.setBucketName("examplebucket-1250000000");//2.2 Add the request content
List<BatchImageAuditingInputObject> inputList = request.getInputList();BatchImageAuditingInputObject input = new BatchImageAuditingInputObject();
input.setObject("1.jpg");
input.setDataId("DataId");
inputList.add(input);©2013-2022 Tencent Cloud. All rights reserved.

Page 860 of 1869

Cloud Infinite

input = new BatchImageAuditingInputObject();
input.setUrl("https://examplebucket-1250000000.cos.ap-chongqing.myqcloud.com/1.png"
input.setDataId("DataId");
inputList.add(input);//2.2 Set the moderation type
request.getConf().setDetectType("all");//3. Call the API to get the job response object
BatchImageAuditingResponse response = client.batchImageAuditing(request);
List<BatchImageJobDetail> jobList = response.getJobList();Parameter description
request has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

RequestNone

Batch image moderation configuration.

Container

Yes

Description

Type

RequiredContent to be moderated. If there are multiple

Container

images, pass in multiple Input structures.

Array

Moderation rule configuration.

Container

Request has the following sub-nodes:
Node Name(Keyword)

Parent
Node

Input

Request

Conf

RequestYes
Yes

Input has the following sub-nodes:
Node Name(Keyword)

ObjectParent NodeRequest.Input

Description
Name of the image file stored in the COS
bucket; for example, if the file isimage.jpg in the test directory,
then the filename is test/image.jpg .

Type

Required

StringNo

StringNo

Either Object or Url can be selected
at a time.
Url

Request.Input

Full URL of the image file, such as
http://a-1250000.cos.apshanghai.myqcloud.com/image.jpg .

©2013-2022 Tencent Cloud. All rights reserved.

Page 861 of 1869

Cloud Infinite

Either Object or Url can be selected
at a time.

Interval

Request.Input

Frame capturing frequency, which takes
effect for GIF images only. The default value
is 5 , indicating to capture a frame every

Int

No

Int

No

String

No

Int

No

ContainerNo

five frames starting from the first frame(included).

MaxFrames

Request.Input

The maximum number of frames to be
captured, which takes effect for GIF images
only. The default value is 5 , indicating tocapture only five frames of the GIF image formoderation. The parameter value must be
greater than 0.

DataIdRequest.Input

Image ID. This field will return the originalcontent in the result, which can contain up to
512 bytes.
Whether to compress the image thatexceeds the size limit before moderation.
Valid values: 0 (no), 1 (yes). Default

LargeImageDetect

Request.Input

value: 0 .
Note: Images up to 32 MB in size can becompressed, and compression fees will becharged.

UserInfo

Request.Input

Business field.

UserInfo has the following sub-nodes:
Node Name(Keyword)

Description

Type

RequiredTokenId

Account information, which can contain up to 128 bytes.

StringNo

Nickname

Nickname information, which can contain up to 128 bytes.

StringNo

DeviceId

Device information, which can contain up to 128 bytes.

StringNo

AppId

Unique app ID, which can contain up to 128 bytes.

StringNo

Room

Room ID information, which can contain up to 128 bytes.

StringNo

IP

IP address information, which can contain up to 128 bytes.

StringNo©2013-2022 Tencent Cloud. All rights reserved.

Page 862 of 1869

Cloud Infinite

Type

Business type, which can contain up to 128 bytes.

String

No

ReceiveTokenId

User account to receive messages, which can contain up to
128 bytes.

String

No

GenderGender information, which can contain up to 128 bytes.

StringNo

Level

Level information, which can contain up to 128 bytes.

StringNo

Role

Role information, which can contain up to 128 bytes.

StringNo

Type

Required

StringNo

String

No

IntegerNo

String

No

Conf has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription
Unique identifier of the moderation policy. You canconfigure the scenes you want to moderate on themoderation policy page in the console, such as
pornographic, adverting, and illegal information. For
configuration guidelines, see Setting Moderation

BizTypeRequest.Conf

Policy. You can get BizType in the console. If
BizType is specified, the moderation request
will perform moderation based on the scenes
configured in the moderation policy. If BizType
is not specified, the default moderation policy will
be used automatically.
The scene to be moderated, such as Porn
(pornography) and Ads (advertising). This

DetectType

Request.Confparameter will no longer be maintained in the
future. You can pass in multiple types and separate
them by comma, such as Porn,Ads . If you
need to moderate more scenes, use the
BizType parameter.
Whether to moderate asynchronously. Valid values:

Async

Request.Conf

0 (returns the result synchronously); 1(moderates asynchronously). Default value: 0 .
The moderation result (in Detail mode) can besent to your callback address in the form of a

Callback

Request.Conf

callback. This parameter takes effect for async
moderation. Addresses starting with http://
or https:// are supported, such as
http://www.callback.com .

©2013-2022 Tencent Cloud. All rights reserved.

Page 863 of 1869

Cloud Infinite

Note:
Moderation through Object is a private network operation and will not generate public network traffic.
Moderation through Url will generate public network traffic with regard to the origin where the image resides.
Response description
Success: A BatchImageAuditingResponse instance is returned upon success, which contains the moderation
result.
Failure: An error (such as the bucket does not exist) occurs, reporting the CosClientException or
CosServiceException exception. For more information, see Troubleshooting.
Content of the ImageAuditingResponse object after it is converted to JSON:©2013-2022 Tencent Cloud. All rights reserved.

Page 864 of 1869

Cloud Infinite{"requestId":"NjJkOTJjMjVfMTIwNjUzMDlfNDg5OF8*****","jobList":[{"dataId":"DataId","jobId":"sif6423b8008e011ed9b3d525400*****","category":"","label":"Normal","result":"0","object":"1.jpg","score":"0",©2013-2022 Tencent Cloud. All rights reserved.

Page 865 of 1869

Cloud Infinite"subLabel":"","text":"","code":"","message":"","url":"","compressionResult":"0","pornInfo":{"code":"0","msg":"OK","hitFlag":"0","score":"45","label":"","keywords":"","count":"","subLabel":"","ocrResults":{"text":"","keywords":""},"category":""},"adsInfo":{"code":"0","msg":"OK","hitFlag":"0","score":"0","label":"","keywords":"","count":"","subLabel":"","ocrResults":{"text":"","keywords":""},"category":""},"userInfo":{"tokenId":"","nickname":"","deviceId":"","appId":"","room":"","ip":"","type":"","receiveTokenId":"","gender":"","level":"",©2013-2022 Tencent Cloud. All rights reserved.

Page 866 of 1869

Cloud Infinite"role":""},"ocrResults":{"text":"","keywords":""}},{"dataId":"DataId","jobId":"sif640a3c108e011ed9b3d525400*****","category":"","label":"Normal","result":"0","object":"","score":"42","subLabel":"","text":"","code":"","message":"","url":"https://demo-1234567890.cos.ap-chongqing.myqcloud.com/1.png","compressionResult":"0","pornInfo":{"code":"0","msg":"OK","hitFlag":"0","score":"0","label":"","keywords":"","count":"","subLabel":"","category":"","ocrResults":{"text":"","keywords":""}},"adsInfo":{"code":"0","msg":"OK","hitFlag":"0","score":"0","label":"","keywords":"","count":"","subLabel":"","category":"","ocrResults":{©2013-2022 Tencent Cloud. All rights reserved.

Page 867 of 1869

Cloud Infinite"text":"","keywords":""}},"userInfo":{"tokenId":"","nickname":"","deviceId":"","appId":"","room":"","ip":"","type":"","receiveTokenId":"","gender":"","level":"","role":""},"ocrResults":{"text":"","keywords":""}}]}
The response body is as described below:
Response has the following sub-nodes:
Parameter

Type

Description

JobsDetail

Array

Image moderation result.

RequestId

StringThe ID automatically generated by the server for a request when the request is sent,
which can help locate problems faster.

JobsDetail has the following sub-nodes:
Parameter

Type

Description

CodeStringError code, which will be returned only in case of a failure. For more
information, see Error Codes.

Message

StringError message, which will be returned only in case of a failure.

DataIdStringImage ID. The original content will be returned in the moderation result,which can contain up to 512 bytes.

©2013-2022 Tencent Cloud. All rights reserved.

Page 868 of 1869

Cloud Infinite

JobId

StringModeration job ID.

State

StringStatus of the moderation job. Valid values: Success , Failed .

ObjectString

The name of the image file stored in the COS bucket, which will be
returned if Object is selected during job creation.

Url

StringCompressionResult

Integer

The URL of the image file, which will be returned if Url is selectedduring job creation.
Whether the image is compressed. Valid values: 0 (no), 1 (yes).
This field is used to return the maliciousness tag with the highest
priority in the detection result, which represents the moderation result

Label

Stringsuggested by the model. We recommend you handle different types ofviolations and suggestions based on your business needs. Returned
values: Normal , Porn , Ads .
This field indicates the moderation result. You can perform subsequent
operations based on the result. We recommend you handle different

ResultInteger

results based on your business needs. Valid values: 0 (normal), 1(sensitive), and 2 (suspiciously sensitive, with human review
recommended).
The confidence the moderation result hits the moderation scene. Value

Score

Integerrange: 0–100. The higher the value, the more likely the content hits thecurrently returned moderation scene. For example, Porn 99 meansthat the content is very likely to be pornographic.

Category

StringModeration type hit by the image.

SubLabel

StringSecond-level tag hit by the image.

Text

StringPornInfo

Container

The moderation result of the pornographic information moderation
scene.

AdsInfo

Container

The moderation result of the advertising information moderation scene.

UserInfo

Container

UserInfo set in the request, which will be returned as-is.

ListInfo

Container

Blocklist/Allowlist status of the account.

The specific text content recognized by OCR in the image, which will be
returned if text content detection is enabled in the moderation policy.

The moderation information (such as PornInfo and AdsInfo ) has the following sub-nodes:©2013-2022 Tencent Cloud. All rights reserved.

Page 869 of 1869

Cloud Infinite

Parameter

Type

Code

Integer

Msg

StringDescription
Error code for individual moderation scenes. 0: Succeeded; other values:
Failed. For more information, see Error Codes.
The specific error message, which will be OK if the moderation result isnormal.
The moderation result returned for the moderation scene. Returned values:

HitFlag

Integer

0 (normal); 1 (confirmed as a violation of the current scene); 2(suspected as a violation of the current scene).
The confidence the moderation result hits the moderation scene. Value range:

Score

Integer

0–100. The higher the value, the more likely the content hits the currently
returned moderation scene. For example, Porn 99 means that the content
is very likely to be pornographic.

Label

StringCategory

String

SubLabel

String

OcrResults

Container
Array

LibResults

The overall result tag of the image, which may be SubLabel , a person
name, etc.
This field is a subset of Label , indicating the specific moderation category
hit; for example, Sexy presents the sexy category in the Porn tag.
Second-level tag of the image.
This field represents the detailed OCR result, including the text coordinate
information and text recognition result. It will be returned if there is noncompliant content.

Container

This field returns results based on recognition against the risk library. Note:

Array

This field will not be returned if no samples in the risk library are hit.

LibResults has the following sub-nodes:
Node Name(Keyword)
ImageIdType

Description

StringThis field represents the hit image sample ID in the risk library.
This field returns the confidence under the current tag. Value range: 0–100. The

Score

Integerhigher the value, the more likely the image hits a sample in the risk library. For
example, Porn 99 means that the content is very likely to hit a pornographic
sample in the library.

OcrResults has the following sub-nodes:
Node Name (Keyword)Type©2013-2022 Tencent Cloud. All rights reserved.

Description

Page 870 of 1869

Cloud Infinite

Text

StringSensitive OCR text content

Keywords

String Array

Sensitive words in the text content

UserInfo has the following sub-nodes (same as UserInfo in the request):
Node Name(Keyword)

Description

Type

RequiredTokenId

Account information, which can contain up to 128 bytes.

StringNo

Nickname

Nickname information, which can contain up to 128 bytes.

StringNo

DeviceId

Device information, which can contain up to 128 bytes.

StringNo

AppId

Unique app ID, which can contain up to 128 bytes.

StringNo

Room

Room ID information, which can contain up to 128 bytes.

StringNo

IP

IP address information, which can contain up to 128 bytes.

StringNo

Type

Business type, which can contain up to 128 bytes.

String

No

ReceiveTokenId

User account to receive messages, which can contain up to
128 bytes.

String

No

GenderGender information, which can contain up to 128 bytes.

StringNo

Level

Level information, which can contain up to 128 bytes.

StringNo

Role

Role information, which can contain up to 128 bytes.

StringNo

ListInfo has the following sub-nodes:
Node Name (Keyword)

Type

Description

ListResults

Container Array

Results in all hit lists.

ListResults has the following sub-nodes:
Node Name (Keyword)

Type

Description

ListType

StringType of the hit list. Valid values: 0 (allowlist), 1 (blocklist).

ListName

StringName of the hit list.

EntityStringEntity hit in the list.

©2013-2022 Tencent Cloud. All rights reserved.

Page 871 of 1869

Cloud Infinite©2013-2022 Tencent Cloud. All rights reserved.

Page 872 of 1869

Cloud Infinite

Video Moderation：

Last updated 2024-02-29 17:31:27

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for video moderation.
API

Description

Submitting video moderation job

Submits video moderation job.

Querying video moderation job result

Queries the result of specified video moderation job.

Submitting Video Moderation Job
Feature description
This API is used to submit a video moderation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 873 of 1869

Cloud Infinite

VideoAuditingResponse createVideoAuditingJob(VideoAuditingRequest request);

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 874 of 1869

Cloud Infinite//1. Create a job request object
VideoAuditingRequest request = new VideoAuditingRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("examplebucket-1250000000");
request.getInput().setObject("1.mp4");
request.getConf().setDetectType("Porn,Ads");
request.getConf().getSnapshot().setCount("10");
request.getConf().getSnapshot().setMode("Interval");request.getConf().getSnapshot().setTimeInterval("10");//3. Call the API to get the job response object
VideoAuditingResponse response = client.createVideoAuditingJob(request);©2013-2022 Tencent Cloud. All rights reserved.

Page 875 of 1869

Cloud Infinite

Parameter description
Request has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

Input

RequestVideo to be moderated.

Container

Yes

Conf

RequestModeration rule configuration.

Container

Yes

Input has the following sub-nodes:
Node
Name

Parent NodeDescription

Type

Required

Request.Input

Name of the video file stored in the COS bucket; forexample, if the file is video.mp4 in the test

StringYes

StringNo(Keyword)

Objectdirectory, then the filename is test/video.mp4 .
Full URL of the video file, such as
http://examplebucketUrl

Request.Input

1250000000.cos.apshanghai.myqcloud.com/test.mp4 . Either
Object or Url can be selected at a time.

Conf has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

StringYes

Container

Yes

StringNo

The scene to be moderated, such as Porn
DetectType

Request.Conf(pornography) and Ads (advertising). You
can pass in multiple types and separate themby comma, such as Porn,Ads .

Snapshot

Request.Conf

Video image moderation is implemented bytaking a certain number of screenshots basedon the video frame capturing capability andthen moderating the screenshots one by one.
This parameter is used to specify theconfiguration of video frame capturing.

Callback

Request.Conf

Callback address, which must start with
http:// or https:// .

©2013-2022 Tencent Cloud. All rights reserved.

Page 876 of 1869

Cloud Infinite

CallbackVersion

Request.Conf

Structure of the callback content. Validvalues: Simple (the callback content

StringNo

String

No

IntegerNo

contains basic information), Detail (thecallback content contains detailed
information). Default value: Simple .
BizType

DetectContent

Request.Conf

Request.Conf

Moderation policy. If this parameter is not
specified, the default policy will be used.
Whether to moderate video sound. Validvalues: 0 (moderates the video image
only), 1 (moderates both the video image
and video sound). Default value: 0 .

Snapshot has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

StringNo

Frame capturing mode. Valid values:
Interval (interval mode), Average(average mode), Fps (fixed frame ratemode).
Interval mode: The
TimeInterval and Countparameters take effect. If Count is set
but TimeInterval is not, all frames
ModeRequest.Conf.Snapshot

will be captured to generate a total ofCount images.
Average mode: The Countparameter takes effect, indicating tocapture a total of Count images at an
average interval in the entire video.
Fps mode: TimeInterval
indicates how many frames to capture persecond, and Count indicates how many
frames to capture in total.

Count

TimeInterval

Request.Conf.Snapshot

The number of captured frames. Value
range: (0, 10000].

String

No

Request.Conf.Snapshot

Video frame capturing frequency. Value
range: (0.000, 60.000] seconds. The value
supports the float format, accurate to themillisecond.

Float

No

©2013-2022 Tencent Cloud. All rights reserved.

Page 877 of 1869

Cloud Infinite

Response description
Success: The VideoAuditingResponse media moderation job result object is returned upon success.
Failure: An error (such as the bucket does not exist) occurs, reporting the CosClientException or
CosServiceException exception. For more information, see Troubleshooting.

Querying Video Moderation Job Result
Feature description
This API is used to query the status and result of a video moderation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 878 of 1869

Cloud Infinite

VideoAuditingResponse describeAuditingJob(VideoAuditingRequest request);

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 879 of 1869

Cloud Infinite//1. Create a job request object
VideoAuditingRequest request = new VideoAuditingRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("examplebucket-1250000000");
request.setJobId("av81591b4bbd2211eb80235254008*****");//3. Call the API to get the job response object
VideoAuditingResponse response = client.describeAuditingJob(request);

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 880 of 1869

Cloud Infinite

Parameter
bucketName
jobId

Description
Bucket name in the format of BucketName-APPID . For more
information, see Bucket Overview.
ID of the job to be queried.

Type

Required

StringYes

StringYes

Response description
Success: The VideoAuditingResponse moderation job result object is returned.
Failure: If an error (such as authentication failure) occurs, the CosClientException or
CosServiceException exception will be reported. For more information, see Troubleshooting.

©2013-2022 Tencent Cloud. All rights reserved.

Page 881 of 1869

Cloud Infinite

Audio Moderation：

Last updated 2024-02-29 17:31:27

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for audio moderation.
API

Description

Submitting audio moderation job

Submits audio moderation job.

Querying audio moderation job result

Queries the result of specified audio moderation job.

Submitting Audio Moderation Job
Feature description
This API is used to submit an audio moderation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 882 of 1869

Cloud Infinite

AudioAuditingResponse createAudioAuditingJob(AudioAuditingRequest request);

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 883 of 1869

Cloud Infinite//1. Create a job request object
AudioAuditingRequest request = new AudioAuditingRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("examplebucket-1250000000");
request.getInput().setObject("pron.mp3");
request.getConf().setDetectType("Porn,Ads");
request.getConf().setCallback("http://cloud.tencent.com/");//3. Call the API to get the job response object
AudioAuditingResponse response = client.createAudioAuditingJobs(request);©2013-2022 Tencent Cloud. All rights reserved.

Page 884 of 1869

Cloud Infinite

Parameter description
Request has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

Input

RequestContent to be moderated.

Container

Yes

Conf

RequestModeration rule configuration.

Container

Yes

Input has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

StringNo

StringNo

Name of the audio file stored in the COS bucket; forexample, if the file is audio.mp3 in the test
ObjectRequest.Input

directory, then the filename is test/audio.mp3 .
Either Object or Url can be selected at atime.
Full URL of the audio file, such as
http://examplebucket-

Url

Request.Input

1250000000.cos.apshanghai.myqcloud.com/audio.mp3 . Either
Object or Url can be selected at a time.

Conf has the following sub-nodes:
Node Name(Keyword)

BizTypeParent NodeDescription

Type

Required

Request.Conf

Moderation policy. If this parameter is not
specified, the default policy will be used. The
policy can be configured in the console.

StringNo

StringNo

StringNo

The scene to be moderated, such as Porn
(pornography) and Ads (advertising). This
DetectType

Request.Confparameter will no longer be maintained in the
future. You can pass in multiple types andseparate them by comma, such as Porn,Ads .
If you need to moderate more scenes, use the
BizType parameter.

Callback

Request.Conf

The moderation result can be sent to yourcallback address in the form of a callback.
Addresses starting with http:// or©2013-2022 Tencent Cloud. All rights reserved.

Page 885 of 1869

Cloud Infinite

https:// are supported, such as
http://www.callback.com .

CallbackVersion

Request.Conf

Structure of the callback content. Valid values:
Simple (the callback content contains basic
information), Detail (the callback content contains
detailed information). Default value: Simple.

stringNo

Response description
Success: The AudioAuditingResponse audio moderation job result object is returned upon success.
Failure: An error (such as the bucket does not exist) occurs, reporting the CosClientException or
CosServiceException exception. For more information, see Troubleshooting.

Querying Audio Moderation Job
Feature description
This API is used to query the status and result of an audio moderation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 886 of 1869

Cloud Infinite

AudioAuditingResponse describeAuditingJob(AudioAuditingRequest request);

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 887 of 1869

Cloud Infinite//1. Create a job request object
AudioAuditingRequest request = new AudioAuditingRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("examplebucket-1250000000");
request.setJobId("sacbf7269cbd2e11eba5325254009*****");//3. Call the API to get the job response object
AudioAuditingResponse response = client.describeAudioAuditingJob(request);

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 888 of 1869

Cloud Infinite

Parameter
bucketName
jobId

Description
Bucket name in the format of BucketName-APPID . For more
information, see Bucket Overview.
ID of the job to be queried.

Type

Required

StringYes

StringYes

Response description
Success: The AudioAuditingResponse moderation job result object is returned. For field descriptions, see
Querying Audio Moderation Job Result.
Failure: If an error (such as authentication failure) occurs, the CosClientException or
CosServiceException exception will be reported. For more information, see Troubleshooting.

©2013-2022 Tencent Cloud. All rights reserved.

Page 889 of 1869

Cloud Infinite

File Moderation：

Last updated 2024-02-29 17:31:27

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for file moderation.
API

Description

Submitting file moderation job

Submits file moderation job.

Querying file moderation job result

Queries the result of specified file moderation job.

Submitting File Moderation Job
Feature description
This API is used to submit a file moderation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 890 of 1869

Cloud Infinite

DocumentAuditingResponse createAuditingDocumentJobs(DocumentAuditingRequest request

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 891 of 1869

Cloud Infinite//1. Create a job request object
DocumentAuditingRequest request = new DocumentAuditingRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("examplebucket-1250000000");//2.1.1 Set the object address// request.getInput().setObject("1.txt");//2.1.2 Or, directly set the file address
request.getInput().setUrl("https://markjrzhang-1251704708.cos.ap-chongqing.myqcloud//2.2 Set the moderation type parameterrequest.getConf().setDetectType("all");//3. Call the API to get the job response object©2013-2022 Tencent Cloud. All rights reserved.

Page 892 of 1869

Cloud Infinite

DocumentAuditingResponse response = client.createAuditingDocumentJobs(request);

Parameter description
Request has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

Input

RequestContent to be moderated.

Container

Yes

Conf

RequestModeration rule configuration.

Container

Yes

Input has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeDescription

Type

Required

Url

Request.Input

Full URL of the file, such as
http://www.example.com/doctest.doc .

StringYes

StringNo

File type. If this parameter is not specified, the fileextension will be used as the type by default, such as
Type

Request.Input

DOC, DOCX, PPT, and PPTX.
If the file has no extension, this field must be specified;otherwise, moderation will fail.

Conf has the following sub-nodes:
Node
Name

Parent NodeDescription

Type

Required

Request.Conf

Moderation policy. If this parameter is not specified,the default policy will be used. The policy can be
configured in the console. For more information, see
Setting Moderation Policy.

StringNo

StringNo

StringNo(Keyword)

BizType

The scene to be moderated, such as Porn
DetectType

Request.Conf

Callback

Request.Conf(pornography) and Ads (advertising). You canpass in multiple types and separate them by comma,
such as Porn,Ads .
The moderation result can be sent to your callback
address in the form of a callback. Addresses starting©2013-2022 Tencent Cloud. All rights reserved.

Page 893 of 1869

Cloud Infinite

with http:// or https:// are supported,
such as http://www.callback.com .

Response description
Success: The DocumentAuditingResponse file moderation job result object is returned upon success.
Failure: An error (such as the bucket does not exist) occurs, reporting the CosClientException or
CosServiceException exception. For more information, see Troubleshooting.

Querying File Moderation Job
Feature description
This API is used to query the status and result of a file moderation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 894 of 1869

Cloud Infinite

DocumentAuditingResponse describeAuditingJob(DocumentAuditingRequest request);

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 895 of 1869

Cloud Infinite//1. Create a job request object
DocumentAuditingRequest request = new DocumentAuditingRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("examplebucket-1250000000");
request.setJobId("sdd5d1cc630fdc11ecb3fa5254009******");//3. Call the API to get the job response object
DocumentAuditingResponse response = client.describeAuditingDocumentJob(request);

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 896 of 1869

Cloud Infinite

Parameter
bucketName
jobId

Description
Bucket name in the format of BucketName-APPID . For more
information, see Bucket Overview.
ID of the job to be queried.

Type

Required

StringYes

StringYes

Response description
Success: The DocumentAuditingResponse moderation job result object is returned.
Failure: If an error (such as authentication failure) occurs, the CosClientException or
CosServiceException exception will be reported. For more information, see Troubleshooting.

©2013-2022 Tencent Cloud. All rights reserved.

Page 897 of 1869

Cloud Infinite

Text Moderation：

Last updated 2024-02-29 17:31:27

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for text moderation.
API

Description

Submitting text moderation job

Submits text moderation job.

Querying text moderation job result

Queries the result of specified text moderation job.

Submitting Text Moderation Job
Feature description
This API is used to submit a text moderation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 898 of 1869

Cloud Infinite

TextAuditingResponse createAuditingTextJobs(TextAuditingRequest request);

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 899 of 1869

Cloud Infinite//1. Create a job request object
TextAuditingRequest request = new TextAuditingRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("examplebucket-12500000008");//2.1.1 Set the object address//request.getInput().setObject("1.txt");//2.1.2 Or, directly set the request content, i.e., Base64-encoded text content
request.getInput().setContent("Base64Str");//2.2 Set the moderation type parameterrequest.getConf().setDetectType("all");//2.3 Set the moderation template (optional)©2013-2022 Tencent Cloud. All rights reserved.

Page 900 of 1869

Cloud Infinite//request.getConf().setBizType("aa3e9d84a6a079556b0109a935c*****");//3. Call the API to get the job response object
TextAuditingResponse response = client.createAuditingTextJobs(request);

Parameter description
Request has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

RequestNone

Text moderation configuration.

Container

Yes

Request has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

Input

RequestContent to be moderated.

Container

Yes

Conf

RequestModeration rule configuration.

Container

Yes

Input has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeDescription

Type

Required

StringNo

StringNo

Name of the text file stored in the current COS bucket;
for example, if the file is test.txt in the test
ObjectRequest.Input

directory, then the filename is test/test.txt .
Only text files in UTF-8 and GBK encodings aresupported, and the file size cannot exceed 1 MB.

Content

Request.Input

When the input content is plain text, it needs to be
Base64-encoded first. The length of the original text
before encoding cannot exceed 10,000 UTF-8
characters. If the length limit is exceeded, the API willreport an error.

Note:
Object and Content cannot be entered at the same time.
If Object is selected, the moderation result will be returned asynchronously, which can be obtained through the
API for querying text moderation job result.
If Content is selected, the moderation result will be returned synchronously, which can be viewed in the responsebody.

©2013-2022 Tencent Cloud. All rights reserved.

Page 901 of 1869

Cloud Infinite

Currently, only Chinese, English, and Arabic numerals can be detected and moderated.
Conf has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeDescription

Type

Required

StringNo

StringNo

StringNo

Moderation policy. If this parameter is not specified,
BizTypeRequest.Conf

the default policy will be used. The policy can be
configured in the console. For more information, see
Setting Moderation Policy.
The scene to be moderated, such as Porn
(pornography), Ads (advertising), Illegal

DetectType

Request.Conf(illegal), and Abuse (abusive). You can pass in
multiple types and separate them by comma, such as
Porn,Ads .

Callback

Request.Conf

The moderation result can be sent to your callback
address in the form of a callback. Addresses startingwith http:// or https:// are supported,
such as http://www.callback.com .

Response description
Success: The TextAuditingResponse text moderation job result object is returned upon success.
Failure: An error (such as the bucket does not exist) occurs, reporting the CosClientException or
CosServiceException exception. For more information, see Troubleshooting.

Querying Text Moderation Job
Feature description
This API is used to query the status and result of a text moderation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 902 of 1869

Cloud Infinite

TextAuditingResponse describeAuditingTextJob(TextAuditingRequest request);

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 903 of 1869

Cloud Infinite//1. Create a job request object
TextAuditingRequest request = new TextAuditingRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("examplebucket-1250000000");
request.setJobId("st68d08596f35011eb9324525400*****");//3. Call the API to get the job response object
TextAuditingResponse response = client.describeAuditingTextJob(request);

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 904 of 1869

Cloud Infinite

Parameter
bucketName
jobId

Description
Bucket name in the format of BucketName-APPID . For more
information, see Bucket Overview.
ID of the job to be queried.

Type

Required

StringYes

StringYes

Response description
Success: The TextAuditingResponse moderation job result object is returned.
Failure: If an error (such as authentication failure) occurs, the CosClientException or
CosServiceException exception will be reported. For more information, see Troubleshooting.

©2013-2022 Tencent Cloud. All rights reserved.

Page 905 of 1869

Cloud Infinite

Callback Information Processing：

Last updated 2024-02-29 17:31:27

Overview
This document provides SDK code samples for standard callback information parsing in CI.

XML Callback Content Parsing
Description
The common XML callback information in CI is parsed into Java objects.

ExamplesThis example shows you how to parse the XML callback data by getting Unmarshallers.
Note:
You can get the required XML parser by viewing the APIs of COSClient. You can also find out which Unmarshaller isbeing used by viewing the query API corresponding to the feature.
For example, the query API corresponding to the file preview callback information is describeDocProcessJob .
The code snippet in COSClient used to check which Unmarshaller is used by the invoke method.

©2013-2022 Tencent Cloud. All rights reserved.

Page 906 of 1869

Cloud Infinite@Override
public DocJobResponse describeDocProcessJob(DocJobRequest request) {this.checkCIRequestCommon(request);
CosHttpRequest<DocJobRequest> httpRequest = this.createRequest(request.getBucketN
return this.invoke(httpRequest, new Unmarshallers.DescribeDocJobUnmarshaller());}
Use Unmarshaller to parse the response content.

©2013-2022 Tencent Cloud. All rights reserved.

Page 907 of 1869

Cloud Infinite

public static void processCINotifyResponse(String response) throws Exception {Unmarshallers.DescribeDocJobUnmarshaller describeDocJobUnmarshaller = new Unmarsh
InputStream is = new ByteArrayInputStream(response.getBytes());
DocJobResponse docJobResponse = describeDocJobUnmarshaller.unmarshall(is);}JSON Callback Content Parsing©2013-2022 Tencent Cloud. All rights reserved.

Page 908 of 1869

Cloud Infinite

Description
The common JSON callback information in CI is parsed into Java objects.

ExamplesNote:
Essentially, processing JSON callbacks is to convert JSON to XML before processing.
The demo uses org.json to convert JSON to XML. This dependency is not provided in the POM of the SDK and needs
to be imported by yourself.
For example, the query API corresponding to image moderation callback information is
describeAuditingImageJob .
The code snippet in COSClient used to check which Unmarshaller is used by the invoke method.

©2013-2022 Tencent Cloud. All rights reserved.

Page 909 of 1869

Cloud Infinite@Override
public ImageAuditingResponse describeAuditingImageJob(DescribeImageAuditingRequest
rejectNull(imageAuditingRequest.getBucketName(),"The bucketName parameter must be specified setting the object tags");
rejectNull(imageAuditingRequest.getJobId(),"The jobId parameter must be specified setting the object tags");
CosHttpRequest<DescribeImageAuditingRequest> request = createRequest(imageAuditin
return invoke(request, new Unmarshallers.ImageAuditingDescribeJobUnmarshaller());}
Use Unmarshaller to parse the response content after converting the JSON response to XML.

©2013-2022 Tencent Cloud. All rights reserved.

Page 910 of 1869

Cloud Infinite// Callback demo
public static void processJsonCINotifyResponse(String jsonResponse) throws Exceptio
JSONObject response = new JSONObject(jsonResponse);
JSONObject json = new JSONObject();
json.put("Response",response);
String xml = XML.toString(json);
Unmarshallers.ImageAuditingDescribeJobUnmarshaller imageJobUnmarshaller = new Unm
InputStream is = new ByteArrayInputStream(xml.getBytes());
ImageAuditingResponse imageAuditingResponse = imageJobUnmarshaller.unmarshall(is)}©2013-2022 Tencent Cloud. All rights reserved.

Page 911 of 1869

Cloud Infiniteorg.json.json is used in the above example, which is not provided in the SDK. If you need to use it, add the following
dependencies:<dependency><groupId>org.json</groupId><artifactId>json</artifactId><version>20180130</version></dependency>©2013-2022 Tencent Cloud. All rights reserved.

Page 912 of 1869

Cloud Infinite

Troubleshooting：

Last updated 2024-02-29 17:31:27

Overview
When calling the SDK to request the COS or CI service fails, all exceptions reported are RuntimeExcpetion .
Common exceptions in the SDK currently include CosClientException , CosServiceException ,CIServiceException , and IllegalArgumentException .

Client Exceptions
CosClientException results from unexpected interaction issues between the client and the COS server, suchas a failure to connect to the server, a failure to parse the data returned by the server, or the occurrence of an IO
exception when reading a local file. Inherited from RuntimeException , CosClientException has no
custom member variables, and is used in the same way as RuntimeException .

Server Exceptions
CosServiceException and CIServiceException refer to scenarios where the interaction is completed
normally but the operation fails; for example, the client accesses a bucket that does not exist, deletes a file that does
not exist, or does not have the permission to perform the operation, or the server fails.
CosServiceException contains the status code, request ID, and error details. After such an exception is
captured, we recommend you print out the entire exception as it contains necessary factors for troubleshooting. The
following describes the member variables of the exception:
RequestElement

DescriptionTyperequestId

Request ID, which is used to identify a request and is very important fortroubleshooting.

StringtraceId

ID for troubleshooting

StringstatusCode

Status code in the response. 4xx indicates that the request failed due to aclient exception. 5xx indicates that the request failed due to a server
exception. For more information, see Error Codes.

StringerrorType

Enumeration type, indicating the type of exception, such as Client ,ErrorType©2013-2022 Tencent Cloud. All rights reserved.

Page 913 of 1869

Cloud Infinite

Service , and Unknown .
errorCodeError code returned by the body when the request fails. For more information,
see Error Codes.

StringerrorMessage

Error message returned by the body when the request fails. For more
information, see Error Codes.

StringUsing the Diagnosis Tool
CI provides a self-help diagnosis tool to help you quickly locate request errors and debug the code.
Directions
1. Copy the request ID ( RequestId ) returned when the request error occurs.
2. Click Diagnosis Tool.
3. Enter RequestId and click Diagnose.
4. Wait and view the diagnostic result.

FAQs
If you have any questions about the Java SDK, see FAQs.

©2013-2022 Tencent Cloud. All rights reserved.

Page 914 of 1869

Cloud Infinite

File Processing
Hash Calculation：

Last updated 2024-02-29 17:31:27

Overview
This document provides an overview of APIs and SDK code samples for hash calculation in CI.
API

Description

Submitting a hash calculation job

Creates a hash calculation job.

Querying the hash calculation result

Queries the result of a hash calculation job.

Submitting a Hash Calculation Job
Feature description
This API is used to submit a job to perform hash calculation and asynchronously return a calculated hash value.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 915 of 1869

Cloud Infinite

public FileProcessJobResponse createFileProcessJob(FileProcessRequest request);

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description

Type

Requiredtag

RequestJob type. It is FileHashCode for hashStringYes

calculation.

©2013-2022 Tencent Cloud. All rights reserved.

Page 916 of 1869

Cloud Infinite

operation

RequestHash calculation rule.

Container

Yes

queueId

RequestID of the queue where the job is in.

StringYes

StringNo

StringNo

StringNo

ContainerNo

Job callback format, which can be JSON or
callBackFormat

RequestXML (default). It takes priority over that of thequeue.
Job callback type, which can be UrlcallBackType

Request(default) or TDMQ . It takes priority over thatof the queue.

callBack

RequestcallBackMqConfig

RequestJob callback address. It takes priority over thatof the queue.
TDMQ configuration for job callback as
described in Structure, which is required if
CallBackType is TDMQ .

Input has the following sub-nodes:
Node Name(Keyword)
objectParent NodeDescription

Type

Required

Request.Input

Filename, which is the full name of the file inthe bucket.

StringYes

Operation has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

fileHashCodeConfig

Request.Operation

Hash calculation rule.

Container

Yes

Request.Operation

The user information passed
through, which is printable ASCII

StringNo

userData

codes of up to 1,024 in length.

FileHashCodeConfig has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

RequiredType

Request.Operation.FileHashCodeConfig

Hash algorithm. Validvalues: MD5 , SHA1 ,StringYes©2013-2022 Tencent Cloud. All rights reserved.

Page 917 of 1869

Cloud Infinite

SHA256 .
Whether to add thecalculated hash value tothe custom header in the
file. Valid values:
true , false
addToHeader

Request.Operation.FileHashCodeConfig(default).<br>The
custom header varies
depending on Type .

String

No

For example, if Typeis MD5 , the custom
header is x-cosmeta-md5 .

Response description
Success: The FileProcessJobResponse object response information is returned.
Failure: An error (such as the bucket does not exist) occurs, reporting the CosClientException or
CosServiceException exception. For more information, see Troubleshooting.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 918 of 1869

Cloud Infinite//1. Create a job request object
FileProcessRequest request = new FileProcessRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("demo-1234567890");
request.setTag(FileProcessJobType.FileHashCode);request.getInput().setObject("input/1.mp4");
FileHashCodeConfig fileHashCodeConfig = request.getOperation().getFileHashCodeConfi
fileHashCodeConfig.setType("MD5");
fileHashCodeConfig.setAddToHeader("true");request.setQueueId("p1ff062b35a494cf0ac4b572df22a****");//3. Call the API to get the job response object©2013-2022 Tencent Cloud. All rights reserved.

Page 919 of 1869

Cloud Infinite

FileProcessJobResponse response = client.createFileProcessJob(request);

Querying Hash Calculation Result
Feature description
This API is used to query the details of a file processing job by job ID.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 920 of 1869

Cloud Infinite

public FileProcessJobResponse describeFileProcessJob(FileProcessRequest request);

Parameter description
Parameter
bucketName
jobId

Description
Bucket name in the format of BucketName-APPID . For more
information, see Bucket Overview.
ID of the job to be queried.

Type

Required

StringYes

StringYes

Response description
Success: A job details response wrapper class is returned, which contains the job details object
FileProcessJobResponse .
Failure: If an error (such as authentication failure) occurs, the CosClientException or
CosServiceException exception will be reported. For more information, see Troubleshooting.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 921 of 1869

Cloud Infinite//1. Create a job request object
FileProcessRequest request = new FileProcessRequest();//2. Add request parameters as detailed in the API documentation
request.setBucketName("demo-1234567890");
request.setJobId("fda7eb1607b8411ed8c182156726*****");//3. Call the API to get the job response object
FileProcessJobResponse response = client.describeFileProcessJob(request);©2013-2022 Tencent Cloud. All rights reserved.

Page 922 of 1869

Cloud Infinite

JavaScript SDK
Getting Started：

Last updated 2024-03-01 10:49:05

Download and Installation
Relevant resources
Source code of COS XML JS SDK download: XML JavaScript SDK.
SDK download: XML JavaScript SDK.
Demo download: JS Sample.
For the complete sample code, see SDK Sample Code.
For the SDK changelog, see Changelog.
For SDK FAQs, see JavaScript SDK FAQs.
Note:
If you encounter errors such as non-existent functions or methods when using the XML version of the SDK, please
update the SDK to the latest version and try again.
Environment requirements
1. The SDK for JavaScript requires the browser to support basic HTML5 features (IE 10 and higher) for AJAX file
uploading and MD5 checksum calculation.
2. Log in to the COS console, create a bucket, and get the bucket name and region name.
3. Log in to the CAM console and get the SecretId and SecretKey of your project.
4. Configure CORS rule. Put in * for AllowHeader . For ExposeHeaders , put in ETag , ContentLength , and the other header fields that JS needs to read as shown below. For more information, see Setting
Cross-Origin Access.

©2013-2022 Tencent Cloud. All rights reserved.

Page 923 of 1869

Cloud Infinite

Note:
For the definition of parameters such as SecretId , SecretKey , and Bucket , see COS’s Glossary.
If you are using cross platform framework such as uni-app, and encounter problems when packaging the app (such as
iOS or Android app), use the iOS SDK or Android SDK.
Installing SDK
You can install the SDK in the following ways:
Importing via script
Note:
We recommend you download the SDK to local and then import it. You can download the latest SDK file "cos-js-sdkv5.min.js" at URL 1 or URL 2.

©2013-2022 Tencent Cloud. All rights reserved.

Page 924 of 1869

Cloud Infinite<!--src is a local path. Set it based on the directory structure of your project.-<script src="../dist/cos-js-sdk-v5.min.js"></script>
When the script tag references the SDK, the SDK occupies the global variable name COS, and its constructor cancreate an SDK instance.
Importing via webpack
Install the SDK dependencies by running npm i cos-js-sdk-v5 --save , which supports webpack packaging
scenarios. You can use npm import as a module with the following code:©2013-2022 Tencent Cloud. All rights reserved.

Page 925 of 1869

Cloud Infinite

var COS = require('cos-js-sdk-v5');// orimport COS from 'cos-js-sdk-v5';

Getting Started©2013-2022 Tencent Cloud. All rights reserved.

Page 926 of 1869

Cloud Infinite

Note:
We recommend you use a temporary key as instructed in Generating and Using Temporary Keys to call the SDK for
security purposes. When you apply for a temporary key, follow the Notes on Principle of Least Privilege to avoid
leaking resources besides your buckets and objects.
If you must use a permanent key, we recommend you follow the Notes on Principle of Least Privilege to limit the scopeof permission on the permanent key.

Getting a temporary key
As placing a permanent key on the frontend may cause security risks, we recommend you use temporary keys duringformal deployment. The implementation process is as follows: the frontend first requests the server, and then theserver uses the permanent key to call the STS service to apply for a temporary key (for more information, see
Generating and Using Temporary Keys) and returns it to the frontend.
Note:
If the site has a login state, login state verification should be added to the temporary key getting API.

Initialization
1. Create a web.html file, enter the following code, and modify the bucket name and region in web.html.
2. Deploy the temporary key service on the backend and modify the key service address in getAuthorization.
3. Place the web.html file on the web server, visit the page in a browser, and test file uploading. The sample codefor web.html is as follows:©2013-2022 Tencent Cloud. All rights reserved.

Page 927 of 1869

Cloud Infinite<input id="file-selector" type="file"><script src="dist/cos-js-sdk-v5.min.js"></script><script>// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which canvar Bucket = 'examplebucket-1250000000'; /* Bucket. Required */// The bucket region can be viewed in the COS console at https://console.tencentclo// The region details can be viewed at https://www.tencentcloud.com/document/produc
var Region = 'COS_REGION';/* Bucket region. Required */©2013-2022 Tencent Cloud. All rights reserved.

Page 928 of 1869

Cloud Infinite// Initialize an instance.
var cos = new COS({// The `getAuthorization` parameter is required.
getAuthorization: function (options, callback) {// It will not be called during initialization and will be entered only whe// Get a temporary key asynchronously.
// Server-side JS and PHP sample: https://github.com/tencentyun/cos-js-sdk// For server-side examples for other programming languages, see the COS SD// For the STS documentation, visit https://www.tencentcloud.com/document/p
var url = 'http://example.com/server/sts.php'; // Replace the URL with yourvar xhr = new XMLHttpRequest();xhr.open('GET', url, true);
xhr.onload = function (e) {try {var data = JSON.parse(e.target.responseText);
var credentials = data.credentials;} catch (e) {}if (!data || !credentials) {return console.error('credentials invalid:\\n' + JSON.stringify(data,};
callback({
TmpSecretId: credentials.tmpSecretId,
TmpSecretKey: credentials.tmpSecretKey,
SecurityToken: credentials.sessionToken,// We recommend that you use the server time as the signature start t
StartTime: data.startTime, // Timestamp in seconds, such as 158000000
ExpiredTime: data.expiredTime, // Timestamp in seconds, such as 15800});};
xhr.send();}});// The COS instance can then be used to call a COS request.
</script>

Configuration item
Sample code
Create a COS SDK instance in one of the following ways:
Method 1 (recommended): The backend gets a temporary key and sends it to the frontend for signature calculation.

©2013-2022 Tencent Cloud. All rights reserved.

Page 929 of 1869

Cloud Infinite

var COS = require('cos-js-sdk-v5');
var cos = new COS({// The `getAuthorization` parameter is required.
getAuthorization: function (options, callback) {// Get a temporary key asynchronously.
// Server-side JS and PHP sample: https://github.com/tencentyun/cos-js-sdk// For server-side examples for other programming languages, see the COS SD// For the STS documentation, visit https://www.tencentcloud.com/document/p
var url = 'http://example.com/server/sts.php'; // Replace the URL with yourvar xhr = new XMLHttpRequest();©2013-2022 Tencent Cloud. All rights reserved.

Page 930 of 1869

Cloud Infinite

xhr.open('GET', url, true);
xhr.onload = function (e) {try {var data = JSON.parse(e.target.responseText);
var credentials = data.credentials;} catch (e) {}if (!data || !credentials) {return console.error('credentials invalid:\\n' + JSON.stringify(data,};
callback({
TmpSecretId: credentials.tmpSecretId,
TmpSecretKey: credentials.tmpSecretKey,
SecurityToken: credentials.sessionToken,// We recommend that you use the server time as the signature start t
StartTime: data.startTime, // Timestamp in seconds, such as 158000000
ExpiredTime: data.expiredTime, // Timestamp in seconds, such as 15800});};
xhr.send();}});
Method 2 (recommended). Permissions are controlled in a more refined manner. The backend gets a temporary key
and sends it to the frontend. The frontend reuses the key only for the same request, and the backend can granularly
manage permissions through Scope.

©2013-2022 Tencent Cloud. All rights reserved.

Page 931 of 1869

Cloud Infinite

var COS = require('cos-js-sdk-v5');
var cos = new COS({// The `getAuthorization` parameter is required.
getAuthorization: function (options, callback) {// Server example: https://github.com/tencentyun/qcloud-cos-sts-sdk/blob/ma// Get a temporary key asynchronously.
var url = 'http://example.com/server/sts.php'; // Replace the URL with yourvar xhr = new XMLHttpRequest();xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function (e) {©2013-2022 Tencent Cloud. All rights reserved.

Page 932 of 1869

Cloud Infinite

try {var data = JSON.parse(e.target.responseText);
var credentials = data.credentials;} catch (e) {}if (!data || !credentials) {return console.error('credentials invalid:\\n' + JSON.stringify(dat};callback({
TmpSecretId: credentials.tmpSecretId,
TmpSecretKey: credentials.tmpSecretKey,
SecurityToken: credentials.sessionToken,// We recommend that you use the server time as the signature start
StartTime: data.startTime, // Timestamp in seconds, such as 1580000
ExpiredTime: data.expiredTime, // Timestamp in seconds, such as 158
ScopeLimit: true, // Refined permission control needs to be set to});};xhr.send(JSON.stringify(options.Scope));}});
Method 3 (not recommended): The frontend needs to get a signature through getAuthorization before eachrequest, and the backend uses a permanent or temporary key to calculate the signature and returns it to the frontend.
This method makes it difficult to control permissions for multipart upload and thus is not recommended.

©2013-2022 Tencent Cloud. All rights reserved.

Page 933 of 1869

Cloud Infinite

var COS = require('cos-js-sdk-v5');
var cos = new COS({// The `getAuthorization` parameter is required.
getAuthorization: function (options, callback) {// Obtain the signature asynchronously.
var url = 'http://example.com/server/sts.php'; // Replace the URL with yourvar method = (options.Method || 'get').toLowerCase();var query = options.Query || {};var headers = options.Headers || {};var pathname = options.Pathname || '/';

©2013-2022 Tencent Cloud. All rights reserved.

Page 934 of 1869

Cloud Infinite

var xhr = new XMLHttpRequest();var data = {method: method,
pathname: pathname,query: query,headers: headers,};
xhr.open('POST', url, true);
xhr.setRequestHeader('content-type', 'application/json');
xhr.onload = function (e) {try {var data = JSON.parse(e.target.responseText);} catch (e) {}if (!data || !data.authorization) return console.error('authorization icallback({
Authorization: data.authorization,// SecurityToken: data.sessionToken, // If a temporary key is used,});};
xhr.send(JSON.stringify(data));},});
Method 4 (not recommended): The frontend uses a permanent key to calculate the signature. This method can beused for frontend debugging. If you use this method, be sure to avoid key disclosure.

©2013-2022 Tencent Cloud. All rights reserved.

Page 935 of 1869

Cloud Infinite

var COS = require('cos-js-sdk-v5');// Log in to https://console.tencentcloud.com/cam/capi to check and manage the Secrvar cos = new COS({
SecretId: 'SECRETID',
SecretKey: 'SECRETKEY',});

Constructor parameters©2013-2022 Tencent Cloud. All rights reserved.

Page 936 of 1869

Cloud Infinite

Parameter

Description

Type

Required

SecretId

User SecretId

StringNo

String

No

User's SecretKey , which we recommend to be
SecretKey

used only for frontend debugging and should not be
disclosed

FileParallelLimit

Number of concurrent file uploads in the same
instance. Default value: 3

NumberNo

ChunkParallelLimit

Number of concurrent part uploads for the same
uploaded file. Default value: 3

Number

No

Number

No

Number

No

Number

No

Number

No

Number

No

Number

No

NumberNo

String

No

ChunkRetryTimes

Number of retries for multipart upload failure. Default
value: 2 (a request will be made 3 time in total,
including the initial one)

ChunkSize

Part size in the multipart upload in bytes. Default value:
1048576 (1 MB)
When files are uploaded in batches using
uploadFiles , if the file size is greater than the

SliceSizevalue of this parameter (measured in bytes), multipartupload is used; otherwise, simple upload is used.
Default value: 1048576 (1 MB)

CopyChunkParallelLimit

CopyChunkSize

Number of concurrent part uploads for the same
multipart copy operation. Default value: 20
Number of bytes in each part during a multipart copy
operation with sliceCopyFile . Default value:
10485760 (10 MB)
When a file is copied by using sliceCopyFile , if

CopySliceSize

ProgressInterval

the file size is greater than the value of this parameter,
multipart copy is used; otherwise, simple copy is used.
Default value: 10485760 (10 MB)
Callback frequency of the upload progress callback
method onProgress in milliseconds. Default
value: 1000

ProtocolThe protocol used when the request is made. Validvalues: https: , http: . By default, http: isused when the current page is determined to be in
http: format; otherwise, https: is used©2013-2022 Tencent Cloud. All rights reserved.

Page 937 of 1869

Cloud Infinite

DomainThe custom request domain name used to call abucket or object API. You can use a template, such as"{Bucket}.cos.{Region}.myqcloud.com"

StringNo

NumberNo

BooleanNo

Boolean

No

Function

No

NumberNo

BooleanNowhich will use the bucket and region passed in thereplacement parameters when an API is called.

UploadQueueSize

ForcePathStyle

UploadCheckContentMd5

The maximum size of the upload queue. Excess tasks
will be cleared if their status is not waiting, checking,or uploading. Default value: 10000
Forces the use of a suffix when sending requests. The
suffixed bucket will be placed in the pathname after thedomain name, and the bucket will be added to thesignature pathname for calculation. Default value: false
Verifies Content-MD5 when uploading files, which isfalse by default. If it is enabled, the MD5 value of the
uploading files will be calculated, which may be timeconsuming for large files
Callback method for getting the signature. If there is no
SecretId or SecretKey , this parameter is

getAuthorization

required.
Note: This callback method is passed in during
instance initialization, and is only executed toobtain the signature when the instance calls
APIs.

Timeout

Timeout period in milliseconds. Default value: 0,
indicating no timeout period.
Whether to enable a global acceleration endpoint.
Default value: false . If you set the value to

UseAcceleratetrue , you need to enable global acceleration forthe bucket. For more information, see Enabling Global
Acceleration.

getAuthorization Callback function description (Format 1)©2013-2022 Tencent Cloud. All rights reserved.

Page 938 of 1869

Cloud Infinite

getAuthorization: function(options, callback) { ... }getAuthorization callback parameter descriptions:Parameter

Description

Type

options

Required for getting the signature

Object- Bucket

Bucket name in the format BucketName-APPID . The bucket name entered here
must be in this format©2013-2022 Tencent Cloud. All rights reserved.

StringPage 939 of 1869

Cloud Infinite

RegionBucket region. For the enumerated values, see bucket regions.

Stringcallback

Callback method after the temporary key is obtained

Function

After the temporary key is obtained, the callback returns an object. The attributes of the returned object are as listed
below:
Attribute

Description

Type

Required

TmpSecretId

tmpSecretId of the obtained temporary key

StringYes

TmpSecretKey

tmpSecretKey of the obtained temporary key

StringYes

SecurityTokensessionToken of the obtained temporary key, which corresponds
to the x-cos-security-token field in the header

StringYes

StringNo

StringYes

StartTimeThe timestamp in seconds of when you obtained the key, such as
1580000000 . Passing in this parameter as the signature start
time can avoid signature expiration issues due to time deviationon the frontend.

ExpiredTime

expiredTime of the obtained temporary key measured inseconds, i.e., the timeout timestamp, such as 1580000900

getAuthorization Callback function description (Format 2)©2013-2022 Tencent Cloud. All rights reserved.

Page 940 of 1869

Cloud Infinite

getAuthorization: function(options, callback) { ... }getAuthorization function callback parameter descriptions:Parameter

Description

Type

options

Parameter object for getting the signature

Object- Method

Method of the current request

String- PathnameRequest path used for signature calculation

String©2013-2022 Tencent Cloud. All rights reserved.

Page 941 of 1869

Cloud Infinite- Key

An object key (object name), the unique identifier of an object in a bucket. For
more information, see Object Overview.
Note: This parameter is empty if the API that uses the instance is not an
object-operation API.

String- Query

Query parameter in the current request. Format: {key: 'val'}

Object- Headers

Headers in the current request. Format: {key: 'val'}

Objectcallback

Callback after the temporary key is obtained

FunctionOnce the getAuthorization callback function is finished, it returns one of the following:
An Authorization string.
An object whose attributes are listed as follows:
Attribute

Description

Type

Required

Authorization

Calculated signature string

StringYes

StringNosessionToken of the obtained temporary key, which
SecurityToken

corresponds to the x-cos-security-token field in theheaderGetting an authentication credential
There are three ways to get the authentication credentials for your instance by passing in different parameters during
instantiation:
1. During instantiation, pass in your SecretId and SecretKey . Each time a signature is required, it will beinternally calculated by the instance.
2. During instantiation, pass in the getAuthorization callback. Every time a signature is required, it will be calculated
and returned to the instance through this callback.
3. During instantiation, pass in the getAuthorization callback. When the callback is called, a temporary key will be
returned. After the key expires, the callback will be called again.

Enabling DataInsight
We have introduced the Tencent Beacon into the SDK to track down and optimize the SDK quality for a better user
experience.
Note:
DataInsight only monitors the COS request performance and doesn't report any business data.
To enable this feature, make sure that the SDK version is 1.4.0 or later and specify EnableTracker as true
during initialization.

©2013-2022 Tencent Cloud. All rights reserved.

Page 942 of 1869

Cloud Infinite

new COS({
EnableTracker: true,})

How to use
Callback method
The callback method is used by default in the documentation. Below is the sample code:©2013-2022 Tencent Cloud. All rights reserved.

Page 943 of 1869

Cloud Infinite// The initialization process and upload parameters are omitted here.
var cos = new COS({ ... });cos.uploadFile({ ... }, function(err, data) {if (err) {console.log('Upload failed', err);} else {console.log('Uploaded successfully', data);}});©2013-2022 Tencent Cloud. All rights reserved.

Page 944 of 1869

Cloud Infinite

PromiseThe SDK also supports calling through the promise method. For example, the code of the callback method above isequivalent to the following code:// The initialization process and upload parameters are omitted here.
var cos = new COS({ ... });cos.uploadFile({ ... }).then(data => {console.log('Uploaded successfully', data);}).catch(err => {console.log('Upload failed', err);});©2013-2022 Tencent Cloud. All rights reserved.

Page 945 of 1869

Cloud Infinite

Sync method
The sync method is based on JavaScript's async and await (keep browser compatibility in mind when using it). The
code of the callback method above is equivalent to the following code:

async function upload() {// The initialization process and upload parameters are omitted here.
var cos = new COS({ ... });try {var data = await cos.uploadFile({ ... });©2013-2022 Tencent Cloud. All rights reserved.

Page 946 of 1869

Cloud Infinite

return { err: null, data: data }} catch (err) {return { err: err, data: null };}}// The returned value of the request can be obtained synchronously. Here is only an
var uploadResult = await upload();if (uploadResult.err) {console.log('Upload failed', uploadResult.err);} else {console.log('Uploaded successfully', fuploadResult.data);}
Note:cos.getObjectUrl currently only supports the callback method.

Tips
In most cases, you only need to create a COS SDK instance, and use it directly where SDK methods need to becalled.

©2013-2022 Tencent Cloud. All rights reserved.

Page 947 of 1869

Cloud Infinite/* Sample Vue project *//* Create `cos.js` and export the COS instance */import COS from 'cos-js-sdk-v5'; // SDK installed using npm
const cos = new COS({....
});
export default cos;/* `page.vue` in a single page */<template>©2013-2022 Tencent Cloud. All rights reserved.

Page 948 of 1869

Cloud Infinite<input id="fileSelector" type="file" @change="upload" /></template><script>/* Import the path of the `cos.js` newly created above */import cos from 'cos';
export default {data() {},methods: {upload(e) {const file = e.target.files && e.target.files[0];/* Call the method of COS SDK directly */cos.uploadFile({
Bucket: 'examplebucket-1250000000', /* Your bucket name. Required. */Region: 'COS_REGION',/* Bucket region. Required */Key: '1.jpg', /* Object key stored in the bucket (for example, `1.jpg` aBody: file, // Upload the file object
SliceSize: 1024 * 1024 * 5,/* Threshold (5 MB in this example) to tr
});
}
},
}
</script>
Below are some common APIs. For more detailed initialization methods, see the demo.

Querying objects©2013-2022 Tencent Cloud. All rights reserved.

Page 949 of 1869

Cloud Infinite

cos.getBucket({
Bucket: 'examplebucket-1250000000', /* Your bucket name. Required. */Region: 'COS_REGION',/* Bucket region. Required */Prefix: 'a/',/* All files in directory `a`. Optional */}, function(err, data) {console.log(err || data.Contents);});

Uploading an object©2013-2022 Tencent Cloud. All rights reserved.

Page 950 of 1869

Cloud Infinite

We strongly recommend you use the advanced upload API uploadFile , which automatically uses simple upload
for small files and multipart upload for large files for a better performance. For more information, see Uploading Object.
If you use the temporary key method, you need to grant the permissions of both simple upload and multipart upload as
instructed in Working with COS API Authorization Policies.
For SDK FAQs, see FAQs.

<!-- DOM element in the HTLM file --><!-- Choose an image to upload --><input id="fileSelector" type="file" />©2013-2022 Tencent Cloud. All rights reserved.

Page 951 of 1869

Cloud Infinite<!-- Click the button to upload the image --><input id="submitBtn" type="submit" />function handleFileInUploading(file) {cos.uploadFile({
Bucket: 'examplebucket-1250000000', /* Your bucket name. Required. */Region: 'COS_REGION',/* Bucket region. Required */Key: '1.jpg',/* Object key stored in the bucket (required), suc
Body: file, // Upload the file object
SliceSize: 1024 * 1024 * 5,/* Threshold (5 MB in this example) to trigge
onProgress: function(progressData) {©2013-2022 Tencent Cloud. All rights reserved.

Page 952 of 1869

Cloud Infinite

console.log(JSON.stringify(progressData));}}, function(err, data) {if (err) {console.log('Upload failed', err);} else {console.log('Uploaded successfully');}});}/* Select a file */document.getElementById('submitBtn').onclick = function (e) {var file = document.getElementById('fileSelector').files[0];if (!file) {document.getElementById('msg').innerText = 'File to upload not selected';
return;}handleFileInUploading(file);};

Downloading an object
Note:
Object download is implemented by generating a pre-signed URL and triggering download in the browser.

©2013-2022 Tencent Cloud. All rights reserved.

Page 953 of 1869

Cloud Infinite

cos.getObjectUrl({
Bucket: 'examplebucket-1250000000', /* Your bucket name. Required. */Region: 'COS_REGION',/* Bucket region. Required */Key: '1.jpg', /* Object key stored in the bucket (for example, `1.jpg` and `a/}, function(err, data) {if (err) return console.log(err);/* Implement forced download by specifying `response-content-disposition=attac
var downloadUrl = data.Url + (data.Url.indexOf('?') > -1 ? '&' : '?') + 'respon/* The filename can be concatenated to rename the object during download *//* downloadUrl += ';filename=myname'; */// (The window.open() mode is recommended.) This opens the URL in a new window.

©2013-2022 Tencent Cloud. All rights reserved.

Page 954 of 1869

Cloud Infinite

window.open(downloadUrl);});

Deleting an object

cos.deleteObject({
Bucket: 'examplebucket-1250000000', /* Your bucket name. Required. */Region: 'COS_REGION',/* Bucket region. Required */Key: '1.jpg', /* Object key stored in the bucket (for example, `1.jpg` and `a/}, function(err, data) {©2013-2022 Tencent Cloud. All rights reserved.

Page 955 of 1869

Cloud Infinite

console.log(err || data);});©2013-2022 Tencent Cloud. All rights reserved.

Page 956 of 1869

Cloud Infinite

Image Processing
Basic Image Processing：

Last updated 2024-03-01 10:49:05

Overview
This document provides an overview of APIs and SDK code samples for basic image processing.
Service

Basic image
processing

FeatureDescription

Scaling

Proportional scaling, scaling image to target width and height

Cropping

Regular cropping, cropping and scaling, inscribed circle cropping,intelligent face cropping

Rotation

Adaptive rotation, regular rotation

Format conversion

Format conversion, GIF format optimization, progressive display

Quality change

Quality change for JPG and WebP images

Gaussian blurring

Image blurring

Sharpening

Image sharpening

Watermarking

Image watermark, text watermark

Image informationacquisition

Basic information, EXIF information, average hue

Metadata removal

Including EXIF information

Quick thumbnail
template

Quick image format conversion, scaling, and cropping for
thumbnail generation

Processing Image During Upload
The following example shows how to automatically process an image when you upload it to COS.

©2013-2022 Tencent Cloud. All rights reserved.

Page 957 of 1869

Cloud Infinite

When the image is uploaded successfully, COS will save both the original and the processed images. You can later
obtain the processing results by using a general download request.

Sample code<!-- DOM element on the HTLM page --><!-- Choose a file to upload --><input id="fileSelector" type="file" /><!-- Click the button for upload--><input id="submitBtn" type="submit" />©2013-2022 Tencent Cloud. All rights reserved.

Page 958 of 1869

Cloud Infinite

function handleFileInUploading(file) {cos.putObject({
Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION',
Key: file.name,Body: file,
Headers: {// Use the `imageMogr2` API to scale the image (by specifying the width of'Pic-Operations':©2013-2022 Tencent Cloud. All rights reserved.

Page 959 of 1869

Cloud Infinite'{"is_pic_info": 1, "rules": [{"fileid": "desample_photo.jpg", "rule": "i},},function (err, data) {console.log(err || data);},);}
document.getElementById('submitBtn').onclick = function (e) {var file = document.getElementById('fileSelector').files[0];if (!file) {document.getElementById('msg').innerText = 'No file selected for upload';
return;}handleFileInUploading(file);};

Processing In-Cloud Image
The following example shows how to process an image stored in COS and save the processing result to COS.

Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 960 of 1869

Cloud Infinite<!-- DOM element on the HTLM page --><!-- Click the button to process the in-cloud image --><input id="submitBtn" type="submit" />©2013-2022 Tencent Cloud. All rights reserved.

Page 961 of 1869

Cloud Infinite

function handleFileInBucket() {cos.request({
Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION',
Key: 'exampleImage',
Method: 'POST',
Action: 'image_process',
Headers: {// Use the `imageMogr2` API to scale the image (by specifying the width of'Pic-Operations':©2013-2022 Tencent Cloud. All rights reserved.

Page 962 of 1869

Cloud Infinite'{"is_pic_info": 1, "rules": [{"fileid": "desample_photo.jpg", "rule": "i},},function (err, data) {console.log(err || data);},);}
document.getElementById('submitBtn').onclick = function (e) {handleFileInBucket();};Processing Image During Download
The following example shows how to process an image during download.

Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 963 of 1869

Cloud Infinite<!-- DOM element on the HTLM page --><!-- Click the button to download and process the image --><input id="submitBtn" type="submit" />©2013-2022 Tencent Cloud. All rights reserved.

Page 964 of 1869

Cloud Infinite

function getObject() {cos.getObject({
Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION',
Key: 'exampleobject',
QueryString: `imageMogr2/thumbnail/200x/`,},function (err, data) {console.log(err || data);},©2013-2022 Tencent Cloud. All rights reserved.

Page 965 of 1869

Cloud Infinite);}

Generating Signed URL with Image Processing Parameters
Sample code// Generate a signed URL (valid for 30 minutes) with image processing parameters.
cos.getObjectUrl(©2013-2022 Tencent Cloud. All rights reserved.

Page 966 of 1869

Cloud Infinite{
Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION',
Key: 'exampleobject',
Query: {`imageMogr2/thumbnail/200x/`: ''},Expires: 1800,
Sign: true,},
function (err, data) {if (data) {console.log(data.URL);}},);// Generate an unsigned URL with image processing parameters.
cos.getObjectUrl({
Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION',
Key: 'exampleobject',
Query: {`imageMogr2/thumbnail/200x/`: ''},Sign: false,},function (err, data) {if (data) {console.log(data.URL);}},);©2013-2022 Tencent Cloud. All rights reserved.

Page 967 of 1869

Cloud Infinite

Blind Watermark：

Last updated 2024-03-01 10:49:05

Overview
This document provides an overview of APIs and SDK code samples for blind watermarking.
For blind watermark APIs, see Blind Watermarking.

Adding Blind Watermark
Feature description
You can add a blind watermark when uploading or downloading an object.
Sample 1: Adding a blind watermark during upload©2013-2022 Tencent Cloud. All rights reserved.

Page 968 of 1869

Cloud Infinite<!-- DOM element on the HTLM page --><!-- Choose a file to upload --><input id="fileSelector" type="file" /><!-- Click the button for upload--><input id="submitBtn" type="submit" />©2013-2022 Tencent Cloud. All rights reserved.

Page 969 of 1869

Cloud Infinite

function handleFileInUploading(file) {cos.putObject({
Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION',
Key: file.name,Body: file,
Headers: {// CI's persistent processing API during upload'Pic-Operations':'{"is_pic_info": 1, "rules": [{"fileid": "desample_photo.jpg", "rule": "w©2013-2022 Tencent Cloud. All rights reserved.

Page 970 of 1869

Cloud Infinite},},
function (err, data) {console.log(err || data);},);}
document.getElementById('submitBtn').onclick = function (e) {var file = document.getElementById('fileSelector').files[0];if (!file) {document.getElementById('msg').innerText = 'No file selected for upload';
return;}handleFileInUploading();};

Sample 2: Adding a blind watermark during download©2013-2022 Tencent Cloud. All rights reserved.

Page 971 of 1869

Cloud Infinite<!-- DOM element on the HTLM page --><!-- Click the button to download and process the image --><input id="submitBtn" type="submit" />©2013-2022 Tencent Cloud. All rights reserved.

Page 972 of 1869

Cloud Infinite

function getObject() {cos.getObject({
Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION',
Key: 'exampleobject',
QueryString: `watermark/3/type/1/image/aHR0cDovL2V4YW1wbGVzLTEyNTEwMDAwMDQucG},
function (err, data) {console.log(err || data);},©2013-2022 Tencent Cloud. All rights reserved.

Page 973 of 1869

Cloud Infinite);}©2013-2022 Tencent Cloud. All rights reserved.

Page 974 of 1869

Cloud Infinite

Media Processing
Media Bucket APIs：

Last updated 2024-03-01 10:49:05

Overview
This document provides an overview of APIs and SDK code samples for media buckets.
API
DescribeMediaBuckets

Operation

Description

Querying media processing activation

Queries buckets with media processing

statusenabledQuerying Media Processing Activation Status
Feature description
This API is used to query buckets with media processing enabled.
Note:
The COS JavaScript SDK version must be at least v1.3.1.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 975 of 1869

Cloud Infinite

var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket (required) */Region: 'COS_REGION', /* Bucket region (required) */};var host = 'ci.' + config.Region + '.myqcloud.com';
var url = 'https://' + host + '/mediabucket';cos.request({
Bucket: config.Bucket,
Region: config.Region,
Method: 'GET',©2013-2022 Tencent Cloud. All rights reserved.

Page 976 of 1869

Cloud Infinite

Key: 'mediabucket', /** Fixed value (required) */Url: url,
Query: {pageNumber: '1', /** Page number (optional) */pageSize: '10', /** Number of entries per page (optional) */// regions: 'ap-chengdu', /** Region (optional), such as 'ap-beijing'. To s// bucketNames: 'test-1250000000', /** Bucket name (optional), such as 'tes// bucketName: 'test', /** Bucket name prefix for prefix search (optional),}}, function (err, data) {console.log(err || data);});

Parameter description
Parameter

Description

Type

Required

BucketBucket name in the format of BucketName-APPID .

StringYes

RegionBucket region. For the enumerated values, see Regions and AccessEndpoints.

StringYes

Key

Fixed value: mediabucket.

StringYes

PageNumber

Page number.

StringNo

PageSize

Number of entries per page.

StringNo

String

No

Region information, such as ap-shanghai and ap-beijing .
Regions

To specify multiple regions, separate them with commas. For more
information, see Regions and Domain Names.

BucketNames

Bucket name. To specify multiple bucket names, separate them withcommas. Exact search is supported.

StringNo

BucketName

Bucket name prefix for prefix search.

StringNo

Callback function description©2013-2022 Tencent Cloud. All rights reserved.

Page 977 of 1869

Cloud Infinite

function(err, data) { ... }Parameter

Description

Type

err

The object returned when an error (network error or service error) occurs.
If the request is successful, this parameter is empty. For more

Objectinformation, see Error Codes.
- statusCode

Returned HTTP status code, such as 200 , 403 , and 404 .

Number- headers

Returned headers.

Object©2013-2022 Tencent Cloud. All rights reserved.

Page 978 of 1869

Cloud Infinitedata

The object returned when the request is successful. If an error occurs
with the request, this parameter is empty.

Object- statusCode

Returned HTTP status code, such as 200 , 403 , and 404 .

Number- headers

Returned headers.

Object- Response

Response result.

Object- - RequestId

Unique ID of the request.

String- - TotalCount

Total number of media buckets.

String- - PageNumber- - PageSize

Current page number, which is the same as pageNumber in therequest.
Number of entries per page, which is the same as pageSize in therequest.

StringString-MediaBucketList

Media bucket list.

Object- - - BucketId

Bucket ID.

String- - - Name

Bucket name, which is the same as BucketId .

String- - - Region

Region.

String- - - CreateTime

Creation time.

String©2013-2022 Tencent Cloud. All rights reserved.

Page 979 of 1869

Cloud Infinite

Media Information APIs：

Last updated 2024-03-01 10:49:05

Overview
This document provides an overview of APIs and SDK code samples for media information.
Note:
The COS JavaScript SDK version must be at least v1.3.1.
API

Operation

Description

GetMediaInfo

Querying file information

Queries media file information

Querying File Information
Feature description
This API is used to query the information of a media file.
Note:
Before using this API, make sure that the media processing feature has been enabled in the data processing sectionin the console; otherwise, the error media bucket unbinded, bucket's host is unavailable will bereported.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 980 of 1869

Cloud Infinite

var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket (required) */Region: 'COS_REGION', /* Bucket region (required) */};cos.request({
Bucket: config.Bucket,
Region: config.Region,
Method: 'GET',
Key: 'test.mp4', /* Media file in bucket (required) */Query: {©2013-2022 Tencent Cloud. All rights reserved.

Page 981 of 1869

Cloud Infinite'ci-process': 'videoinfo' /** Fixed value (required) */}}, function (err, data) {console.log(err || data);});

Parameter description
Parameter

Description

Type

Required

BucketBucket name in the format of BucketName-APPID .

StringYes

StringYes

RegionBucket region. For the enumerated values, see Regions and AccessEndpoints.

Key

Fixed value: mediabucket.

StringYes

ci-process

Operation type, which is fixed at videoinfo .

StringYes

Callback function description©2013-2022 Tencent Cloud. All rights reserved.

Page 982 of 1869

Cloud Infinite

function(err, data) { ... }Parameter

Description

Type

The object returned when an error (network error or service error) occurs. If
err

the request is successful, this parameter is empty. For more information,
see Error Codes.

Object- statusCode

Returned HTTP status code, such as 200 , 403 , and 404 .

Number- headers

Returned headers.

Object©2013-2022 Tencent Cloud. All rights reserved.

Page 983 of 1869

Cloud Infinitedata

The object returned when the request is successful. If an error occurs withthe request, this parameter is empty.

Object- statusCode

Returned HTTP status code, such as 200 , 403 , and 404 .

Number- headers

Returned headers.

Object- RequestId

Unique ID of the request.

String- Response

Response result.

Object- - MediaInfo

Media details.

Object- - - Stream

Stream information.

Object- - - - Video

Video information.

Container- - - - - Index

Stream number.

Number----CodecName

Codec format name.

String----CodecLongName

Detailed name of the codec format

String----CodecTimeBase

Codec timebase.

String----CodecTagString

Codec tag name.

String- - - - - CodecTag

Codec tag.

String- - - - - Profile

Video codec profile.

String- - - - - Height

Video height in px.

Number- - - - - Width

Video width in px.

Number----HasBFrame

Whether B-frames exist. 1: yes; 0: no.

Number- - - - - RefFrames

Number of reference frames for video codec.

Number- - - - - Sar

Sample aspect ratio.

String- - - - - Dar

Display aspect ratio.

String- - - - - PixFormat

Pixel format.

String©2013-2022 Tencent Cloud. All rights reserved.

Page 984 of 1869

Cloud Infinite- - - - - FieldOrder

Field order.

String- - - - - Level

Video codec level.

Number- - - - - Fps

Video frame rate.

Number- - - - - AvgFps

Average frame rate.

String- - - - - Timebase

Timebase.

String- - - - - StartTime

Video start time in seconds.

Number- - - - - Duration

Video duration in seconds.

Number- - - - - Bitrate

Bitrate in Kbps.

Number----NumFrames

Total number of frames.

Number- - - - - Language

Language.

String- - - - Audio

Audio information.

Container- - - - - Index

Stream number.

Number----CodecName

Codec format name.

String----CodecLongName

Detailed name of the codec format.

StringCodec timebase.

String----CodecTagString

Codec tag name.

String- - - - - CodecTag

Codec tag.

String----SampleFmt

Sample format.

String----SampleRate

Sample rate.

Number- - - - - Channel

Number of channels.

Number-----Channel layout.

String----CodecTimeBase©2013-2022 Tencent Cloud. All rights reserved.

Page 985 of 1869

Cloud Infinite

ChannelLayout- - - - - Timebase

Timebase.

String- - - - - StartTime

Audio start time in seconds.

Number- - - - - Duration

Audio duration in seconds.

Number- - - - - Bitrate

Bitrate in Kbps.

Number- - - - - Language

Language.

String- - - - Subtitle

Subtitles information.

Container- - - - - Index

Stream number.

Number- - - - - Language

Language. und indicates no query result.

String- - - Format

Format information.

Object- - - - NumStream

Number of streams (including videos, audios, and subtitles).

Number---NumProgram

Number of programs.

Number---FormatName

Container format name.

String---FormatLongName

Detailed name of the container format.

String- - - - StartTime

Start time in seconds.

Number- - - - Duration

Duration in seconds.

Number- - - - Bitrate

Bitrate in Kbps.

Number- - - - Size

Size in bytes.

Number©2013-2022 Tencent Cloud. All rights reserved.

Page 986 of 1869

Cloud Infinite

Media Screenshot APIs：

Last updated 2024-03-01 10:49:05

Overview
This document provides an overview of APIs and SDK code samples for media screenshot.
Note:
The COS JavaScript SDK version must be at least v1.3.1.
API

Operation

Description

GetSnapshot

Querying screenshot

Query the screenshot of media file at some time point

Querying Screenshot
Feature description
This API is used to query the screenshot of a media file at some time point.
Note:
Before using this API, make sure that the media processing feature has been enabled in the data processing sectionin the console; otherwise, the error media bucket unbinded, bucket's host is unavailable will bereported.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 987 of 1869

Cloud Infinite

var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket (required) */Region: 'COS_REGION', /* Bucket region (required) */};cos.request({
Bucket: config.Bucket,
Region: config.Region,
Method: 'GET',
Key: 'test.mp4', /* Media file in bucket (required) */Query: {©2013-2022 Tencent Cloud. All rights reserved.

Page 988 of 1869

Cloud Infinite'ci-process': 'snapshot', /** Fixed value (required) */time: 1, /** Screenshot time point in seconds (required) */// width: 0, /** Screenshot width (optional) */// height: 0, /** Screenshot height (optional) */// format: 'jpg', /** Screenshot format (optional). Valid values: jpg; png.
// rotate: 'auto', /** Image rotation method (optional). Default value: aut// mode: 'exactframe', /** Frame capturing method (optional). Default value},
RawBody: true,},
function(err, data){
console.log(err || data);});

Parameter description
Parameter

Description

Type

Required

BucketBucket name in the format of BucketName-APPID .

StringYes

RegionBucket region. For the enumerated values, see Regions and AccessEndpoints.

StringYes

StringYes

Key

Object key (object name), which is the unique identifier of the object
in the bucket. For more information, see Object Overview.

ci-process

Operation type, which is fixed at snapshot .

StringYes

time

Screenshot time point in seconds.

NumberYes

width

Screenshot width. Default value: 0.

Number

No

NumberNo

StringNo

StringNo

StringNo

Screenshot height. Default value: 0. If width and height areheightboth 0 , the width and height of the video are used. If one of them is
0 , the other value is used to automatically adapt to the aspect ratioof the video.

formatrotatemode

Screenshot format. Valid values: jpg; png. Default value: jpg.
Image rotation method. auto: Rotate automatically according to thevideo rotation information. off: Do not rotate. Default value: auto.
Frame capturing method. keyframe: Capture the last keyframe before
the specified time point. exactframe: Capture the frame at a specified
time point. Default value: exactframe.

©2013-2022 Tencent Cloud. All rights reserved.

Page 989 of 1869

Cloud Infinite

Callback function descriptionfunction(err, data) { ... }Parameter

Description

Type

The object returned when an error (network error or service error) occurs. If
err

the request is successful, this parameter is empty. For more information, see
Error Codes.

Object- statusCode

Returned HTTP status code, such as 200 , 403 , and 404 .

Number©2013-2022 Tencent Cloud. All rights reserved.

Page 990 of 1869

Cloud Infinite- headers

Returned headers.

Objectdata

The object returned when the request is successful. If an error occurs withthe request, this parameter is empty.

Object- statusCode

Returned HTTP status code, such as 200 , 403 , and 404 .

Number- headers

Returned headers.

Object- RequestId

Unique ID of the request.

String- BodyReturned file content, which is in string format by default.

String©2013-2022 Tencent Cloud. All rights reserved.

Page 991 of 1869

Cloud Infinite

Content Moderation
Image Moderation：

Last updated 2024-03-01 10:49:05

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for image moderation.
Note:
The COS JavaScript SDK version must be at least v1.3.1.
API

Description

Moderating single image

Scans existing data stored in COS for pornographic, illegal, and advertising
images.

Batch moderating images

Moderates multiple images in batches.

Single Image Moderation
Feature description
The existing data scan feature of image moderation leverages CI's persistent processing API to scan existing datastored in COS for pornographic, illegal, and advertising images.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 992 of 1869

Cloud Infinite

var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket (required) */Region: 'COS_REGION', /* Bucket region (required) */};function getImageAuditing() {cos.request({
Bucket: config.Bucket,
Region: config.Region,
Method: 'GET',
Key: '1.png', /* Image file in the bucket (required) */©2013-2022 Tencent Cloud. All rights reserved.

Page 993 of 1869

Cloud Infinite

Query: {'ci-process': 'sensitive-content-recognition', /** Fixed value (required)'biz-type': '', /** Moderation type (optional) */'detect-type': 'porn,ads', /** Moderation policy (optional). If this para'detect-url': '', /** URL of any image accessible over the public network'interval': 5, /** Frame capturing interval for GIF image moderation (opt'max-frames': 5, /** Maximum number of frames to be captured for GIF ima'large-image-detect': '0', /** Whether to compress the image first before'dataid': '123', /** Custom image ID (optional) */},},function(err, data){
console.log(err || data);});}

Parameter description
Query has the following sub-nodes:
Node Name

Parent(Keyword)

Node

Description

Type

Required

StringNo

StringNo

StringYes

String

No

Int

No

Moderation policy. If this parameter is not specified,biz-type

Query

the default policy will be used. The policy can be
configured in the console. For more information, see
Setting Moderation Policy.
Moderation type. Valid values: porn , ads . You

detect-type

Querycan specify multiple types and separate them bycomma.

object-key

Query

Location of the image in the bucket.
You can enter a detect-url value to moderate
an image accessible over the public network.
If detect-url is not specified, the backend will
moderate by ObjectKey by default.

detect-url

Query

If detect-url is specified, the backend will
moderate by detect-url , and there will be noneed to enter ObjectKey .
Sample detect-url :http://www.example.com/abc.jpg

interval

Query

For GIF image moderation, you can use thisparameter to configure the frame capturing interval.
The default value is 5 , indicating to capture a©2013-2022 Tencent Cloud. All rights reserved.

Page 994 of 1869

Cloud Infinite

frame every five frames starting from the first frame(included).

max-frames

Query

The maximum number of frames to be captured for
GIF image moderation, which must be greater than0. The default value is 5 , indicating to capture five

Int

No

StringNo

StringNoframes at most.

large-imagedetect

Whether to compress the image that exceeds thesize limit before moderation. Valid values: 0 (no),Query

1 (yes). Default value: 0 .
Note: Images up to 32 MB in size can becompressed, and compression fees will be charged.

dataidQueryImage ID. This field will return the original content in
the result, which can contain up to 512 bytes.

Response description
For more information, see Single Image Moderation.

Batch Image Moderation
Feature description
The batch image moderation API adopts a sync POST request method. You can use this API to perform content
moderation on multiple image files.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 995 of 1869

Cloud Infinite

var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket (required) */Region: 'COS_REGION', /* Bucket region (required) */};function postImagesAuditing() {var host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
var url = 'https://' + host + '/image/auditing';
var body = COS.util.json2xml({
Request: {Input: [{©2013-2022 Tencent Cloud. All rights reserved.

Page 996 of 1869

Cloud Infinite

Object: '1.png', /* Path of the image to be moderated in the bucket */}, {Object: 'a/6.png', /* Path of the image to be moderated in the bucket */}],Conf: {
BizType: '', /* If this parameter is not specified, the default policy will
DetectType: 'Porn' /* Checks for pornographic information only */}}});cos.request({
Bucket: config.Bucket,
Region: config.Region,
Method: 'POST',
Url: url,
Key: '/image/auditing', /** Fixed value (required) */ContentType: 'application/xml', /** Fixed value (required) */Body: body},function(err, data){
console.log(err || data);});}

Parameter description
request has the following sub-nodes:
Node Name(Keyword)
RequestParent NodeDescription

Type

Required

None

Batch image moderation
configuration.

Container

Yes

Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description

Type

Required

Input

RequestContent to be moderated. If there are multiple
images, pass in multiple Input structures.

Container
Array

Yes

Conf

RequestModeration rule configuration.

Container

Yes

Input has the following sub-nodes:©2013-2022 Tencent Cloud. All rights reserved.

Page 997 of 1869

Cloud Infinite

Node
Name
(Keyword)

Parent NodeDescription

Type

Required

StringNo

String

No

Int

No

Int

No

Image ID. This field will return the original content in
the result, which can contain up to 512 bytes.

StringNo

Description

Type

Required

StringYes

StringNo

Name of the image file stored in the COS bucket; forexample, if the file is image.jpg in the test
ObjectRequest.Input

directory, then the filename is test/image.jpg .
Either Object or Url can be selected at atime.
Full URL of the image file, such as http://a-Url

1250000.cos.ap-

Request.Input

shanghai.myqcloud.com/image.jpg . Either
Object or Url can be selected at a time.
Frame capturing frequency, which takes effect forInterval

MaxFrames

GIF images only. The default value is 5 , indicating

Request.Input

to capture a frame every five frames starting fromthe first frame (included).
The maximum number of frames to be captured,
which takes effect for GIF images only. The default
value is 5 , indicating to capture only five frames ofRequest.Input

the GIF image for moderation. The parameter value
must be greater than 0.
DataIdRequest.Input

Conf has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeThe scene to be moderated, such as Porn
DetectType

Request.Conf(pornography) and Ads (advertising). You canpass in multiple types and separate them bycomma, such as Porn,Ads .

BizTypeRequest.Conf

Moderation policy. If this parameter is not specified,the default policy will be used. The policy can be
configured in the console. For more information, see
Setting Moderation Policy.

©2013-2022 Tencent Cloud. All rights reserved.

Page 998 of 1869

Cloud Infinite

Note:
Moderation through Object is a private network operation and will not generate public network traffic.
Moderation through Url will generate public network traffic with regard to the origin where the image resides.
Response description
For more information, see Batch Image Moderation.

©2013-2022 Tencent Cloud. All rights reserved.

Page 999 of 1869

Cloud Infinite

Video Moderation：

Last updated 2024-03-01 10:49:05

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for video moderation.
Note:
The COS JavaScript SDK version must be at least v1.3.1.
API

Description

Submitting video moderation job

Submits video moderation job.

Querying video moderation job result

Queries the result of specified video moderation job.

Submitting Video Moderation Job
Feature description
This API is used to submit a video moderation job.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1000 of 1869

Cloud Infinite

var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket (required) */Region: 'COS_REGION', /* Bucket region (required) */};function postVideoAuditing() {var host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
var url = 'https://' + host + '/video/auditing';
var body = COS.util.json2xml({
Request: {Input: {©2013-2022 Tencent Cloud. All rights reserved.

Page 1001 of 1869

Cloud Infinite

Object: '1.mp4', /* Path of the video file to be moderated in the bucket */},Conf: {
BizType: '',DetectType: 'Porn',Snapshot: {Count: 1000, // Number of frames captured},
DetectContent: 1, // Whether to moderate the video sound. Valid values: `0`}}});cos.request({
Bucket: config.Bucket,
Region: config.Region,
Method: 'POST',
Url: url,
Key: '/video/auditing', /** Fixed value (required) */ContentType: 'application/xml', /** Fixed value (required) */Body: body},function(err, data){
console.log(err || data);});}

Parameter description
Request has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

Input

RequestVideo to be moderated.

Container

Yes

Conf

RequestModeration rule configuration.

Container

Yes

Input has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeDescription

Type

Required

StringYes

StringNo

Name of the video file stored in the COS bucket; for
ObjectRequest.Input

example, if the file is video.mp4 in the test
directory, then the filename is test/video.mp4 .

Url

Request.Input

Full URL of the video file, such as©2013-2022 Tencent Cloud. All rights reserved.

Page 1002 of 1869

Cloud Infinite

http://examplebucket1250000000.cos.apshanghai.myqcloud.com/test.mp4 . Either
Object or Url can be selected at a time.

Conf has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

StringNo

Container

Yes

StringNo

StringNo

String

No

IntegerNo

The scene to be moderated, such as Porn
DetectType

Request.Conf(pornography) and Ads (advertising). You
can pass in multiple types and separate themby comma, such as Porn,Ads .
Video image moderation is implemented bySnapshot

Request.Conf

Callback

Request.Conf

taking a certain number of screenshotsbased on the video frame capturing capability
and then moderating the screenshots one byone. This parameter is used to specify theconfiguration of video frame capturing.
Callback address, which must start with
http:// or https:// .
Structure of the callback content. Validvalues: Simple (the callback content

CallbackVersion

Request.Confcontains basic information), Detail (thecallback content contains detailed
information). Default value: Simple .

BizType

DetectContent

Request.Conf

Request.Conf

Moderation policy. If this parameter is not
specified, the default policy will be used.
Whether to moderate video sound. Validvalues: 0 (moderates the video image
only), 1 (moderates both the video image
and video sound). Default value: 0 .

Snapshot has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

RequiredMode

Request.Conf.Snapshot

Frame capturing mode. Valid values:

StringNo©2013-2022 Tencent Cloud. All rights reserved.

Page 1003 of 1869

Cloud Infinite

Interval (interval mode), Average(average mode), Fps (fixed frame ratemode).
Interval mode: The
TimeInterval and Countparameters take effect. If Count is set
but TimeInterval is not, all frames
will be captured to generate a total ofCount images.
Average mode: The Countparameter takes effect, indicating tocapture a total of Count images at an
average interval in the entire video.
Fps mode: TimeInterval
indicates how many frames to capture persecond, and Count indicates how many
frames to capture in total.
Count

TimeInterval

Request.Conf.Snapshot

The number of captured frames. Value
range: (0, 10000].

String

No

Request.Conf.Snapshot

Video frame capturing frequency. Value
range: (0.000, 60.000] seconds. The value
supports the float format, accurate to themillisecond.

Float

No

Response description
For more information, see Submitting Video Moderation Job.

Querying Video Moderation Job Result
Feature description
This API is used to query the status and result of a video moderation job.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1004 of 1869

Cloud Infinite

var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket (required) */Region: 'COS_REGION', /* Bucket region (required) */};function getVideoAuditingResult() {var jobId = 'av14d9ca15af3a11eca0d6525400d88xxx'; // `jobId`, which is returned avar host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
var url = 'https://' + host + '/video/auditing/' + jobId;
cos.request({
Bucket: config.Bucket,©2013-2022 Tencent Cloud. All rights reserved.

Page 1005 of 1869

Cloud Infinite

Region: config.Region,
Method: 'GET',
Key: '/video/auditing/' + jobId,
Url: url,},function(err, data){
console.log(err || data);});}

Parameter description
Parameter

Description

Type

RequiredjobId

ID of the job to be queried.

StringYes

Response description
For more information, see Querying Video Moderation Job Result.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1006 of 1869

Cloud Infinite

Audio Moderation：

Last updated 2024-03-01 10:49:05

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for audio moderation.
Note:
The COS JavaScript SDK version must be at least v1.3.1.
API

Description

Submitting audio moderation job

Submits audio moderation job.

Querying audio moderation job result

Queries the result of specified audio moderation job.

Submitting Audio Moderation Job
Feature description
This API is used to submit an audio moderation job.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1007 of 1869

Cloud Infinite

var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket (required) */Region: 'COS_REGION', /* Bucket region (required) */};function postAudioAuditing() {var host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
var url = 'https://' + host + '/audio/auditing';
var body = COS.util.json2xml({
Request: {Input: {©2013-2022 Tencent Cloud. All rights reserved.

Page 1008 of 1869

Cloud Infinite

Object: '1.mp3', /* Path of the audio file to be moderated in the bucket */},Conf: {
BizType: '',DetectType: 'Porn',}}});cos.request({
Bucket: config.Bucket,
Region: config.Region,
Method: 'POST',
Url: url,
Key: '/audio/auditing', /** Fixed value (required) */ContentType: 'application/xml', /** Fixed value (required) */Body: body},function(err, data){
console.log(err || data);});}

Parameter description
Request has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

Input

RequestContent to be moderated.

Container

Yes

Conf

RequestModeration rule configuration.

Container

Yes

Input has the following sub-nodes:
Node
Name
(Keyword)

ObjectParent NodeRequest.Input

Description

Name of the audio file stored in the COS bucket; forexample, if the file is audio.mp3 in the test
directory, then the filename is test/audio.mp3 .

Type

Required

StringNo

StringNo

Either Object or Url can be selected at a time.
Url

Request.Input

Full URL of the audio file, such as
http://examplebucket1250000000.cos.ap-©2013-2022 Tencent Cloud. All rights reserved.

Page 1009 of 1869

Cloud Infinite

shanghai.myqcloud.com/audio.mp3 . Either
Object or Url can be selected at a time.

Conf has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

StringNo

StringNo

stringNo

StringNo

The scene to be moderated, such as Porn
(pornography), Ads (advertising),
DetectType

Request.Conf

Illegal (illegal), and Abuse (abusive).
You can pass in multiple types and separate
them by comma, such as Porn,Ads .

Callback

Request.Conf

The moderation result can be sent to yourcallback address in the form of a callback.
Addresses starting with http:// or
https:// are supported, such as
http://www.callback.com .
Structure of the callback content. Valid values:
Simple (the callback content contains basic

CallbackVersion

Request.Conf

information), Detail (the callback content
contains detailed information). Default value:
Simple .
Moderation policy. If this parameter is not
specified, the default policy will be used. The

BizTypeRequest.Conf

policy can be configured in the console. For
more information, see Setting Moderation
Policy.

Response description
For more information, see Submitting Audio Moderation Job.

Querying Audio Moderation Job
Feature description
This API is used to query the status and result of an audio moderation job.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1010 of 1869

Cloud Infinite

var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket (required) */Region: 'COS_REGION', /* Bucket region (required) */};function getAudioAuditingResult() {var jobId = 'sa0c28d41daff411ecb23352540078cxxx'; // `jobId`, which is returned avar host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
var url = 'https://' + host + '/audio/auditing/' + jobId;
cos.request({
Bucket: config.Bucket,©2013-2022 Tencent Cloud. All rights reserved.

Page 1011 of 1869

Cloud Infinite

Region: config.Region,
Method: 'GET',
Key: '/audio/auditing/' + jobId,
Url: url,},function(err, data){
console.log(err || data);});}

Parameter description
Parameter

Description

Type

RequiredjobId

ID of the job to be queried.

StringYes

Response description
For more information, see Querying Audio Moderation Job Result.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1012 of 1869

Cloud Infinite

Text Moderation：

Last updated 2024-03-01 10:49:05

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for text moderation.
Note:
The COS JavaScript SDK version must be at least v1.3.1.
API

Description

Submitting text moderation job

Submits text moderation job.

Querying text moderation job result

Queries the result of specified text moderation job.

Submitting Text Moderation Job
Feature description
This API is used to submit a text moderation job.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1013 of 1869

Cloud Infinite

var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket (required) */Region: 'COS_REGION', /* Bucket region (required) */};function postTextAuditing() {var host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
var url = 'https://' + host + '/text/auditing';
var body = COS.util.json2xml({
Request: {Input: {©2013-2022 Tencent Cloud. All rights reserved.

Page 1014 of 1869

Cloud Infinite

Object: 'hello.txt', /* Path of the text file to be moderated in the bucket},
Conf: {
BizType: '',DetectType: 'Porn',}}});cos.request({
Bucket: config.Bucket,
Region: config.Region,
Method: 'POST',
Url: url,
Key: '/text/auditing', /** Fixed value (required) */ContentType: 'application/xml', /** Fixed value (required) */Body: body},function(err, data){
console.log(err || data);});}

Parameter description
Request has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

RequestNone

Text moderation configuration.

Container

Yes

Request has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

Input

RequestContent to be moderated.

Container

Yes

Conf

RequestModeration rule configuration.

Container

Yes

Input has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeDescription

Type

Required

ObjectRequest.Input

Name of the text file stored in the current COS bucket;
for example, if the file is test.txt in the test

StringNo

directory, then the filename is test/test.txt .

©2013-2022 Tencent Cloud. All rights reserved.

Page 1015 of 1869

Cloud Infinite

Only text files in UTF-8 and GBK encodings aresupported, and the file size cannot exceed 1 MB.

Content

Request.Input

When the input content is plain text, it needs to be
Base64-encoded first. The length of the original text
before encoding cannot exceed 10,000 UTF-8
characters. If the length limit is exceeded, the API will

StringNoreport an error.

Note:
Object and Content cannot be entered at the same time.
If Object is selected, the moderation result will be returned asynchronously, which can be obtained through the
API for querying text moderation job result.
If Content is selected, the moderation result will be returned synchronously, which can be viewed in the
TextAuditingResponse response body.
Currently, only Chinese, English, and Arabic numerals can be detected and moderated.
Conf has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeDescription

Type

Required

StringNo

StringNo

StringNo

The scene to be moderated, such as Porn
(pornography), Ads (advertising), Illegal
DetectType

Request.Conf(illegal), and Abuse (abusive). You can pass in
multiple types and separate them by comma, such as
Porn,Ads .

Callback

Request.Conf

The moderation result can be sent to your callback
address in the form of a callback. Addresses startingwith http:// or https:// are supported,
such as http://www.callback.com .

BizTypeRequest.Conf

Moderation policy. If this parameter is not specified,the default policy will be used. The policy can be
configured in the console. For more information, see
Setting Moderation Policy.

Response description
For more information, see Submitting Text Moderation Job.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1016 of 1869

Cloud Infinite

Querying Text Moderation Job
Feature description
This API is used to query the status and result of a text moderation job.
Sample request

var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket (required) */©2013-2022 Tencent Cloud. All rights reserved.

Page 1017 of 1869

Cloud Infinite

Region: 'COS_REGION', /* Bucket region (required) */};function getTextAuditingResult() {var jobId = 'st8d88c664aff511ecb23352540078cxxx'; // `jobId`, which is returned avar host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
var url = 'https://' + host + '/text/auditing/' + jobId;
cos.request({
Bucket: config.Bucket,
Region: config.Region,
Method: 'GET',
Key: '/text/auditing/' + jobId,
Url: url,},function(err, data){
console.log(err || data);});}

Parameter description
Parameter

Description

Type

RequiredjobId

ID of the job to be queried.

StringYes

Response description
For more information, see Querying Text Moderation Job Result.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1018 of 1869

Cloud Infinite

Webpage Moderation：

Last updated 2024-03-01 10:49:05

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for webpage moderation.
Note:
The COS JavaScript SDK version must be at least v1.3.1.
API

Description

Submitting webpage moderation job

Submits webpage moderation job.

Querying webpage moderation job result

Queries the result of specified webpage moderation job.

Submitting Webpage Moderation Job
Feature description
This API is used to submit a webpage moderation job.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1019 of 1869

Cloud Infinite

var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket (required) */Region: 'COS_REGION', /* Bucket region (required) */};function postWebpageAuditing() {var host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
var url = 'https://' + host + '/webpage/auditing';
var body = COS.util.json2xml({
Request: {Input: {©2013-2022 Tencent Cloud. All rights reserved.

Page 1020 of 1869

Cloud Infinite

Url: 'https://cloud.tencent.com/', // The resource stored in COS. The moder},
Conf: {
BizType: '',DetectType: 'Porn,Ads',}}});cos.request({
Bucket: config.Bucket,
Region: config.Region,
Method: 'POST',
Url: url,
Key: '/webpage/auditing', /** Fixed value (required) */ContentType: 'application/xml', /** Fixed value (required) */Body: body},function(err, data){
console.log(err || data);});}

Parameter description
Request has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

RequestNone

Webpage moderation configuration.

Container

Yes

Request has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

Input

RequestWebpage to be moderated.

Container

Yes

Conf

RequestModeration rule configuration.

Container

Yes

Input has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeDescription

Type

Required

Url

Request.Input

Full URL of the webpage, such as
http://www.test.com .

StringYes©2013-2022 Tencent Cloud. All rights reserved.

Page 1021 of 1869

Cloud Infinite

DataIdRequest.Input

This field will return the original content in themoderation result, which can contain up to 512
bytes. You can use this field to uniquely identify

StringNo

ContainerNo

the data to be moderated in your business.
UserInfo

Request.Input

Business field.

UserInfo has the following sub-nodes:
Node
Name
(Keyword)

Parent Node

TokenId

Request.Input.UserInfo

Nickname

Request.Input.UserInfo

DeviceId

Request.Input.UserInfo

AppId

Request.Input.UserInfo

Room

Request.Input.UserInfo

IP

Request.Input.UserInfo

Type

Request.Input.UserInfo

Description

Business TokenId , which can containup to 128 bytes.
Business Nickname , which can containup to 128 bytes.
Business DeviceId , which can containup to 128 bytes.
Business AppId , which can contain up to
128 bytes.
Business Room , which can contain up to
128 bytes.
Business IP , which can contain up to 128
bytes.
Business Type , which can contain up to
128 bytes.

Type

Required

StringNo

StringNo

StringNo

StringNo

StringNo

StringNo

String

No

Conf has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

The scene to be moderated, such as
Porn (pornography) and Ads
DetectType

Request.Conf(advertising). You can pass in multiple
types and separate them by comma, suchas Porn,Ads .

StringYes

Callback

Request.Conf

Callback address, which must start with

StringNo©2013-2022 Tencent Cloud. All rights reserved.

Page 1022 of 1869

Cloud Infinite

http:// or https:// .

ReturnHighlightHtml

Request.Conf

This parameter specifies whether tohighlight the non-compliant text on the
webpage. When the result is queried orcalled back, this parameter decides
whether to return the highlighted HTML

BooleanNo

content. Valid values: true , false .
Default value: false .

Response description
For more information, see Submitting Webpage Moderation Job.

Querying Webpage Moderation Job Result
Feature description
This API is used to query the status and result of a webpage moderation job.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1023 of 1869

Cloud Infinite

var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket (required) */Region: 'COS_REGION', /* Bucket region (required) */};function getWebpageAuditingResult() {var jobId = 'shce868019aff611ecb1155254009a4xxx'; // `jobId`, which is returned avar host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
var url = 'https://' + host + '/webpage/auditing/' + jobId;
cos.request({
Bucket: config.Bucket,©2013-2022 Tencent Cloud. All rights reserved.

Page 1024 of 1869

Cloud Infinite

Region: config.Region,
Method: 'GET',
Key: '/webpage/auditing/' + jobId,
Url: url,},function(err, data){
console.log(err || data);});}

Parameter description
Parameter

Description

Type

RequiredjobId

ID of the job to bequeried.

StringYes

Response description
For more information, see Querying Webpage Moderation Job Result.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1025 of 1869

Cloud Infinite

File Processing
File Decompression：

Last updated 2024-03-01 10:49:05

Overview
This document provides an overview of APIs and SDK code samples for file decompression in CI.
Note:
The COS JavaScript SDK version must be at least v1.3.1.
API

Description

Submitting a file decompression job

Creates a file decompression job.

Querying the file decompression result

Queries a file decompression job.

Submitting a File Decompression Job
Feature description
This API is used to submit a job to perform file decompression and asynchronously return decompressed files.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1026 of 1869

Cloud Infinite

function postFileUnCompressTask() {var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket. Required */Region: 'COS_REGION',/* Bucket region. Required */};var host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com/file_jobs';
var url = 'https://' + host;var body = COS.util.json2xml({
Request: {Tag: 'FileUncompress', // Required©2013-2022 Tencent Cloud. All rights reserved.

Page 1027 of 1869

Cloud Infinite

Input: {Object: 'compressed.zip', // Filename, which is the full name of the file i},
Operation: {FileUncompressConfig: {Prefix: '', // Prefix of the input file after decompression. If this para
PrefixReplaced: '0', // Whether to replace the prefix of the directory of},
Output: {Bucket: config.Bucket, // Bucket where the decompressed files are stored
Region: config.Region, // Region of the bucket where the decompressed fil},},// QueueId: '', // ID of the queue where the job is in// CallBack: 'http://callback.demo.com', // Job callback address// CallBackFormat: 'JSON', // Job callback format// CallBackType: 'Url', // Job callback type, which can be `Url` (default) or}});cos.request({
Method: 'POST',
Key: 'file_jobs',
Url: url,
Body: body,ContentType: 'application/xml',},
function(err, data){
console.log(err || data);});}
postFileUnCompressTask();Parameter description
Request has the following sub-nodes:
Node Name

Parent(Keyword)

Node

Tag

Request

Input

RequestOperation
QueueId

Description

Type

Required

StringYes

Information about the file to be operated.

Container

Yes

RequestFile decompression rule.

Container

Yes

RequestID of the queue where the job is in.

StringYes

Job type. It is FileUncompress for file
decompression by default.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1028 of 1869

Cloud Infinite

CallBackFormat

RequestJob callback format, which can be JSON or

StringNo

StringNo

StringNo

ContainerNo

XML (default). It takes priority over that of thequeue.
Job callback type, which can be Url (default)
CallBackType

Requestor TDMQ . It takes priority over that of thequeue.

CallBack

RequestCallBackMqConfig

RequestJob callback address. It takes priority over thatof the queue.
TDMQ configuration for job callback as
described in Structure, which is required if
CallBackType is TDMQ .

Input has the following sub-nodes:
Node
Name

Parent NodeDescription

Type

Required

Request.Input

Filename, which is the full name of the file in thebucket.

StringYes(Keyword)
ObjectOperation has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

FileUncompressConfig

Request.Operation

File decompression rule.

Container

Yes

Request.Operation

The user information passed
through, which is printable ASCII

StringNo

Container

Yes

UserData

codes of up to 1,024 in length.
Information about the bucket
OutputRequest.Operation

where the decompressed file isstored.

FileUncompressConfig has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

Prefix

Request.Operation.FileUncompressConfig

Prefix of the input file

StringNoafter decompression.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1029 of 1869

Cloud Infinite

If this parameter isleft empty, the file isstored in the root
directory of thebucket by default.
PrefixReplaced

Request.Operation.FileUncompressConfig

Whether to replace
the prefix of theStringNo

directory of thedecompressed file.
Valid values:
0 : No additional
prefix is added. The
decompressed files
are saved in the
directory specified by
Prefix (thename of thecompressed package
is not retained, andthe file in thecompressed package
is saved to thespecified directoryonly).
1 : The name of
the compressedpackage is used as
the prefix. The
decompressed files
are saved in the
directory specified by
Prefix .
2 : The full
directory of thecompressed package
is used as the prefix.
If Prefix is not
specified, the file isdecompressed to thecurrent directory(including the nameof the compressedpackage) of the©2013-2022 Tencent Cloud. All rights reserved.

Page 1030 of 1869

Cloud Infinite

compressedpackage.
Default value: 0 .

Notes:
If the compressed package is named test.zip , contains the image.jpg file, and is stored in the 123
directory in bucket A, the full directory of the compressed package is 123/test.zip .
Decompress the package to bucket A with Prefix set to 456 . The storage directory of the decompressed filevaries depending on the value of PrefixReplaced :0 : The image.jpg file is stored in the 456 directory and its full directory is 456/image.jpg .
1 : The image.jpg file is stored in the 456 directory with prefix test and its full directory is456/test/image.jpg .
2 : The image.jpg file is stored in the 456 directory with prefix 123/test and its full directory is456/123/test/image.jpg .
Output has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

RequiredRegionRequest.Operation.Output

Bucket region.

StringYes

BucketRequest.Operation.Output

Bucket where the decompressed
files are stored.

StringYes

Response description
For more information, see Submitting a File Decompression Job.

Querying File Decompression Result
Feature description
This API is used to query the details of a file processing job by job ID.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1031 of 1869

Cloud Infinite

function getFileUnCompressTask() {var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket. Required */Region: 'COS_REGION',/* Bucket region. Required */};var jobId = 'xxxxxx'; // After the file decompression job is submitted, its `jobI
var host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com/file_jobs/' +var url = 'https://' + host;cos.request({
Method: 'GET',©2013-2022 Tencent Cloud. All rights reserved.

Page 1032 of 1869

Cloud Infinite

Key: 'file_jobs/' + jobId,
Url: url,},function(err, data){
console.log(err || data);});}
getFileUnCompressTask();Parameter description
Parameter

Description

Type

RequiredjobId

ID of the job to be queried.

StringYes

Response description
For more information, see Querying File Decompression Result.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1033 of 1869

Cloud Infinite

Multi-File Zipping：

Last updated 2024-03-01 10:49:05

Overview
This document provides an overview of APIs and SDK code samples for file zipping in CI.
Note:
The COS JavaScript SDK version must be at least v1.3.1.
API

Description

Submitting a multi-file zipping job

Creates a multi-file zipping job.

Querying the multi-file zipping result

Queries the result of a specified multi-file zipping job.

Submitting a Multi-File Zipping Job
Feature description
The multi-file zipping feature uses a request to zip multiple files into a compressed file such as a ZIP file. You can
submit a job to zip multiple files and asynchronously return the compressed file.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1034 of 1869

Cloud Infinite

function postFileCompressTask() {var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket. Required */Region: 'COS_REGION',/* Bucket region. Required */};var host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com/file_jobs';
var url = 'https://' + host;var body = COS.util.json2xml({
Request: {Tag: 'FileCompress', // Required©2013-2022 Tencent Cloud. All rights reserved.

Page 1035 of 1869

Cloud Infinite

Operation: {FileCompressConfig: {Flatten: '0', // Whether to remove the directory structure of the origina
Format: 'zip', // Zipping type. Valid values: `zip`, `tar`, `tar.gz`.
// Only one of UrlList, Prefix, and Key can be selected. They cannot all// UrlList: '', // Object address of the index filePrefix: 'testCompress/', // Directory prefix// Key: [], // Multiple files in the bucket can be zipped. The number of},
Output: {Bucket: config.Bucket, // Bucket where the compressed file is stored
Region: config.Region, // Region of the bucket where the compressed file
Object: 'testCompress/compressed.zip', // Name of the compressed file},
UserData: '',},// QueueId: '', // ID of the queue where the job is in// CallBack: 'http://callback.demo.com', // Job callback address// CallBackFormat: 'JSON', // Job callback format// CallBackType: 'Url', // Job callback type, which can be `Url` (default) or}});cos.request({
Method: 'POST',
Key: 'file_jobs',
Url: url,
Body: body,ContentType: 'application/xml',},
function(err, data){
console.log(err || data);});}
postFileCompressTask();Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

Parent
Node

Tag

RequestOperation

RequestDescription
Job type. It is FileCompress for multi-filezipping by default.
File zipping rule.

©2013-2022 Tencent Cloud. All rights reserved.

Type

Required

StringYes

Container

Yes

Page 1036 of 1869

Cloud Infinite

QueueId

RequestID of the queue where the job is in.

StringNo

StringNo

StringNo

StringNo

ContainerNo

Job callback format, which can be JSON or
CallBackFormat

RequestXML (default). It takes priority over that of thequeue.
Job callback type, which can be Url (default)

CallBackType

Requestor TDMQ . It takes priority over that of thequeue.

CallBack

RequestCallBackMqConfig

RequestJob callback address. It takes priority over thatof the queue.
TDMQ configuration for job callback as
described in Structure, which is required if
CallBackType is TDMQ .

Operation has the following sub-nodes:
Node Name

Parent NodeDescription

Type

Required

Request.Operation

File zipping rule.

Container

Yes

UserData

Request.Operation

The user information passed
through, which is printable ASCII
codes of up to 1,024 in length.

StringNo

OutputRequest.Operation

Container

Yes(Keyword)
FileCompressConfig

Address where the compressed fileis stored.

FileCompressConfig has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeDescription

Type

FlattenRequest.Operation.FileCompressConfig

Whether to remove the directory structure ofStringthe original file during file zipping. Validvalues:0 : No. After file zipping, the original
directory structure is retained.
1 : Yes. After file zipping, the original
directory structure is removed and all files
are at the same level.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1037 of 1869

Cloud Infinite

Assume that the original file URL is
https://domain/source/test.mp4
and the original file directory issource/test.mp4 . If this parameter is
set to 1 , the file directory in the ZIP file istest.mp4 . If this parameter is set to
0 , the file directory in the ZIP file issource/test.mp4 .
FormatRequest.Operation.FileCompressConfig

Zipping type. Valid values: zip , tar ,tar.gz .

StringFiles to be zipped can be sorted into anindex file. The backend zips the files into acompressed file according to the file URL
provided in the index file. The index file mustbe saved in the current bucket, and this fieldmust provide the object address of the index
file, for example, /test/index.csv .
UrlListRequest.Operation.FileCompressConfig

Index file format: Only CSV files in which one
URL occupies one row (only files in thebucket are supported) are supported. If
there are multiple columns, the first column
is used as the URL by default. The number

Stringof files cannot exceed 10,000 and the total
size cannot exceed 50 GB. Otherwise, thejob will fail.
Files with a specified prefix in the bucket can

Prefix

Request.Operation.FileCompressConfig

be zipped. To zip files in a specified
directory, add / to the directory. For
example, to zip files in the test directory,
set this parameter to test/ . The number

Stringof files cannot exceed 10,000 and the total
size cannot exceed 50 GB. Otherwise, thejob will fail.

Key

Request.Operation.FileCompressConfig

Multiple files in the bucket can be zipped.
The number of files cannot exceed 1,000
and the total size cannot exceed 50 GB.
Otherwise, the job will fail.

String
array

Note:

©2013-2022 Tencent Cloud. All rights reserved.

Page 1038 of 1869

Cloud Infinite

Only one of UrlList, Prefix, and Key can be selected. They cannot all be empty or do not take effect at the same time. If
multiple parameters are specified, the parameter with the highest priority prevails according to the priority UrlList >Prefix > Key.
Output has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

RequiredRegionRequest.Operation.Output

Bucket region.

StringYes

BucketRequest.Operation.Output

Bucket where the compressed fileis stored.

StringYes

ObjectRequest.Operation.Output

Name of the compressed file.

StringYes

Response description
For more information, see Submitting a Multi-File Zipping Job.

Querying Multi-File Zipping Result
Feature description
This API is used to query the details of a file processing job by job ID.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1039 of 1869

Cloud Infinite

function getFileCompressTask() {var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket. Required */Region: 'COS_REGION',/* Bucket region. Required */};var jobId = 'xxxxxx'; // After the multi-file zipping job is submitted, its `jobI
var host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com/file_jobs/' +var url = 'https://' + host;cos.request({
Method: 'GET',©2013-2022 Tencent Cloud. All rights reserved.

Page 1040 of 1869

Cloud Infinite

Key: 'file_jobs/' + jobId,
Url: url,},function(err, data){
console.log(err || data);});}
getFileCompressTask();Parameter description
Parameter

Description

Type

RequiredjobId

ID of the job to be queried.

StringYes

Response description
For more information, see Querying Multi-File Zipping Result.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1041 of 1869

Cloud Infinite

Hash Calculation：

Last updated 2024-03-01 10:49:05

Overview
This document provides an overview of APIs and SDK code samples for hash calculation in CI.

Note:
The COS JavaScript SDK version must be at least v1.3.1.
API

Description

Submitting a hash calculation job

Creates a hash calculation job.

Querying the hash calculation result

Queries the result of a hash calculation job.

Submitting a Hash Calculation Job
Feature description
This API is used to submit a job to perform hash calculation and asynchronously return a calculated hash value.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1042 of 1869

Cloud Infinite

function postFileHashTask() {var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket. Required */Region: 'COS_REGION',/* Bucket region. Required */};var host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com/file_jobs';
var url = 'https://' + host;var body = COS.util.json2xml({
Request: {Tag: 'FileHashCode', // Required©2013-2022 Tencent Cloud. All rights reserved.

Page 1043 of 1869

Cloud Infinite

Input: {Object: 'test/1.pdf', // Filename, which is the full name of the file in th},
Operation: {FileHashCodeConfig: {Type: 'MD5', // Hash algorithm. Valid values: `MD5`, `SHA1`, `SHA256`.
AddToHeader: 'false', // Whether to add the calculated hash value to the},// UserData: '', // The user information passed through, which is printable},// QueueId: '', // ID of the queue where the job is in// CallBack: 'http://callback.demo.com', // Job callback address// CallBackFormat: 'JSON', // Job callback format// CallBackType: 'Url', // Job callback type, which can be `Url` (default) or}});cos.request({
Method: 'POST',
Key: 'file_jobs',
Url: url,
Body: body,ContentType: 'application/xml',},
function(err, data){
console.log(err || data);});}
postFileHashTask();Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

Parent
Node

Tag

RequestOperation

RequestQueueId

RequestDescription

Type

Required

StringYes

Hash calculation rule.

Container

Yes

ID of the queue where the job is in.

StringYes

String

No

Job type. It is FileHashCode for hashcalculation.

Job callback format, which can be JSON or
CallBackFormat

RequestXML (default). It takes priority over that of thequeue.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1044 of 1869

Cloud Infinite

CallBackType

RequestJob callback type, which can be Url

StringNo

StringNo

ContainerNo(default) or TDMQ . It takes priority over that of
the queue.
CallBack

RequestCallBackMqConfig

RequestJob callback address. It takes priority over thatof the queue.
TDMQ configuration for job callback as
described in Structure, which is required if
CallBackType is TDMQ .

Input has the following sub-nodes:
Node Name

Parent Node

(Keyword)
ObjectRequest.Input

Description
Filename, which is the full name of the file inthe bucket.

Type

Required

StringYes

Operation has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

FileHashCodeConfig

Request.Operation

Hash calculation rule.

Container

Yes

Request.Operation

The user information passed
through, which is printable ASCII
codes of up to 1,024 in length.

String

No

UserData

FileHashCodeConfig has the following sub-nodes:
Node Name(Keyword)Type

Parent NodeDescription

Type

Required

Request.Operation.FileHashCodeConfig

Hash algorithm. Validvalues: MD5 ,StringYes

StringNo

SHA1 , SHA256 .
AddToHeader

Request.Operation.FileHashCodeConfig

Whether to add thecalculated hash value
to the custom header inthe file. Valid values:
true , false(default).<br>The
custom header varies©2013-2022 Tencent Cloud. All rights reserved.

Page 1045 of 1869

Cloud Infinite

depending on Type .
For example, if
Type is MD5 , thecustom header is xcos-meta-md5 .

Response description
For more information, see Submitting Hash Calculation Job.

Querying Hash Calculation Result
Feature description
This API is used to query the details of a file processing job by job ID.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1046 of 1869

Cloud Infinite

function getFileHashTask() {var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket. Required */Region: 'COS_REGION',/* Bucket region. Required */};var jobId = 'xxxxxx'; // After the file has calculation job is submitted, its `jovar host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com/file_jobs/' +var url = 'https://' + host;cos.request({
Method: 'GET',©2013-2022 Tencent Cloud. All rights reserved.

Page 1047 of 1869

Cloud Infinite

Key: 'file_jobs/' + jobId,
Url: url,},function(err, data){
console.log(err || data);});}
getFileHashTask();Parameter description
Parameter

Description

Type

RequiredjobId

ID of the job to bequeried.

StringYes

Response description
For more information, see Querying Hash Calculation Result.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1048 of 1869

Cloud Infinite

Node.js SDK
Getting Started：

Last updated 2024-03-01 14:25:48

Download and Installation
Relevant resources
Download the COS XML SDK resources for Node.js here.
SDK download: XML Node.js SDK.
Download the demo here.
For the complete sample code, see SDK Sample Code.
For the SDK changelog, see Changelog.
Note:
If you encounter errors such as non-existent functions or methods when using the SDK, you can update the SDK to
the latest version and try again.
Environmental dependencies
1. The SDK requires your runtime environment to include Node.js (v6 or later) and npm.
2. Log in to the COS console, create a bucket, and get the bucket name and region name.
3. Log in to the CAM console and get your project's SecretId and SecretKey .
Note:
For the definition of terms such as SecretId, SecretKey, and Bucket, see COS Glossary.
Installing SDK
Install the SDK through npm which can be downloaded here.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1049 of 1869

Cloud Infinite

npm i cos-nodejs-sdk-v5 --saveGetting Started
InitializationNote:©2013-2022 Tencent Cloud. All rights reserved.

Page 1050 of 1869

Cloud Infinite

We recommend you use a temporary key as instructed in Generating and Using Temporary Keys to call the SDK for
security purposes. When you apply for a temporary key, follow the Notes on Principle of Least Privilege to avoid
leaking resources besides your buckets and objects.
If you must use a permanent key, we recommend you follow the Notes on Principle of Least Privilege to limit the scopeof permission on the permanent key.
Using a temporary key for initialization (recommended)
For more information on how to generate and use a temporary key, see Generating and Using Temporary Keys. The
SDK for Node.js supports initialization by passing in a temporary key as shown in the sample code below:©2013-2022 Tencent Cloud. All rights reserved.

Page 1051 of 1869

Cloud Infinite

var request = require('request');var COS = require('cos-nodejs-sdk-v5');
var cos = new COS({
getAuthorization: function (options, callback) {// It will not be called during initialization and will be entered only whe// Get a temporary key asynchronously.
request({url: 'https://example.com/sts',
data: {// The required parameters can be obtained from options.
}}, function (err, response, body) {try {var data = JSON.parse(body);
var credentials = data.credentials;} catch(e) {}if (!data || !credentials) return console.error('credentials invalid');callback({
TmpSecretId: credentials.tmpSecretId, // tmpSecretId of the tempora
TmpSecretKey: credentials.tmpSecretKey, // tmpSecretKey of the temp
SecurityToken: credentials.sessionToken, // sessionToken of the tem
ExpiredTime: data.expiredTime, // Expiration timestamp of the tempo
});
});
}
});

Using a permanent key for initialization (not recommended)
When using a permanent key for initialization, store the key properly to prevent leakage.
First, log in to the CAM console, and get your SecretId and SecretKey from the Access Key page.
Replace SecretId , SecretKey , bucket , and region with the actual values in your development
environment. To test file upload, see the following sample code.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1052 of 1869

Cloud Infinite// Log in to https://console.tencentcloud.com/cam/capi to check and manage the Secrvar COS = require('cos-nodejs-sdk-v5');
var cos = new COS({
SecretId: process.env.SecretId, // User `SecretId`. We recommend you obtain it
SecretKey: process.env.SecretKey, // User `SecretKey`. We recommend you obtain});
Below are some common APIs. For more detailed initialization methods, see the demo.

Configuration item

©2013-2022 Tencent Cloud. All rights reserved.

Page 1053 of 1869

Cloud Infinite

Constructor parameters
Parameter

Description

Type

Required

SecretId

User SecretId

StringYes

SecretKey

User SecretKey

StringYes

NumberNo

FileParallelLimit

Number of concurrent file uploads in the same instance.
Default value: 3

ChunkParallelLimit

Number of concurrent part uploads for the same
uploaded file. Default value: 3

NumberNo

ChunkRetryTimes

Number of retries for multipart upload failure. Default
value: 2 (a request will be made 3 time in total,
including the initial one)

NumberNo

ChunkSize

Part size in the multipart upload in bytes. Default value:
1048576 (1 MB)

Number

No

Number

No

Number

No

Number

No

Number

No

NumberNo

StringNo

When files are uploaded in batches using
uploadFiles , if the file size is greater than the
SliceSize

CopyChunkParallelLimit

CopyChunkSize

value of this parameter (measured in bytes), multipartupload is used; otherwise, simple upload is used.
Default value: 1048576 (1 MB)
Number of concurrent part uploads for the same
multipart copy operation. Default value: 20
Number of bytes in each part during a multipart copy
operation with sliceCopyFile . Default value:
10485760 (10 MB)
When a file is copied using sliceCopyFile , if the

CopySliceSize

ProgressInterval

file size is greater than the value of this parameter,
multipart copy is used; otherwise, simple copy is used.
Default value: 10485760 (10 MB)
Callback frequency of the upload progress callback
method onProgress in milliseconds. Default value:
1000

ProtocolThe protocol used when the request is made. Validvalues: https: , http: . By default, http: isused when the current page is determined to be in
http: format; otherwise, https: is used©2013-2022 Tencent Cloud. All rights reserved.

Page 1054 of 1869

Cloud Infinite

ServiceDomain

The request domain name when getService isStringNo

StringNo

NumberNo

BooleanNo

BooleanNo

NumberNo

BooleanNocalled, such as service.cos.myqcloud.com
Custom request domain name used to call a bucket or
object API. You can use a template
Domainsuch as "{Bucket}.cos.
{Region}.myqcloud.com" which will use thebucket and region information passed in thereplacement parameters when an API is called.
The maximum size of the upload queue. If theUploadQueueSize

ForcePathStyle

maximum is exceeded, failed, completed, and canceledtasks will be cleared. Default value: 1000
Forces the use of a suffix when sending requests. The
suffixed bucket will be placed in the pathname after thedomain name, and the bucket will be added to thesignature pathname for calculation. Default value: false
Forces the verification of Content-MD5 for file

UploadCheckContentMd5

uploads, which calculates the MD5 checksum of the file
request body and places it in the Content-MD5
field of the header. Default value: false

Timeout

KeepAlive

Timeout period in milliseconds. Default value: 0,
indicating no timeout period.
Indicates that more than one request is sent over one
TCP connection. Default value: true . Thisparameter is recommended for a large number ofconcurrent requests.

StrictSsl

Strict verification of the HTTPS certificate. Default
value: true

BooleanNo

ProxyUses an HTTP proxy when making requests, such as:
http://127.0.0.1:8080

String

No

FunctionNo

BooleanNo

Callback method for getting the signature. If there is no
getAuthorization

SecretId or SecretKey , this parameter isrequired

UseAccelerate

Whether to enable a global acceleration endpoint.
Default value: false . If you set the value totrue , you need to enable global acceleration for the
bucket. For more information, see Enabling Global
Acceleration.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1055 of 1869

Cloud Infinite

getAuthorization Callback function description (Format 1)

getAuthorization: function(options, callback) { ... }getAuthorization function parameters:
Parameter

Description

Type

options

Required for getting the signature

Object©2013-2022 Tencent Cloud. All rights reserved.

Page 1056 of 1869

Cloud Infinite- Bucket

Bucket name in the format of BucketName-APPID . The bucket name entered

Stringhere must be in this format- Region

Bucket region. For the enumerated values, see Regions and Access Endpoints.

Stringcallback

Callback method after the temporary key is obtained

Function

After the temporary key is obtained, the callback returns an object. The attributes of the returned object are as listed
below:
Attribute

Description

Type

Required

TmpSecretId

tmpSecretId of the obtained temporary key

StringYes

TmpSecretKey

tmpSecretKey of the obtained temporary key

StringYes

SecurityTokensessionToken of the obtained temporary key, which corresponds
to the x-cos-security-token field in the header

StringYes

StringNo

StringYes

StartTime

ExpiredTime

The timestamp in seconds of when you obtained the key, such as
1580000000 . Passing in this parameter as the signature start
time can avoid signature expiration issues due to time deviation on
the frontend.
expiredTime of the obtained temporary key measured inseconds, i.e., the timeout timestamp, such as 1580000900

getAuthorization Callback function description (Format 2)©2013-2022 Tencent Cloud. All rights reserved.

Page 1057 of 1869

Cloud Infinite

getAuthorization: function(options, callback) { ... }getAuthorization function parameters:
Parameter

Description

Type

options

Parameter object for getting the signature

Object- Method

Method of the current request

String- PathnameRequest path used for signature calculation

String©2013-2022 Tencent Cloud. All rights reserved.

Page 1058 of 1869

Cloud Infinite- Key

ObjectKey (object name) is the unique ID of an object in a bucket. For more
information, see Object Overview.

String- Query

Query parameter in the current request. Format: {key: 'val'}

Object- Headers

Headers in the current request. Format: {key: 'val'}

Objectcallback

Callback after the temporary key is obtained

FunctionOnce the getAuthorization callback function is finished, it returns one of the following:
An Authorization string.
An object whose attributes are listed as follows:
Attribute

Description

Type

Required

Authorization

Calculated signature string

StringYes

StringNosessionToken of the obtained temporary key, which
SecurityToken

corresponds to the x-cos-security-token field in theheaderGetting an authentication credential
There are three ways to get the authentication credentials for your instance by passing in different parameters during
instantiation:
1. During instantiation, pass in your SecretId and SecretKey . Each time a signature is required, it will beinternally calculated by the instance.
2. During instantiation, pass in the getAuthorization callback function. Each time a signature is required, it will
be calculated and returned to the instance through this callback.
3. During instantiation, pass in the getSTS callback. Each time a temporary key is required, it will be returned tothe instance for signature calculation within the instance during each request.

How to use
Callback method
The callback method is used by default in the documentation. Below is the sample code:©2013-2022 Tencent Cloud. All rights reserved.

Page 1059 of 1869

Cloud Infinite// The initialization process and upload parameters are omitted here.
var cos = new COS({ ... });cos.uploadFile({ ... }, function(err, data) {if (err) {console.log('Upload failed', err);} else {console.log('Uploaded successfully', data);}});©2013-2022 Tencent Cloud. All rights reserved.

Page 1060 of 1869

Cloud Infinite

PromiseThe SDK also supports calling through the promise method. For example, the code of the callback method above isequivalent to the following code:// The initialization process and upload parameters are omitted here.
var cos = new COS({ ... });cos.uploadFile({ ... }).then(data => {console.log('Uploaded successfully', data);}).catch(err => {console.log('Upload failed', err);});©2013-2022 Tencent Cloud. All rights reserved.

Page 1061 of 1869

Cloud Infinite

Sync method
The sync method is based on JavaScript's async and await. The code of the callback method above is equivalent to
the following code:

async function upload() {// The initialization process and upload parameters are omitted here.
var cos = new COS({ ... });try {var data = await cos.uploadFile({ ... });©2013-2022 Tencent Cloud. All rights reserved.

Page 1062 of 1869

Cloud Infinite

return { err: null, data: data }} catch (err) {return { err: err, data: null };}}// The returned value of the request can be obtained synchronously. Here is only an
var uploadResult = await upload();if (uploadResult.err) {console.log('Upload failed', uploadResult.err);} else {console.log('Uploaded successfully', uploadResult.data);}
Note:cos.getObjectUrl currently only supports the callback method.

Tips
In most cases, you only need to create a COS SDK instance, and use it directly where SDK methods need to becalled.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1063 of 1869

Cloud Infinite

var cos = new COS({....
});/* Self-encapsulated upload method */function myUpload() {// COS SDK instances do not need to be created in each method// var cos = new COS({//...
// });
cos.putObject({©2013-2022 Tencent Cloud. All rights reserved.

Page 1064 of 1869

Cloud Infinite

....
});
}
/* Self-encapsulated deletion method */function myDelete() {// COS SDK instances do not need to be created in each method// var cos = new COS({//...
// });
cos.deleteObject({
....
});
}
Below are some common APIs. For more detailed initialization methods, see the demo.

Creating a bucket©2013-2022 Tencent Cloud. All rights reserved.

Page 1065 of 1869

Cloud Infinite

cos.putBucket({
Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION'}, function(err, data) {console.log(err || data);});

Querying the bucket list

©2013-2022 Tencent Cloud. All rights reserved.

Page 1066 of 1869

Cloud Infinite

cos.getService(function (err, data) {console.log(data && data.Buckets);});

Uploading an object
This API is used to upload small files. For large files, use the multipart upload API. For more information, see Object
Operations.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1067 of 1869

Cloud Infinite

cos.putObject({
Bucket: 'examplebucket-1250000000', /* Required */Region: 'COS_REGION', /* Required */Key: 'exampleobject', /* Required */StorageClass: 'STANDARD',
Body: fs.createReadStream('./exampleobject'), // Uploading file object
onProgress: function(progressData) {console.log(JSON.stringify(progressData));}}, function(err, data) {console.log(err || data);©2013-2022 Tencent Cloud. All rights reserved.

Page 1068 of 1869

Cloud Infinite});

Querying objects

cos.getBucket({
Bucket: 'examplebucket-1250000000', /* Required */Region: 'COS_REGION', /* Required */Prefix: 'a/', /*Optional*/}, function(err, data) {console.log(err || data.Contents);©2013-2022 Tencent Cloud. All rights reserved.

Page 1069 of 1869

Cloud Infinite});

Downloading an objectcos.getObject({
Bucket: 'examplebucket-1250000000', /* Required */Region: 'COS_REGION', /* Required */Key: 'exampleobject', /* Required */Output: fs.createWriteStream('./exampleobject'),}, function(err, data) {©2013-2022 Tencent Cloud. All rights reserved.

Page 1070 of 1869

Cloud Infinite

console.log(err || data);});

Deleting an object

cos.deleteObject({
Bucket: 'examplebucket-1250000000', /* Required */Region: 'COS_REGION', /* Required */Key: 'exampleobject'/* Required */}, function(err, data) {©2013-2022 Tencent Cloud. All rights reserved.

Page 1071 of 1869

Cloud Infinite

console.log(err || data);});©2013-2022 Tencent Cloud. All rights reserved.

Page 1072 of 1869

Cloud Infinite

Image Processing
Basic Image Processing：

Last updated 2024-03-01 14:25:48

Overview
This document provides an overview of APIs and SDK code samples for basic image processing.
ServiceFeatureDescription

Scaling

Proportional scaling, scaling image to target width and height

Cropping

Basic image

Regular cropping, cropping and scaling, inscribed circle cropping,intelligent face cropping

Rotation

Adaptive rotation, regular rotation

Format conversion

Format conversion, GIF format optimization, progressive display

Quality change

Quality change for JPG and WebP images

Gaussian blurring

Image blurring

Sharpening

Image sharpening

Watermarking

Image watermark, text watermark

processing

Image informationacquisition

Basic information, EXIF information, average hue

Metadata removal

Including EXIF information

Quick thumbnail

Quick image format conversion, scaling, and cropping fortemplatethumbnail generation

Processing Image During Upload
The following example shows how to automatically process an image when you upload it to COS.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1073 of 1869

Cloud Infinite

When the image is uploaded successfully, COS will save both the original and the processed images. You can later
obtain the processing results by using a general download request.

Sample code

const filePath = "temp-file-to-upload" // Local file pathcos.putObject({
Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION',
Key: 'exampleobject',Body: fs.createReadStream(filePath), // Uploaded file object©2013-2022 Tencent Cloud. All rights reserved.

Page 1074 of 1869

Cloud Infinite

onProgress: function(progressData) {console.log(JSON.stringify(progressData));},
Headers: {// Use the `imageMogr2` API to scale the image (by specifying the width of t
'Pic-Operations': '{"is_pic_info": 1, "rules": [{"fileid": "desample_photo.j},}, function(err, data) {console.log(err || data);});

Processing In-Cloud Image
The following example shows how to process an image stored in COS and save the processing result to COS.

Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1075 of 1869

Cloud Infinite

cos.request({
Bucket: config.Bucket,
Region: config.Region,
Key: 'exampleobject',
Method: 'POST',
Action: 'image_process',
Headers: {// Use the `imageMogr2` API to scale the image (by specifying the width of t
'Pic-Operations': '{"is_pic_info": 1, "rules": [{"fileid": "desample_photo.jp},}, function (err, data) {©2013-2022 Tencent Cloud. All rights reserved.

Page 1076 of 1869

Cloud Infinite

console.log(err || data);});

Processing Image During Download
The following example shows how to process an image during download.

Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1077 of 1869

Cloud Infinite

cos.getObject({
Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION',
Key: 'exampleobject',
QueryString: `imageMogr2/thumbnail/200x/`,}, function (err, data) {console.log(err || data);
fs.writeFileSync('filepath', data.Body); // Save the image locally});

Generating Signed URL with Image Processing Parameters
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1078 of 1869

Cloud Infinite// Generate a signed URL (valid for 30 minutes) with image processing parameters.
var url1 = cos.getObjectUrl({
Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION',
Key: 'exampleobject',
Query: {`imageMogr2/thumbnail/200x/`: ''},Expires: 1800,
Sign: true,}, function (err, data) {©2013-2022 Tencent Cloud. All rights reserved.

Page 1079 of 1869

Cloud Infinite

if(data){console.log(data.Url);}});// Generate an unsigned URL with image processing parameters.
var url2 = cos.getObjectUrl({
Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION',
Key: 'exampleobject',
Query: {`imageMogr2/thumbnail/200x/`: ''},Sign: false,}, function (err, data) {if(data){console.log(data.Url);}});©2013-2022 Tencent Cloud. All rights reserved.

Page 1080 of 1869

Cloud Infinite

Blind Watermark：

Last updated 2024-03-01 14:25:48

Overview
This document provides an overview of APIs and SDK code samples for blind watermarking.
For blind watermark APIs, see Blind Watermarking.

Adding Blind Watermark
Feature description
You can add a blind watermark when uploading or downloading an object.
Sample 1: Adding a blind watermark during upload©2013-2022 Tencent Cloud. All rights reserved.

Page 1081 of 1869

Cloud Infinite

const filePath = "temp-file-to-upload" // Local file pathcos.putObject({
Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION',
Key: 'exampleobject',Body: fs.createReadStream(filePath), // Uploaded file object
Headers: {// CI's persistent processing API during upload'Pic-Operations': '{"is_pic_info": 1, "rules": [{"fileid": "desample_photo.j},}, function(err, data) {©2013-2022 Tencent Cloud. All rights reserved.

Page 1082 of 1869

Cloud Infinite

console.log(err || data);});

Sample 2: Adding a blind watermark during downloadcos.getObject({
Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION',
Key: 'exampleobject',
QueryString: 'watermark/3/type/1/image/aHR0cDovL2V4YW1wbGVzLTEyNTEwMDAwMDQucGlj}, function (err, data) {©2013-2022 Tencent Cloud. All rights reserved.

Page 1083 of 1869

Cloud Infinite

console.log(err || data);
fs.writeFileSync('filepath', data.Body);// Save the image locally});©2013-2022 Tencent Cloud. All rights reserved.

Page 1084 of 1869

Cloud Infinite

Media Processing
Media Bucket APIs：

Last updated 2024-03-01 14:25:48

Overview
This document provides an overview of APIs and SDK code samples for media buckets.
API
DescribeMediaBuckets

Operation

Description

Querying media processing activation

Queries buckets with media processing

statusenabledQuerying Media Processing Activation Status
Feature description
This API is used to query buckets with media processing enabled.
Note:
The COS Node.js SDK version must be at least v2.11.2.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1085 of 1869

Cloud Infinite

var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket (required) */Region: 'COS_REGION', /* Bucket region (required) */};var host = 'ci.' + config.Region + '.myqcloud.com';
var url = 'https://' + host + '/mediabucket';cos.request({
Bucket: config.Bucket,
Region: config.Region,
Method: 'GET',©2013-2022 Tencent Cloud. All rights reserved.

Page 1086 of 1869

Cloud Infinite

Key: 'mediabucket', /** Fixed value (required) */Url: url,
Query: {pageNumber: '1', /** Page number (optional) */pageSize: '10', /** Number of entries per page (optional) */// regions: 'ap-chengdu', /** Region (optional), such as 'ap-beijing'. To s// bucketNames: 'test-1250000000', /** Bucket name (optional), such as 'tes// bucketName: 'test', /** Bucket name prefix for prefix search (optional),}}, function (err, data) {console.log(err || data);});

Parameter description
Parameter

Description

Type

Required

BucketBucket name in the format of BucketName-APPID .

StringYes

RegionBucket region. For the enumerated values, see Regions andAccess Endpoints.

StringYes

Key

Fixed value: mediabucket.

StringYes

PageNumber

Page number.

StringNo

PageSize

Number of entries per page.

StringNo

String

No

Region information, such as ap-shanghai and apRegions

beijing . To specify multiple regions, separate them withcommas. For more information, see Regions and Domain Names.

BucketNames

Bucket name. To specify multiple bucket names, separate themwith commas. Exact search is supported.

StringNo

BucketName

Bucket name prefix for prefix search.

StringNo

Callback function description©2013-2022 Tencent Cloud. All rights reserved.

Page 1087 of 1869

Cloud Infinite

function(err, data) { ... }Parameter

Description

Type

The object returned when an error (network error or service error) occurs. If
err

the request is successful, this parameter is empty. For more information,
see Error Codes.

Object- statusCode

Returned HTTP status code, such as 200 , 403 , and 404 .

Number- headers

Returned headers.

Object©2013-2022 Tencent Cloud. All rights reserved.

Page 1088 of 1869

Cloud Infinitedata

The object returned when the request is successful. If an error occurs withthe request, this parameter is empty.

Object- statusCode

Returned HTTP status code, such as 200 , 403 , and 404 .

Number- headers

Returned headers.

Object- Response

Response result.

Object- - RequestId

Unique ID of the request.

String- - TotalCount

Total number of media buckets.

String- - PageNumber- - PageSize--

Current page number, which is the same as pageNumber in therequest.
Number of entries per page, which is the same as pageSize in therequest.

StringStringMedia bucket list.

Object- - - BucketId

Bucket ID.

String- - - Name

Bucket name, which is the same as BucketId .

String- - - Region

Region.

String- - - CreateTime

Creation time.

StringMediaBucketList©2013-2022 Tencent Cloud. All rights reserved.

Page 1089 of 1869

Cloud Infinite

Media Information APIs：

Last updated 2024-03-01 14:25:48

Overview
This document provides an overview of APIs and SDK code samples for media information.
Note:
The COS Node.js SDK version must be at least v2.11.2.
API

Operation

Description

GetMediaInfo

Querying file information

Queries media file information

Querying File Information
Feature description
This API is used to query the information of a media file.
Note:
Before using this API, make sure that the media processing feature has been enabled in the data processing sectionin the console; otherwise, the error media bucket unbinded, bucket's host is unavailable will bereported.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1090 of 1869

Cloud Infinite

var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket (required) */Region: 'COS_REGION', /* Bucket region (required) */};cos.request({
Bucket: config.Bucket,
Region: config.Region,
Method: 'GET',
Key: 'test.mp4', /* Media file in bucket (required) */Query: {©2013-2022 Tencent Cloud. All rights reserved.

Page 1091 of 1869

Cloud Infinite'ci-process': 'videoinfo' /** Fixed value (required) */}}, function (err, data) {console.log(err || data);});

Parameter description
Parameter

Description

Type

Required

BucketBucket name in the format of BucketName-APPID .

StringYes

StringYes

RegionBucket region. For the enumerated values, see Regions and AccessEndpoints.

Key

Fixed value: mediabucket.

StringYes

ci-process

Operation type, which is fixed at videoinfo .

StringYes

Callback function description©2013-2022 Tencent Cloud. All rights reserved.

Page 1092 of 1869

Cloud Infinite

function(err, data) { ... }Parameter

Description

Type

The object returned when an error (network error or service error)
err

occurs. If the request is successful, this parameter is empty. For more
information, see Error Codes.

Object- statusCode

Returned HTTP status code, such as 200 , 403 , and 404 .

Number- headers

Returned headers.

Object©2013-2022 Tencent Cloud. All rights reserved.

Page 1093 of 1869

Cloud Infinitedata

The object returned when the request is successful. If an error occurs
with the request, this parameter is empty.

Object- statusCode

Returned HTTP status code, such as 200 , 403 , and 404 .

Number- headers

Returned headers.

Object- RequestId

Unique ID of the request.

String- Response

Response result.

Object- - MediaInfo

Media details.

Object- - - Stream

Stream information.

Object- - - - Video

Video information.

Container- - - - - Index

Stream number.

Number- - - - - CodecName

Codec format name.

String----CodecLongName

Detailed name of the codec format

String----CodecTimeBase

Codec timebase.

String----CodecTagString

Codec tag name.

String- - - - - CodecTag

Codec tag.

String- - - - - Profile

Video codec profile.

String- - - - - Height

Video height in px.

Number- - - - - Width

Video width in px.

Number- - - - - HasBFrame

Whether B-frames exist. 1: yes; 0: no.

Number- - - - - RefFrames

Number of reference frames for video codec.

Number- - - - - Sar

Sample aspect ratio.

String- - - - - Dar

Display aspect ratio.

String- - - - - PixFormat

Pixel format.

String- - - - - FieldOrder

Field order.

String©2013-2022 Tencent Cloud. All rights reserved.

Page 1094 of 1869

Cloud Infinite- - - - - Level

Video codec level.

Number- - - - - Fps

Video frame rate.

Number- - - - - AvgFps

Average frame rate.

String- - - - - Timebase

Timebase.

String- - - - - StartTime

Video start time in seconds.

Number- - - - - Duration

Video duration in seconds.

Number- - - - - Bitrate

Bitrate in Kbps.

Number- - - - - NumFrames

Total number of frames.

Number- - - - - Language

Language.

String- - - - Audio

Audio information.

Container- - - - - Index

Stream number.

Number- - - - - CodecName

Codec format name.

String----CodecLongName

Detailed name of the codec format.

String----CodecTimeBase

Codec timebase.

String----CodecTagString

Codec tag name.

String- - - - - CodecTag

Codec tag.

String- - - - - SampleFmt

Sample format.

String- - - - - SampleRate

Sample rate.

Number- - - - - Channel

Number of channels.

Number----ChannelLayout

Channel layout.

String- - - - - Timebase

Timebase.

String- - - - - StartTime

Audio start time in seconds.

Number- - - - - Duration

Audio duration in seconds.

Number©2013-2022 Tencent Cloud. All rights reserved.

Page 1095 of 1869

Cloud Infinite- - - - - Bitrate

Bitrate in Kbps.

Number- - - - - Language

Language.

String- - - - Subtitle

Subtitles information.

Container- - - - - Index

Stream number.

Number- - - - - Language

Language. und indicates no query result.

String- - - Format

Format information.

Object- - - - NumStream

Number of streams (including videos, audios, and subtitles).

Number- - - - NumProgram

Number of programs.

Number- - - - FormatName

Container format name.

String---FormatLongName

Detailed name of the container format.

String- - - - StartTime

Start time in seconds.

Number- - - - Duration

Duration in seconds.

Number- - - - Bitrate

Bitrate in Kbps.

Number- - - - Size

Size in bytes.

Number©2013-2022 Tencent Cloud. All rights reserved.

Page 1096 of 1869

Cloud Infinite

Media Screenshot APIs：

Last updated 2024-03-01 14:25:48

Overview
This document provides an overview of APIs and SDK code samples for media screenshot.
Note:
The COS Node.js SDK version must be at least v2.11.2.
API

Operation

Description

GetSnapshot

Querying screenshot

Query the screenshot of media file at some time point

Querying Screenshot
Feature description
This API is used to query the screenshot of a media file at some time point.
Note:
Before using this API, make sure that the media processing feature has been enabled in the data processing sectionin the console; otherwise, the error media bucket unbinded, bucket's host is unavailable will bereported.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1097 of 1869

Cloud Infinite

var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket (required) */Region: 'COS_REGION', /* Bucket region (required) */};cos.request({
Bucket: config.Bucket,
Region: config.Region,
Method: 'GET',
Key: 'test.mp4', /* Media file in bucket (required) */Query: {©2013-2022 Tencent Cloud. All rights reserved.

Page 1098 of 1869

Cloud Infinite'ci-process': 'snapshot', /** Fixed value (required) */time: 1, /** Screenshot time point in seconds (required) */// width: 0, /** Screenshot width (optional) */// height: 0, /** Screenshot height (optional) */// format: 'jpg', /** Screenshot format (optional). Valid values: jpg; png.
// rotate: 'auto', /** Image rotation method (optional). Default value: aut// mode: 'exactframe', /** Frame capturing method (optional). Default value},
RawBody: true,},
function(err, data){
console.log(err || data);});

Parameter description
Parameter

Description

Type

Required

BucketBucket name in the format of BucketName-APPID .

StringYes

StringYes

StringYes

RegionKey

Bucket region. For the enumerated values, see Regions andAccess Endpoints.
Object key (object name), which is the unique identifier of theobject in the bucket. For more information, see Object Overview.

ci-process

Operation type, which is fixed at snapshot .

StringYes

time

Screenshot time point in seconds.

NumberYes

width

Screenshot width. Default value: 0.

Number

No

NumberNo

StringNo

StringNo

StringNo

Screenshot height. Default value: 0. If width and heightheightare both 0 , the width and height of the video are used. If one ofthem is 0 , the other value is used to automatically adapt to the
aspect ratio of the video.

formatScreenshot format. Valid values: jpg; png. Default value: jpg.
Image rotation method. auto: Rotate automatically according torotatemode

the video rotation information. off: Do not rotate. Default value:
auto.
Frame capturing method. keyframe: Capture the last keyframe
before the specified time point. exactframe: Capture the frame at a
specified time point. Default value: exactframe.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1099 of 1869

Cloud Infinite

Callback function descriptionfunction(err, data) { ... }Parameter

Description

Type

The object returned when an error (network error or service error) occurs.
err

If the request is successful, this parameter is empty. For more
information, see Error Codes.

Object- statusCode

Returned HTTP status code, such as 200 , 403 , and 404 .

Number©2013-2022 Tencent Cloud. All rights reserved.

Page 1100 of 1869

Cloud Infinite- headers

Returned headers.

Objectdata

The object returned when the request is successful. If an error occurs
with the request, this parameter is empty.

Object- statusCode

Returned HTTP status code, such as 200 , 403 , and 404 .

Number- headers

Returned headers.

Object- RequestId

Unique ID of the request.

String- BodyReturned file content, which is in string format by default.

String©2013-2022 Tencent Cloud. All rights reserved.

Page 1101 of 1869

Cloud Infinite

PHP SDK
Getting Started：

Last updated 2024-03-01 14:43:58

Download and Installation
Relevant resources
Download the source code for the COS XML PHP SDK here.
Download the XML PHP SDK here.
Download the PHP demo here.
For the complete sample code, see SDK Sample Code.
For the SDK changelog, see Changelog.
For SDK FAQs, see PHP SDK FAQs.
Note:
If you encounter errors such as non-existent functions or methods when using the XML version of the SDK, please
update the SDK to the latest version and try again.
Environmental dependencies
PHP 5.6+
You can run the php -v command to view the current PHP version.
Note:
If your PHP version is 5.3 or later and earlier than 5.6, please use v1.3.
cURL extension
XML extension
DOM extension
MBstring extension
JSON extension
You can run the php -m command to check whether the preceding extensions have been installed properly.
On Ubuntu, you can install PHP's extensions using the apt-get package manager with the following command:©2013-2022 Tencent Cloud. All rights reserved.

Page 1102 of 1869

Cloud Infinite

sudo apt-get install php-curl php-xml php-dom php-mbstring php-json
On CentOS, you can install PHP's cURL extension using the yum package manager.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1103 of 1869

Cloud Infinite

sudo yum install php-curl php-xml php-dom php-mbstring php-json

Installing SDK
You can install the SDK using Composer, Phar, or the source code.
Composer
It is recommended to install cos-php-sdk-v5 with Composer, a PHP dependency manager that allows you to declarethe dependencies necessary for your project and then automatically installs them into your project.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1104 of 1869

Cloud Infinite

Note:
You can find more information such as how to install Composer, how to configure auto-load, and other best practices
for defining dependencies at the Composer website.
Directions
1. Open the terminal.
2. Run the following command to download Composer:

curl -sS https://getcomposer.org/installer | php
3. Create a file named composer.json with the following content:©2013-2022 Tencent Cloud. All rights reserved.

Page 1105 of 1869

Cloud Infinite{"require": {"qcloud/cos-sdk-v5": ">=2.0"}}
4. Run the following command to install the SDK with Composer:©2013-2022 Tencent Cloud. All rights reserved.

Page 1106 of 1869

Cloud Infinite

php composer.phar installThis command will create a vendor folder in the current directory. The folder will contain the SDK's dependent
library and an autoload.php script file for future calls in your project.
Note:
Composer will download Guzzle 6 or Guzzle 7 according to the PHP version. Guzzle 7 supports the Laravel 8
framework. If the PHP version is or later than 7.2.5, Guzzle 7 will be downloaded by default. Otherwise, Guzzle 6 will
be downloaded.
5. Run the autoloader script to call cos-php-sdk-v5 and import the autoload.php file into your code.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1107 of 1869

Cloud Infinite

require '/path/to/sdk/vendor/autoload.php';
Note:
After running the Composer installation command, you need to change the path here to the path to the
autoload.php file. Otherwise, the corresponding method cannot be called. For example, if your installation pathis /Users/username/project , set the referenced path in the project to/Users/username/project/vendor/autoload.php .
Now, you can use COS XML SDK for PHP in your project.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1108 of 1869

Cloud Infinite

Phar
Install the SDK using the Phar method as instructed below:
1. Download the phar file here.
Note:
If your PHP version is 5.6 or later and earlier than 7.2.5, download cos-sdk-v5-6.phar to use Guzzle 6.
If your PHP version is 7.2.5 or later, download cos-sdk-v5-7.phar to use Guzzle 7.
2. Import the phar file into your code.

require'/path/to/cos-sdk-v5-x.phar';©2013-2022 Tencent Cloud. All rights reserved.

Page 1109 of 1869

Cloud Infinite

Source code
Install the SDK using the source code as instructed below:
1. Download the cos-sdk-v5.tar.gz compressed file on the SDK releases page.
Note:
If your PHP version is 5.6 or later and earlier than 7.2.5, download cos-sdk-v5-6.tar.gz to use Guzzle 6.
If your PHP version is 7.2.5 or later, download cos-sdk-v5-7.tar.gz to use Guzzle 7.
2. Decompress the file and run the autoload.php script to load the SDK and import the autoload.php file
into your code:©2013-2022 Tencent Cloud. All rights reserved.

Page 1110 of 1869

Cloud Infinite

require '/path/to/sdk/vendor/autoload.php';
Note:
Source code is the default GitHub-compressed code package, which does not include the vendor directory.
Note that you should download the release package ( cos-sdk-v5-x.tar.gz ) rather than the Source package,and should not clone the entire repository (otherwise, index.php and the vendor package will be missing).

Getting Started
The following describes how to use the PHP SDK of COS to perform basic operations, such as initializing the client,creating a bucket, querying the bucket list, uploading an object, querying the object list, downloading an object, anddeleting an object. For more information about the parameters involved in the samples, see Bucket Operations andObject Operations.

Initialization
Note:
We recommend you use a sub-account key and environment variables to call the SDK for security purposes. Whenauthorizing a sub-account, follow the Notes on Principle of Least Privilege to avoid leaking resources besides yourbuckets and objects.
If you must use a permanent key, we recommend you follow the Notes on Principle of Least Privilege to limit the scopeof permission on the permanent key.
If you initialize a client with a temporary key, create an instance in the following way.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1111 of 1869

Cloud Infinite$tmpSecretId = "TmpSecretId"; //SecretId of a temporary key. For more information a$tmpSecretKey = "TmpSecretKey"; //SecretKey of a temporary key. For more informatio$tmpToken = "TmpToken"; //Token of a temporary key. For more information about how$region = "ap-beijing"; //Replace it with the actual `region`, which can be viewed$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', //Protocol header, which is http by default'credentials'=> array('secretId' => $tmpSecretId,'secretKey' => $tmpSecretKey,©2013-2022 Tencent Cloud. All rights reserved.

Page 1112 of 1869

Cloud Infinite'token' => $tmpToken)));If you use a permanent key to initialize a COSClient , you need to get your SecretId and SecretKey on
the API Key Management page in the CAM console. A permanent key is suitable for most application scenarios.

// You can log in to the CAM console to view and manage the `SecretId` and `SecretK$secretId = getenv('COS_SECRET_ID'); // User `SecretId`. We recommend you use a sub$secretKey = getenv('COS_SECRET_KEY'); // User `SecretKey`. We recommend you use a$region = "ap-beijing"; //User `region`, which can be viewed in the console at http$cosClient = new Qcloud\\Cos\\Client(array(©2013-2022 Tencent Cloud. All rights reserved.

Page 1113 of 1869

Cloud Infinite'region' => $region,'schema' => 'https', // Protocol, which is `http` by default'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));Note:
If no HTTPS certificate is configured, you need to delete the schema parameter or enter 'schema' =>'http' . If you enter https , a certificate problem will be reported. If you want to configure an HTTPS certificate,see PHP SDK FAQs.

Creating a bucket©2013-2022 Tencent Cloud. All rights reserved.

Page 1114 of 1869

Cloud Infinite

try {$bucket = "examplebucket-1250000000"; // Bucket name in the format of BucketNam$result = $cosClient->createBucket(array('Bucket' => $bucket));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}©2013-2022 Tencent Cloud. All rights reserved.

Page 1115 of 1869

Cloud Infinite

Querying the bucket list

try {// Request succeeded$result = $cosClient->listBuckets();
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}©2013-2022 Tencent Cloud. All rights reserved.

Page 1116 of 1869

Cloud Infinite

Uploading an object
Note:
Upload a file (up to 5 GB) using the putObject API.
Upload a file using the Upload API. The Upload API is a composition API that uses simple upload for small files anduses multipart upload for large files.
For parameter descriptions, see Object Operations.

# Upload a file## putObject (an API that can upload files of up to 5 GB)### Uploading strings in memory©2013-2022 Tencent Cloud. All rights reserved.

Page 1117 of 1869

Cloud Infinite

try {$bucket = "examplebucket-1250000000"; // Bucket name in the format of BucketNam$key = "exampleobject"; // Object key, the unique identifier of the object in t
$result = $cosClient->putObject(array('Bucket' => $bucket,'Key' => $key,'Body' => 'Hello World!'));
print_r($result);} catch (\\Exception $e) {echo "$e\\n";}### Uploading a file stream
try {$bucket = "examplebucket-1250000000"; // Bucket name in the format of BucketNam$key = "exampleobject"; // Object key, the unique identifier of the object in t
$srcPath = "path/to/localFile";// Absolute path to local file
$file = fopen($srcPath, "rb");
if ($file) {$result = $cosClient->putObject(array('Bucket' => $bucket,'Key' => $key,'Body' => $file));print_r($result);}} catch (\\Exception $e) {echo "$e\\n";}## Upload (advanced upload API, which can upload files of up to 50 TB with multipar### Uploading strings in memory
try {$bucket = "examplebucket-1250000000"; // Bucket name in the format of BucketNam$key = "exampleobject"; // Object key, the unique identifier of the object in t
$result = $cosClient->Upload($bucket = $bucket,$key = $key,$body = 'Hello World!');print_r($result);} catch (\\Exception $e) {echo "$e\\n";}### Uploading a file stream
try {$bucket = "examplebucket-1250000000"; // Bucket name in the format of BucketNam$key = "exampleobject"; // Object key, the unique identifier of the object in t

©2013-2022 Tencent Cloud. All rights reserved.

Page 1118 of 1869

Cloud Infinite$srcPath = "path/to/localFile";// Absolute path to local file
$file = fopen($srcPath, 'rb');
if ($file) {$result = $cosClient->Upload($bucket = $bucket,$key = $key,$body = $file);}
print_r($result);} catch (\\Exception $e) {echo "$e\\n";}Querying objects©2013-2022 Tencent Cloud. All rights reserved.

Page 1119 of 1869

Cloud Infinite

try {$bucket = "examplebucket-1250000000"; // Bucket name in the format of BucketNam$result = $cosClient->listObjects(array('Bucket' => $bucket));// Request succeeded
if (isset($result['Contents'])) {foreach ($result['Contents'] as $rt) {print_r($rt);}}©2013-2022 Tencent Cloud. All rights reserved.

Page 1120 of 1869

Cloud Infinite} catch (\\Exception $e) {// Request failedecho($e);}
A single call to the listObjects API can query up to 1,000 objects. If you want to query all objects, you need tocall it repeatedly.

try {$bucket = "examplebucket-1250000000"; // Bucket name in the format of BucketNam$prefix = ''; // Prefix of the objects to be listed©2013-2022 Tencent Cloud. All rights reserved.

Page 1121 of 1869

Cloud Infinite$marker = ''; // End marker in the last list
while (true) {$result = $cosClient->listObjects(array('Bucket' => $bucket,'Marker' => $marker,'MaxKeys' => 1000 // Set the maximum number of entries to be listed in));
if (isset($result['Contents'])) {foreach ($result['Contents'] as $rt) {// Print keyecho($rt['Key'] . "\\n");}}$marker = $result['NextMarker']; // Set a new end marker
if (!$result['IsTruncated']) {break; // Determine whether the query is complete}}} catch (\\Exception $e) {echo($e);}

Downloading an object
Download a file using the getObject API.
Get the file download URL using the getObjectUrl API.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1122 of 1869

Cloud Infinite# Downloading a file## getObject (download file)### Download to memory
try {$bucket = "examplebucket-1250000000"; // Bucket in the format of BucketName-APP$key = "exampleobject"; // Object key, the unique identifier of the object in$result = $cosClient->getObject(array('Bucket' => $bucket,'Key' => $key));// Request succeededecho($result['Body']);©2013-2022 Tencent Cloud. All rights reserved.

Page 1123 of 1869

Cloud Infinite} catch (\\Exception $e) {// Request failed
echo "$e\\n";}### Download to the local file system
try {$bucket = "examplebucket-1250000000"; // Bucket in the format of BucketName-APP$key = "exampleobject"; // Object key, the unique identifier of the object in$localPath = @"path/to/localFile";// Download to a specific local path$result = $cosClient->getObject(array('Bucket' => $bucket,'Key' => $key,'SaveAs' => $localPath));} catch (\\Exception $e) {// Request failed
echo "$e\\n";}### Specifying the download range/** Range field is in the format of 'bytes=a-b'*/
try {$bucket = "examplebucket-1250000000"; // Bucket in the format of BucketName-APP$key = "exampleobject"; // Object key, the unique identifier of the object in$localPath = @"path/to/localFile";// Download to a specific local path$result = $cosClient->getObject(array('Bucket' => $bucket,'Key' => $key,'Range' => 'bytes=0-10','SaveAs' => $localPath));} catch (\\Exception $e) {// Request failed
echo "$e\\n";}## getObjectUrl (get the file URL)
try {$bucket = "examplebucket-1250000000"; // Bucket in the format of BucketName-APP$key = "exampleobject"; // Object key, the unique identifier of the object in$signedUrl = $cosClient->getObjectUrl($bucket, $key, '+10 minutes');// Request succeeded
echo $signedUrl;} catch (\\Exception $e) {// Request failed
print_r($e);©2013-2022 Tencent Cloud. All rights reserved.

Page 1124 of 1869

Cloud Infinite}

Deleting an object# Delete an object## deleteObject
try {$bucket = "examplebucket-1250000000"; // Bucket in the format of BucketName-APP$key = "exampleobject"; // Object key, the unique identifier of the object in$result = $cosClient->deleteObject(array(©2013-2022 Tencent Cloud. All rights reserved.

Page 1125 of 1869

Cloud Infinite'Bucket' => $bucket,'Key' => $key,'VersionId' => 'string'));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}# Delete multiple objects## deleteObjects
try {$bucket = "examplebucket-1250000000"; // Bucket in the format of BucketName-APP$key1 = "exampleobject1"; // Object key, the unique identifier of the object i$key2 = "exampleobject2"; // Object key, the unique identifier of the object i$result = $cosClient->deleteObjects(array('Bucket' => $bucket,'Objects' => array(
array('Key' => $key1,),
array('Key' => $key2,
),
//...
),
));
// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}©2013-2022 Tencent Cloud. All rights reserved.

Page 1126 of 1869

Cloud Infinite

Image Processing
Basic Image Processing：

Last updated 2024-03-01 14:43:58

Overview
COS has integrated Cloud Infinite (CI), a one-stop professional multimedia solution that offers the image processing
features outlined below. For more information, see Image Processing Overview.
FeatureDescription

Scaling

Scales an image proportionally or to the target width and height.

Cropping

Performs regular cropping, cropping and scaling, cropping to circle, or smart
face cropping.

Rotation

Performs adaptive rotation or regular rotation.

Format conversion

Converts the format of an image, optimizes the GIF format, and performs
progressive display.

Quality change

Changes the quality of images in JPG and WEBP formats.

Gaussian blurring

Blurs an image by a Gaussian function.

Brightness

Adjusts the image brightness.

Contrast

Adjusts the image contrast.

Sharpening

Sharpens an image.

Grayscale image

Sets an image to a grayscale image.

Image watermark

Processes an image watermark.

Text watermark

Processes a text watermark.

Basic image informationacquisition

Queries the basic information of an image, such as format, width, and height.

Image EXIF data acquisition

Gets the EXIF data of an image.

Image average hue
acquisition

Gets the average hue of an image.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1127 of 1869

Cloud Infinite

Metadata removal
Quick thumbnail template

Removes the image metadata, including the EXIF data.
Performs quick format conversion, scaling, and cropping to generate
thumbnails.

Image size limiting

Limits the size of an output image, such as a scaled or compressed image.

Pipeline operator

Performs multiple operations on images in sequence

ScalingFeature description
CI uses the imageMogr2 API to scale images. The input image cannot be larger than 32 MB, with its width and height
not exceeding 30,000 pixels, and the total number of pixels not exceeding 250 million. The width and height of theoutput image cannot exceed 9,999 pixels. For an input animated image, the total number of pixels (Width x Height x
Number of frames) cannot exceed 250 million pixels.
Sample codes©2013-2022 Tencent Cloud. All rights reserved.

Page 1128 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1129 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// Image processing - scaling. For more information, visit https://cloud.tencen$imageRule = new Qcloud\\Cos\\ImageParamTemplate\\ImageMogrTemplate();$imageRule->thumbnailByScale(50); // /thumbnail/!<Scale>p$imageRule->thumbnailByWidthScale(50); // /thumbnail/!<Scale>px$imageRule->thumbnailByHeightScale(50); // /thumbnail/!x<Scale>p$imageRule->thumbnailByWidth(60); // /thumbnail/<Width>x$imageRule->thumbnailByHeight(60); // /thumbnail/x<Height>$imageRule->thumbnailByMaxWH(100, 100); // /thumbnail/<Width>x<Height>$imageRule->thumbnailByMinWH(30, 30); // /thumbnail/!<Width>x<Height>r$imageRule->thumbnailByWH(50, 50); // /thumbnail/<Width>x<Height>!
$imageRule->thumbnailByPixel(10000); // /thumbnail/<Area>@$imageRule->thumbnailEqualRatioReduceByWH(300, 300); // /thumbnail/<Width>x<Hei$imageRule->thumbnailEqualRatioEnlargeByWH(300, 300); // /thumbnail/<Width>x<He$imageRule->pad(1); // /pad/1$imageRule->color('#3D3D3D'); // /color/IzNEM0QzRA$imageRule->ignoreError(); // /ignore-error/1$picOperations = new Qcloud\\Cos\\ImageParamTemplate\\PicOperationsTransformati$picOperations->setIsPicInfo(1); // is_pic_info$picOperations->addRule($imageRule, "output.png"); // rules////// -------------------- 1. Processing during download -------------------- //$downloadUrl = $cosClient->getObjectUrl('examplebucket-1250000000', 'xxx.jpg'$downloadUrl = 'https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/$rule = $imageRule->queryString();echo "{$downloadUrl}?{$rule}";echo "{$downloadUrl}&{$rule}"; // The URL of an image with a signature is con// -------------------- 1. Processing during download -------------------- //// -------------------- 2. Processing during upload -------------------- //$result = $cosClient->putObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'object.jpg','Body' => fopen('/tmp/local.jpg', 'rb'), // Local file
'PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 2. Processing during upload -------------------- //// -------------------- 3. Processing in-cloud data -------------------- //$result = $cosClient->ImageProcess(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu©2013-2022 Tencent Cloud. All rights reserved.

Page 1130 of 1869

Cloud Infinite'Key' => 'test.png','PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 3. Processing in-cloud data -------------------- //} catch (\\Exception $e) {// Request failedecho($e);}

Parameters
Operation: thumbnail
Parameter

Description

ObjectKey

Object name, such as folder/sample.jpg .

/thumbnail/!<Scale>p

Scales an image to Scale% of its original width and height.

/thumbnail/!<Scale>px/thumbnail/!x<Scale>p/thumbnail/<Width>x/thumbnail/x<Height>/thumbnail/<Width>x<Height>

Scales an image to Scale% of its original width while keeping the heightunchanged.
Scales an image to Scale% of its original height while keeping the width
unchanged.
Specifies the target image width as Width , with the height proportionallyscaled.
Specifies the target image height as Height , with the width proportionallyscaled.
Specifies the maximum width and height of a thumbnail as Width andHeight respectively for proportional scaling.
Specifies the maximum width and height of a thumbnail as Width andHeight respectively for proportional scaling down. The smaller value/thumbnail/<Width>x<Height>>

between the width scale ratio and height scale ratio will be used as the scaleratio. If both the output width and height are greater than the input width andheight, the image will not be scaled.
Specifies the maximum width and height of a thumbnail as Width andHeight respectively for proportional scaling up. The smaller value/thumbnail/<Width>x<Height><

between the width scale ratio and height scale ratio will be used as the scaleratio. If both the output width and height are less than the input width andheight, the image will not be scaled.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1131 of 1869

Cloud Infinite/thumbnail/!
<Width>x<Height>r/thumbnail/<Width>x<Height>!

/thumbnail/<Area>@

Specifies the minimum width and height of a thumbnail as Width andHeight respectively for proportional scaling.
Forces image scaling with the specified Width and Height , which
may cause deformation of the target image.
Proportionally scales an image so that the total number of its pixels does notexceed Area .
Pads the blank area with the color specified by color after the input/pad/

image is scaled as large as possible in a rectangle with the specified
Width and Height , with the image centered. Valid values: 0 (not topad), 1 (to pad).
Fill color. The value must be in hexadecimal format, such as #FF0000 . For/color/format conversion, see RGB Color Codes Chart. The value must be URLsafe Base64-encoded as described in FAQs. Default value: #FFFFFF(white).

/ignore-error/1

If this parameter is carried and the image fails to be processed because theimage is too large or a parameter value exceeds the limit, the input image will
be returned with no error reported.

Cropping
Feature description
CI uses the imageMogr2 API to crop images, such as regular cropping, scaling and cropping, inscribed circle
cropping, rounded corner cropping, and smart cropping.
Sample codes©2013-2022 Tencent Cloud. All rights reserved.

Page 1132 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1133 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// Image processing - cropping. For more information, visit https://cloud.tence$imageRule = new Qcloud\\Cos\\ImageParamTemplate\\ImageMogrTemplate();$imageRule->cut(400, 400, 100, 100); // Parameters for regular cropping /cut/<w$imageRule->cropByWidth(400, 'center'); // Parameters for scaling and cropping$imageRule->cropByHeight(400, 'center'); // Parameters for scaling and cropping$imageRule->cropByWH(400, 400, 'center'); // Parameters for scaling and croppin$imageRule->iradius(30); // Parameters for cropping to circle /iradius/<radius>$imageRule->rradius(30); // Parameters for rounded corner cropping /rradius/<ra$imageRule->scrop(30, 30); // Parameters for smart face cropping /scrop/<Width>$imageRule->ignoreError(); // /ignore-error/1$picOperations = new Qcloud\\Cos\\ImageParamTemplate\\PicOperationsTransformati$picOperations->setIsPicInfo(1); // is_pic_info$picOperations->addRule($imageRule, "output.png"); // rules////// -------------------- 1. Processing during download -------------------- //$downloadUrl = $cosClient->getObjectUrl('examplebucket-1250000000', 'xxx.jpg'$downloadUrl = 'https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/$rule = $imageRule->queryString();echo "{$downloadUrl}?{$rule}";echo "{$downloadUrl}&{$rule}"; // The URL of an image with a signature is con// -------------------- 1. Processing during download -------------------- //// -------------------- 2. Processing during upload -------------------- //$result = $cosClient->putObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'object.jpg','Body' => fopen('/tmp/local.jpg', 'rb'), // Local file
'PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 2. Processing during upload -------------------- //// -------------------- 3. Processing in-cloud data -------------------- //$result = $cosClient->ImageProcess(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'test.png','PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 3. Processing in-cloud data -------------------- //©2013-2022 Tencent Cloud. All rights reserved.

Page 1134 of 1869

Cloud Infinite} catch (\\Exception $e) {// Request failedecho($e);}

Parameters
Parameter

Description/ignore-error/1

If this parameter is carried and the image failed to be processed because the image sizeor the parameter value is too large, the input image will be returned with no error reported.

Parameters for regular cropping

Operation: cut
Parameter

Description<width>Width of the output image<height>

Height of the output image<dx>

Horizontal offset relative to the top-left vertex<dy>Vertical offset relative to the top-left vertex

Note:
The values should be greater than 0 and smaller than the width/height of the input image.
Parameters for scaling and cropping

Operation: cropParameter

Description/crop/<Width>x

Width of the output image with the height unchanged. The value must be greaterthan 0 and smaller than the width of the input image.

/crop/x<Height>/crop/<Width>x<Height>

Height of the output image with the width unchanged. The value must be greaterthan 0 and smaller than the height of the input image.
Width and height of the output image. The values of width and height should begreater than 0 and smaller than those of the input image, respectively.

When performing scaling and cropping, you can also use the gravity parameter to specify the start position of
the operation. For more information, see Cropping.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1135 of 1869

Cloud Infinite

Parameters for cropping to circle

Operation: iradiusParameter

Description
Crops to a circle. radius specifies the radius of the inscribed circle, which should be/iradius/<radius>

an integer greater than zero and less than half of the shorter side of the input image. The
center of the inscribed circle is the center of the image. This operation is not supported for
GIF images.

Parameters for rounded corner cropping

Operation: rradiusParameter

Description
Crops with round corners. radius specifies the radius of the rounded corner of the/rradius/<radius>

image, which should be an integer greater than zero and less than half of the shorter sideof the input image. The two sides of the image are the tangent lines of the rounded corner.
This operation is not supported for GIF images.

Parameters for smart face cropping

Operation: scrop
Parameter

Description
Scales and crops an image based on the face position in the image. The width/scrop/<Width>x<Height>

and height of the target image are specified by Width and Heightrespectively.

Rotating
Feature description
CI uses the imageMogr2 API to rotate an image by a specified angle or automatically.
Sample codes©2013-2022 Tencent Cloud. All rights reserved.

Page 1136 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1137 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// Image processing - rotation. For more information, visit https://cloud.tence$imageRule = new Qcloud\\Cos\\ImageParamTemplate\\ImageMogrTemplate();$imageRule->rotate(90); // /rotate/<rotateDegree>$imageRule->autoOrient(); // /auto-orient$imageRule->flip('vertical'); // /flip/<flip>$imageRule->ignoreError(); // /ignore-error/1$picOperations = new Qcloud\\Cos\\ImageParamTemplate\\PicOperationsTransformati$picOperations->setIsPicInfo(1); // is_pic_info$picOperations->addRule($imageRule, "output.png"); // rules// -------------------- 1. Processing during download -------------------- //////$downloadUrl = $cosClient->getObjectUrl('examplebucket-1250000000', 'xxx.jpg'$downloadUrl = 'https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/$rule = $imageRule->queryString();echo "{$downloadUrl}?{$rule}";echo "{$downloadUrl}&{$rule}"; // The URL of an image with a signature is con// -------------------- 1. Processing during download -------------------- //// -------------------- 2. Processing during upload -------------------- //$result = $cosClient->putObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'object.jpg','Body' => fopen('/tmp/local.jpg', 'rb'), // Local file
'PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 2. Processing during upload -------------------- //// -------------------- 3. Processing in-cloud data -------------------- //$result = $cosClient->ImageProcess(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'test.png','PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 3. Processing in-cloud data -------------------- //} catch (\\Exception $e) {// Request failedecho($e);}©2013-2022 Tencent Cloud. All rights reserved.

Page 1138 of 1869

Cloud Infinite

Parameters
Parameter

Description/rotate/<rotateDegree>

Rotates an image clockwise by a specified angle. The value can be 0−360. By default,
the image is not rotated.

/auto-orient

Rotates an image automatically according to its EXIF data.

/flip/<flip>

Flips an image. Valid values: vertical , horizontal .
If this parameter is carried and the image fails to be processed because the image is/ignore-error/1

too large or a parameter value exceeds the limit, the input image will be returned withno error reported.

Format Conversion
Feature description
CI uses the imageMogr2 API to perform format conversion, GIF optimization, and progressive display.
Sample codes©2013-2022 Tencent Cloud. All rights reserved.

Page 1139 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1140 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// Image processing - format conversion. For more information, visit https://cl$imageRule = new Qcloud\\Cos\\ImageParamTemplate\\ImageMogrTemplate();$imageRule->format('jpg'); // Format conversion /format/<Format>$imageRule->gifOptimization(1); // GIF optimization /cgif/<FrameNumber>$imageRule->jpegInterlaceMode(1); // Progressive mode of the output JPG image,$imageRule->ignoreError(); // /ignore-error/1$picOperations = new Qcloud\\Cos\\ImageParamTemplate\\PicOperationsTransformati$picOperations->setIsPicInfo(1); // is_pic_info$picOperations->addRule($imageRule, "output.png"); // rules////// -------------------- 1. Processing during download -------------------- //$downloadUrl = $cosClient->getObjectUrl('examplebucket-1250000000', 'xxx.jpg'$downloadUrl = 'https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/$rule = $imageRule->queryString();echo "{$downloadUrl}?{$rule}";echo "{$downloadUrl}&{$rule}"; // The URL of an image with a signature is con// -------------------- 1. Processing during download -------------------- //// -------------------- 2. Processing during upload -------------------- //$result = $cosClient->putObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'object.jpg','Body' => fopen('/tmp/local.jpg', 'rb'), // Local file
'PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 2. Processing during upload -------------------- //// -------------------- 3. Processing in-cloud data -------------------- //$result = $cosClient->ImageProcess(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'test.png','PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 3. Processing in-cloud data -------------------- //} catch (\\Exception $e) {// Request failedecho($e);}©2013-2022 Tencent Cloud. All rights reserved.

Page 1141 of 1869

Cloud Infinite

Parameters
Parameter

Description
Converts the image format. The target format can be JPG, BMP, GIF, PNG, WebP, or/format/<Format>/cgif/<FrameNumber>

YJPEG (which is optimized based on JPEG and is essentially JPG). The default
format is the format of the input image.
Optimizes images in the GIF format by reducing frames and colors of images. There
are two cases: FrameNumber=1: Cut the input GIF to the default number of frames(30). If the original number of frames is greater than 30, excessive frames will be cut.
FrameNumber=(1,100]: Compress the image to the specified number of frames( FrameNumber ).
Progressive mode of the output JPG image. Valid values: 0 (default): Disables the/interlace/<Mode>

progressive mode; 1 : Enables the progressive mode. This parameter takes effectonly when the output image is in JPG format.
If this parameter is carried and the image fails to be processed because the image is/ignore-error/1

too large or a parameter value exceeds the limit, the input image will be returned withno error reported.

Quality Change
Feature description
CI uses the imageMogr2 API to adjust the quality of an image.
Sample codes©2013-2022 Tencent Cloud. All rights reserved.

Page 1142 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1143 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// Image processing - quality change. For more information, https://cloud.tence$imageRule = new Qcloud\\Cos\\ImageParamTemplate\\ImageMogrTemplate();$imageRule->quality(90, 1); // Absolute quality /quality/<Quality>$imageRule->lowestQuality(90); // Lowest quality /lquality/<quality>$imageRule->relativelyQuality(90); // Relative quality /rquality/<quality>$imageRule->ignoreError(); // /ignore-error/1$picOperations = new Qcloud\\Cos\\ImageParamTemplate\\PicOperationsTransformati$picOperations->setIsPicInfo(1); // is_pic_info$picOperations->addRule($imageRule, "output.png"); // rules////// -------------------- 1. Processing during download -------------------- //$downloadUrl = $cosClient->getObjectUrl('examplebucket-1250000000', 'xxx.jpg'$downloadUrl = 'https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/$rule = $imageRule->queryString();echo "{$downloadUrl}?{$rule}";echo "{$downloadUrl}&{$rule}"; // The URL of an image with a signature is con// -------------------- 1. Processing during download -------------------- //// -------------------- 2. Processing during upload -------------------- //$result = $cosClient->putObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'object.jpg','Body' => fopen('/tmp/local.jpg', 'rb'), // Local file
'PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 2. Processing during upload -------------------- //// -------------------- 3. Processing in-cloud data -------------------- //$result = $cosClient->ImageProcess(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'test.png','PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 3. Processing in-cloud data -------------------- //} catch (\\Exception $e) {// Request failedecho($e);}©2013-2022 Tencent Cloud. All rights reserved.

Page 1144 of 1869

Cloud Infinite

Parameters
Operation: quality
Parameter

Description/quality/<Quality>

Absolute quality of the image. The value can be 0–100. Use the value of the original image
quality (default) or the specified quality, whichever is smaller. If there is an exclamation
mark (!) after <Quality> (such as 90! ), the specified quality value is forcibly used.

/rquality/<quality>

Image quality relative to that of the input image. The value can be 0−100. For example, if
the input image quality is 80 and rquality is set to 80 , the quality of the output
image will be 64 (80 * 80%).

/lquality/<quality>

Minimum quality of the image. Value range: 0−100. If the input image quality is 85 andlquality is set to 80, the quality of the output image will be 85. If the input image
quality is 60 and lquality is set to 80, the quality of the output image will be improved
to 80.

/ignore-error/1

If this parameter is carried and the image fails to be processed because the image is toolarge or a parameter value exceeds the limit, the input image will be returned with no error
reported.

Gaussian Blurring
Feature description
CI uses the imageMogr2 API to blur an image.
Sample codes©2013-2022 Tencent Cloud. All rights reserved.

Page 1145 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1146 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// Image processing - Gaussian blurring. For more information, visit https://cl$imageRule = new Qcloud\\Cos\\ImageParamTemplate\\ImageMogrTemplate();$imageRule->blur(8, 5); // Gaussian blurring /blur/<radius>x<sigma>$imageRule->ignoreError(); // /ignore-error/1$picOperations = new Qcloud\\Cos\\ImageParamTemplate\\PicOperationsTransformati$picOperations->setIsPicInfo(1); // is_pic_info$picOperations->addRule($imageRule, "output.png"); // rules////// -------------------- 1. Processing during download -------------------- //$downloadUrl = $cosClient->getObjectUrl('examplebucket-1250000000', 'xxx.jpg'$downloadUrl = 'https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/$rule = $imageRule->queryString();echo "{$downloadUrl}?{$rule}";echo "{$downloadUrl}&{$rule}"; // The URL of an image with a signature is con// -------------------- 1. Processing during download -------------------- //// -------------------- 2. Processing during upload -------------------- //$result = $cosClient->putObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'object.jpg','Body' => fopen('/tmp/local.jpg', 'rb'), // Local file
'PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 2. Processing during upload -------------------- //// -------------------- 3. Processing in-cloud data -------------------- //$result = $cosClient->ImageProcess(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'test.png','PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 3. Processing in-cloud data -------------------- //} catch (\\Exception $e) {// Request failedecho($e);}©2013-2022 Tencent Cloud. All rights reserved.

Page 1147 of 1869

Cloud Infinite

Parameters
Operation: blur
Parameter

Description

radius<radius>

Blurring radius. Value range: 1–50.

sigma<sigma>

Standard deviation of normal distribution. The value must be greater than 0.

/ignore-error/1

If this parameter is carried and the image failed to be processed because the image
size or the parameter value is too large, the input image will be returned with no error
reported.

Adjusting Brightness
Feature description
CI uses the imageMogr2 API to adjust the brightness of an image.
Sample codes©2013-2022 Tencent Cloud. All rights reserved.

Page 1148 of 1869

Cloud Infinite<?php

require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,©2013-2022 Tencent Cloud. All rights reserved.

Page 1149 of 1869

Cloud Infinite'schema' => 'https', // Protocol, which is `http` by default'credentials' => array('secretId' => $secretId,'secretKey' => $secretKey)));try {// Image processing - brightness. For more information, visit https://cloud.ten$imageRule = new Qcloud\\Cos\\ImageParamTemplate\\ImageMogrTemplate();$imageRule->bright(70); // Image brightness adjustment /bright/<value>$imageRule->ignoreError(); // /ignore-error/1$picOperations = new Qcloud\\Cos\\ImageParamTemplate\\PicOperationsTransformati$picOperations->setIsPicInfo(1); // is_pic_info$picOperations->addRule($imageRule, "output.png"); // rules////// -------------------- 1. Processing during download -------------------- //$downloadUrl = $cosClient->getObjectUrl('examplebucket-1250000000', 'xxx.jpg'$downloadUrl = 'https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/$rule = $imageRule->queryString();echo "{$downloadUrl}?{$rule}";echo "{$downloadUrl}&{$rule}"; // The URL of an image with a signature is con// -------------------- 1. Processing during download -------------------- //// -------------------- 2. Processing during upload -------------------- //$result = $cosClient->putObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'object.jpg','Body' => fopen('/tmp/local.jpg', 'rb'), // Local file
'PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 2. Processing during upload -------------------- //// -------------------- 3. Processing in-cloud data -------------------- //$result = $cosClient->ImageProcess(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'test.png','PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 3. Processing in-cloud data -------------------- //} catch (\\Exception $e) {// Request failedecho($e);}©2013-2022 Tencent Cloud. All rights reserved.

Page 1150 of 1869

Cloud Infinite

Parameters
Operation: brightParameter

Description/bright/<value>

Adjusts the brightness of an image. The value must be an integer in the range of [-100,100]. value < 0: Reduces the image brightness. value = 0: Does not adjust theimage brightness. value > 0: Increases the image brightness.

/ignore-error/1

If this parameter is carried and the image failed to be processed because the image sizeor the parameter value is too large, the input image will be returned with no error reported.

Adjusting Contrast
Feature description
CI uses the imageMogr2 API to adjust an image’s contrast, which is the difference in luminance between thebrightest and darkest points in an image (i.e., the contrast in grayscale).
Sample codes©2013-2022 Tencent Cloud. All rights reserved.

Page 1151 of 1869

Cloud Infinite<?php

require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,©2013-2022 Tencent Cloud. All rights reserved.

Page 1152 of 1869

Cloud Infinite'schema' => 'https', // Protocol, which is `http` by default'credentials' => array('secretId' => $secretId,'secretKey' => $secretKey)));try {// Image processing - contrast. For more information, visit https://cloud.tence$imageRule = new Qcloud\\Cos\\ImageParamTemplate\\ImageMogrTemplate();$imageRule->contrast(-70); // Image contrast adjustment /contrast/<value>$imageRule->ignoreError(); // /ignore-error/1$picOperations = new Qcloud\\Cos\\ImageParamTemplate\\PicOperationsTransformati$picOperations->setIsPicInfo(1); // is_pic_info$picOperations->addRule($imageRule, "output.png"); // rules//// -------------------- 1. Processing during download -------------------- //$downloadUrl = $cosClient->getObjectUrl('examplebucket-1250000000', 'xxx.jpg'$downloadUrl = 'https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/$rule = $imageRule->queryString();echo "{$downloadUrl}?{$rule}";//echo "{$downloadUrl}&{$rule}"; // The URL of an image with a signature is con// -------------------- 1. Processing during download -------------------- //// -------------------- 2. Processing during upload -------------------- //$result = $cosClient->putObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'object.jpg','Body' => fopen('/tmp/local.jpg', 'rb'), // Local file
'PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 2. Processing during upload -------------------- //// -------------------- 3. Processing in-cloud data -------------------- //$result = $cosClient->ImageProcess(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'test.png','PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 3. Processing in-cloud data -------------------- //} catch (\\Exception $e) {// Request failedecho($e);}©2013-2022 Tencent Cloud. All rights reserved.

Page 1153 of 1869

Cloud Infinite

Parameters
Operation: contrast
Parameter

Description/contrast/<value>

Adjusts the contrast of an image. The value must be an integer in the range of [-100,100]. value < 0: Reduces the contrast. value = 0: Does not adjust thecontrast. value > 0: Increases the contrast.

/ignore-error/1

If this parameter is carried and the image fails to be processed because the image is
too large or a parameter value exceeds the limit, the input image will be returned withno error reported.

Sharpening
Feature description
CI uses the imageMogr2 API to sharpen an image.
Sample codes©2013-2022 Tencent Cloud. All rights reserved.

Page 1154 of 1869

Cloud Infinite<?php

require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,©2013-2022 Tencent Cloud. All rights reserved.

Page 1155 of 1869

Cloud Infinite'schema' => 'https', // Protocol, which is `http` by default'credentials' => array('secretId' => $secretId,'secretKey' => $secretKey)));try {// Image processing - sharpening. For more information, visit https://cloud.ten$imageRule = new Qcloud\\Cos\\ImageParamTemplate\\ImageMogrTemplate();$imageRule->sharpen(70); // Image sharpening /sharpen/<value>$imageRule->ignoreError(); // /ignore-error/1$picOperations = new Qcloud\\Cos\\ImageParamTemplate\\PicOperationsTransformati$picOperations->setIsPicInfo(1); // is_pic_info$picOperations->addRule($imageRule, "output.png"); // rules////// -------------------- 1. Processing during download -------------------- //$downloadUrl = $cosClient->getObjectUrl('examplebucket-1250000000', 'xxx.jpg'$downloadUrl = 'https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/$rule = $imageRule->queryString();echo "{$downloadUrl}?{$rule}";echo "{$downloadUrl}&{$rule}"; // The URL of an image with a signature is con// -------------------- 1. Processing during download -------------------- //// -------------------- 2. Processing during upload -------------------- //$result = $cosClient->putObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'object.jpg','Body' => fopen('/tmp/local.jpg', 'rb'), // Local file
'PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 2. Processing during upload -------------------- //// -------------------- 3. Processing in-cloud data -------------------- //$result = $cosClient->ImageProcess(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'test.png','PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 3. Processing in-cloud data -------------------- //} catch (\\Exception $e) {// Request failedecho($e);}©2013-2022 Tencent Cloud. All rights reserved.

Page 1156 of 1869

Cloud Infinite

Parameters
Operation: sharpen
Parameter

Description
Sharpens an image, where value controls the strength of the sharpening effect. The/sharpen/<value>/ignore-error/1

value must be an integer ranging from 10 to 300 (70 is recommended). The greater thevalue, the more obvious the sharpening effect.
If this parameter is carried and the image fails to be processed because the image is toolarge or a parameter value exceeds the limit, the input image will be returned with noerror reported.

Grayscale Image
Feature description
COS uses CI’s imageMogr2/grayscale API to set an image to be a grayscale image.
Sample codes©2013-2022 Tencent Cloud. All rights reserved.

Page 1157 of 1869

Cloud Infinite<?php

require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,©2013-2022 Tencent Cloud. All rights reserved.

Page 1158 of 1869

Cloud Infinite'schema' => 'https', // Protocol, which is `http` by default'credentials' => array('secretId' => $secretId,'secretKey' => $secretKey)));try {// Image processing - grayscale image. For more information, visit https://clou$imageRule = new Qcloud\\Cos\\ImageParamTemplate\\ImageMogrTemplate();$imageRule->grayscale(1); // Conversion of the image to grayscale image /graysc$imageRule->ignoreError(); // /ignore-error/1$picOperations = new Qcloud\\Cos\\ImageParamTemplate\\PicOperationsTransformati$picOperations->setIsPicInfo(1); // is_pic_info$picOperations->addRule($imageRule, "output.png"); // rules//// -------------------- 1. Processing during download -------------------- //$downloadUrl = $cosClient->getObjectUrl('examplebucket-1250000000', 'xxx.jpg'$downloadUrl = 'https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/$rule = $imageRule->queryString();echo "{$downloadUrl}?{$rule}";//echo "{$downloadUrl}&{$rule}"; // The URL of an image with a signature is con// -------------------- 1. Processing during download -------------------- //// -------------------- 2. Processing during upload -------------------- //$result = $cosClient->putObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'object.jpg','Body' => fopen('/tmp/local.jpg', 'rb'), // Local file
'PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 2. Processing during upload -------------------- //// -------------------- 3. Processing in-cloud data -------------------- //$result = $cosClient->ImageProcess(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'test.png','PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 3. Processing in-cloud data -------------------- //} catch (\\Exception $e) {// Request failedecho($e);}©2013-2022 Tencent Cloud. All rights reserved.

Page 1159 of 1869

Cloud Infinite

Parameters
Operation: grayscale
Parameter/grayscale/<value>/ignore-error/1

Description
Whether to set an image to be a grayscale image. Valid values of the value field:
0 (no), 1 (yes).
If this parameter is carried and the image fails to be processed because the image is
too large, the input image will be returned with no error reported.

Image Watermark
Feature description
COS implements image watermarking using the watermark API provided by CI, and thus only images stored in CIbound buckets can be processed. For the restrictions on Basic Image Processing (including watermarking), please
see Rules and Limits.
Sample codes©2013-2022 Tencent Cloud. All rights reserved.

Page 1160 of 1869

Cloud Infinite<?php

require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,©2013-2022 Tencent Cloud. All rights reserved.

Page 1161 of 1869

Cloud Infinite'schema' => 'https', // Protocol, which is `http` by default'credentials' => array('secretId' => $secretId,'secretKey' => $secretKey)));try {// Image processing - image watermark. For more information, visit https://clou$imageWatermarkRule = new Qcloud\\Cos\\ImageParamTemplate\\ImageWatermarkTempla$imageWatermarkRule->setImage('https://www.xxx.com/xxx.jpg'); // Watermark imag
$imageWatermarkRule->setGravity('SouthEast'); // Image watermark position$imageWatermarkRule->setDx(10); // Horizontal offset in px. Default value: `0`.
$imageWatermarkRule->setDy(10); // Vertical offset in px. Default value: `0`.
$imageWatermarkRule->setBlogo(1); // Adaptation mode for an image watermark tha$imageWatermarkRule->setScatype(1); // Scale the image watermark to the size of$imageWatermarkRule->setSpcent(200); // Use together with `scatype`$imageWatermarkRule->setDissolve(70); // Image watermark opacity$imageWatermarkRule->setBatch(1); // Tile the image watermark$imageWatermarkRule->setDegree(90); // Set the angle to rotate the image waterm$picOperations = new Qcloud\\Cos\\ImageParamTemplate\\PicOperationsTransformati$picOperations->setIsPicInfo(1); // is_pic_info$picOperations->addRule($imageWatermarkRule, "output.png"); // rules////// -------------------- 1. Processing during download -------------------- //$downloadUrl = $cosClient->getObjectUrl('examplebucket-1250000000', 'xxx.jpg'$downloadUrl = 'https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/$rule = $imageWatermarkRule->queryString();echo "{$downloadUrl}?{$rule}";echo "{$downloadUrl}&{$rule}"; // The URL of an image with a signature is con// -------------------- 1. Processing during download -------------------- //// -------------------- 2. Processing during upload -------------------- //$result = $cosClient->putObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'object.jpg','Body' => fopen('/tmp/local.jpg', 'rb'), // Local file
'PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 2. Processing during upload -------------------- //// -------------------- 3. Processing in-cloud data -------------------- //$result = $cosClient->ImageProcess(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'test.png','PicOperations' => $picOperations->queryString(),));©2013-2022 Tencent Cloud. All rights reserved.

Page 1162 of 1869

Cloud Infinite// Request succeeded
print_r($result);// -------------------- 3. Processing in-cloud data -------------------- //} catch (\\Exception $e) {// Request failedecho($e);}

Parameters
In the code above, watermark is the operation name and the number 1 indicates that the watermark is animage.
Parameter

Description/image/Image watermark URL, which must be URL-safe Base64-encoded. For example, if the image waterm
http://examplebucket-1250000000.cos.ap-shanghai.myqcloud.com/shuiyin_2.p
aHR0cDovL2V4YW1wbGVidWNrZXQtMTI1MDAwMDAwMC5jb3MuYXAtc2hhbmdoYWkubXlxY2xv/gravity/

Position of the image watermark, which is a square in a 3x3 grid. Default value: SouthEast .

/dx/

Horizontal offset in px. Default value: 0 .

/dy/Vertical offset in px. Default value: 0 .

/blogo//scatype/

Adaptation mode for an image watermark that is larger than the input image. Valid values: 1 (scale
input image); 2 (crops the image watermark to the size of the input image).
Scaling mode for the image watermark (relative to the input image). Valid values: 1 (scales by widt
by area).
Scale ratio of the image watermark in permillage. This parameter must be used together with scaty/spcent/

scatype is set to 1 ); 1−1000 (if scatype is set to 2 ); 1−250 (if scatype is set to 3
1251000004.cos.ap-shanghai.myqcloud.com/sample.jpeg?watermark/1/image/xxx/dissolve/

Opacity of the image watermark. Value range: 1−100. Default value: 90 (meaning 90% opacity)/batch/Whether to tile the image watermark. If this parameter is set to 1 , the image watermark will be tiled/degree/Angle to rotate the image watermark. This parameter will take effect only when /batch/ is set to
0 .

Note:
An image watermark must:
Be stored in the same bucket as the input image.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1163 of 1869

Cloud Infinite

Have a URL containing a COS domain name (a CDN acceleration domain name such as examplebucket1250000000.file.myqcloud.com/shuiyin_2.png is unsupported) and be accessible (if the image
watermark is set to private-read, it must carry a signature).
Have a URL starting with http:// . Note that "http://" cannot be omitted or changed to "https://". For example,
examplebucket-1250000000.cos.ap-shanghai.myqcloud.com/shuiyin_2.png andhttps://examplebucket-1250000000.cos.ap-shanghai.myqcloud.com/shuiyin_2.png areinvalid watermark URLs.

Text Watermark
Feature description
COS uses the watermark API provided by CI to add text watermarks in real time. An input image cannot be larger
than 32 MB, with its width and height not exceeding 30,000 pixels and the total number of pixels not exceeding 250
million. The width and height of the output image cannot exceed 9,999 pixels. For an input animated image, its total
number of pixels (Width x Height x Number of frames) cannot exceed 250 million.
Sample codes©2013-2022 Tencent Cloud. All rights reserved.

Page 1164 of 1869

Cloud Infinite<?php

require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,©2013-2022 Tencent Cloud. All rights reserved.

Page 1165 of 1869

Cloud Infinite'schema' => 'https', // Protocol, which is `http` by default'credentials' => array('secretId' => $secretId,'secretKey' => $secretKey)));try {// Image processing - text watermark. For more information, visit https://cloud$textWatermarkRule = new Qcloud\\Cos\\ImageParamTemplate\\TextWatermarkTemplate$textWatermarkRule->setText('Watermark content'); // Watermark content$textWatermarkRule->setFont('tahoma.ttf'); // Watermark font
$textWatermarkRule->setFontsize(13); // Watermark text font size
$textWatermarkRule->setFill('#3D3D3D'); // Font color. The value must be in hex$textWatermarkRule->setDissolve(90); // Text opacity. Value range: 1−100. Defau$textWatermarkRule->setGravity('SouthEast'); // Position of the text watermark$textWatermarkRule->setDx(10); // Horizontal offset in px. Default value: `0`.
$textWatermarkRule->setDy(10); // Vertical offset in px. Default value: `0`.
$textWatermarkRule->setBatch(1); // Whether to tile the text watermark. If this$textWatermarkRule->setDegree(10); // Angle to rotate the text watermark. This
$textWatermarkRule->setShadow(10); // Text shadow effect. Value range: 0−100. D$picOperations = new Qcloud\\Cos\\ImageParamTemplate\\PicOperationsTransformati$picOperations->setIsPicInfo(1); // is_pic_info$picOperations->addRule($textWatermarkRule, "output.png"); // rules////// -------------------- 1. Processing during download -------------------- //$downloadUrl = $cosClient->getObjectUrl('examplebucket-1250000000', 'xxx.jpg'$downloadUrl = 'https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/$rule = $textWatermarkRule->queryString();echo "{$downloadUrl}?{$rule}";echo "{$downloadUrl}&{$rule}"; // The URL of an image with a signature is con// -------------------- 1. Processing during download -------------------- //// -------------------- 2. Processing during upload -------------------- //$result = $cosClient->putObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'object.jpg','Body' => fopen('/tmp/local.jpg', 'rb'), // Local file
'PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 2. Processing during upload -------------------- //// -------------------- 3. Processing in-cloud data -------------------- //$result = $cosClient->ImageProcess(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'test.png','PicOperations' => $picOperations->queryString(),©2013-2022 Tencent Cloud. All rights reserved.

Page 1166 of 1869

Cloud Infinite));// Request succeeded
print_r($result);// -------------------- 3. Processing in-cloud data -------------------- //} catch (\\Exception $e) {// Request failedecho($e);}

Parameters
In the code above, watermark is the operation name and the number 2 indicates that the watermark is a text.
Parameter

Description/text/

Watermark text, which must be URL-safe Base64-encoded.

/font/

Font of the text, which must be URL-safe Base64-encoded. Default font: Tahoma.ttf (seeSupported Fonts).
Font size, in pt. Default value: 13 . To scale the text watermark proportionally based/fontsize/on the original image, convert the text watermark to a PNG image. For more
configuration information, see Image Watermarking
Font color. The value must be in hexadecimal format, for example, #FF0000 . For/fill/

format conversion, see RGB Color Codes Chart. The value must be URL-safe Base64encoded. Default value: #3D3D3D (gray).

/dissolve/

Text opacity. Value range: 1−100. Default value: 90 (meaning 90% opacity)/gravity/

Position of the text watermark, which is a square in a 3x3 grid. Default value:
SouthEast .

/dx/

Horizontal offset in px. Default value: 0 .

/dy/Vertical offset in px. Default value: 0 .

/batch/Whether to tile the text watermark. If this parameter is set to 1 , the text watermark will
be tiled across the input image.

/degree/Angle to rotate the text watermark. This parameter will take effect only when/batch/ is set to 1 . Value range: 0−360. Default value: 0 .

/shadow/

Text shadow effect. Value range: 0−100. Default value: 0 (no shadow).

Basic Image Information Acquisition©2013-2022 Tencent Cloud. All rights reserved.

Page 1167 of 1869

Cloud Infinite

Feature description
COS uses the imageInfo API provided by CI to query an image’s basic information such as its format, width, andheight.
Sample codes<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';©2013-2022 Tencent Cloud. All rights reserved.

Page 1168 of 1869

Cloud Infinite$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->ImageInfo(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'exampleobject',));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameters
Operation: imageInfo
Parameter

Description

Key

Object name, such as folder/sample.jpg .

Response parameters
Parameter

Description

formatImage type, such as PNG and GIF.

width

Image width in px.

heightImage height in px.

size

Image size in bytes.

md5

Image MD5 value.

frame_countNumber of frames. For static images, this value is 1 .

©2013-2022 Tencent Cloud. All rights reserved.

Page 1169 of 1869

Cloud Infinite

Image EXIF Data Acquisition
Feature description
Exchangeable Image File (EXIF) records the camera settings, thumbnails, and other attributes of digital images. COS
uses the exif API provided by CI to obtain EXIF data. An input image cannot be larger than 32 MB, with its width andheight not exceeding 30,000 pixels and the total number of pixels not exceeding 250 million. The width and height ofan output image cannot exceed 9,999 pixels. For an input animated image, the total number of pixels (Width x Height x
Number of frames) cannot exceed 250 million.
Sample codes©2013-2022 Tencent Cloud. All rights reserved.

Page 1170 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1171 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->ImageExif(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'exampleobject',));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameters
Operation: exif
Parameter

Description

Key

Object name, such as folder/sample.jpg .

Image Average Hue Acquisition
Feature description
COS uses the imageAve API provided by CI to obtain the average hue of an image. The input image cannot be larger
than 32 MB, with its width and height not exceeding 30,000 pixels, and the total number of pixels not exceeding 250
million. The width and height of the output image cannot exceed 9,999 pixels. For an input animated image, the total
number of pixels (Width x Height x Number of frames) cannot exceed 250 million pixels.
Sample codes©2013-2022 Tencent Cloud. All rights reserved.

Page 1172 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1173 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->ImageAve(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'exampleobject',));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameters
Operation: imageAve
Parameter

Description

Key

Object name, such as folder/sample.jpg .

Removing Image Metadata
Feature description
COS uses the imageMogr2 API provided by CI to remove image metadata, including EXIF data.
Sample codes©2013-2022 Tencent Cloud. All rights reserved.

Page 1174 of 1869

Cloud Infinite<?php

require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,©2013-2022 Tencent Cloud. All rights reserved.

Page 1175 of 1869

Cloud Infinite'schema' => 'https', // Protocol, which is `http` by default'credentials' => array('secretId' => $secretId,'secretKey' => $secretKey)));try {// Image processing - metadata removal. For more information, visit https://clo$imageRule = new Qcloud\\Cos\\ImageParamTemplate\\ImageMogrTemplate();$imageRule->strip(); // Remove the image metadata, including EXIF data.
$imageRule->ignoreError(); // /ignore-error/1/strip$picOperations = new Qcloud\\Cos\\ImageParamTemplate\\PicOperationsTransformati$picOperations->setIsPicInfo(1); // is_pic_info$picOperations->addRule($imageRule, "output.png"); // rules////// -------------------- 1. Processing during download -------------------- //$downloadUrl = $cosClient->getObjectUrl('examplebucket-1250000000', 'xxx.jpg'$downloadUrl = 'https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/$rule = $imageRule->queryString();echo "{$downloadUrl}?{$rule}";echo "{$downloadUrl}&{$rule}"; // The URL of an image with a signature is con// -------------------- 1. Processing during download -------------------- //// -------------------- 2. Processing during upload -------------------- //$result = $cosClient->putObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'object.jpg','Body' => fopen('/tmp/local.jpg', 'rb'), // Local file
'PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 2. Processing during upload -------------------- //// -------------------- 3. Processing in-cloud data -------------------- //$result = $cosClient->ImageProcess(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'test.png','PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 3. Processing in-cloud data -------------------- //} catch (\\Exception $e) {// Request failedecho($e);}©2013-2022 Tencent Cloud. All rights reserved.

Page 1176 of 1869

Cloud Infinite

Parameters
Operation: strip
Parameter

Description/ignore-error/1

If this parameter is carried and the image failed to be processed because it is too large,
the input image will be returned with no error reported.

Quick Thumbnail Template
Feature description
COS uses the imageView2 API of Cloud Infinite (CI) to provide a common image processing template. You canappend parameters to the download URL to generate the desired thumbnail. The input image cannot be larger than 32
MB, with its width and height not exceeding 30,000 pixels and the total number of pixels not exceeding 250 million.
The width and height of the output image cannot exceed 9,999 pixels. For an input animated image, the total numberof pixels (width x height x number of frames) cannot exceed 250 million (GIF frame limit: 300).
Sample codes©2013-2022 Tencent Cloud. All rights reserved.

Page 1177 of 1869

Cloud Infinite<?php

require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,©2013-2022 Tencent Cloud. All rights reserved.

Page 1178 of 1869

Cloud Infinite'schema' => 'https', // Protocol, which is `http` by default'credentials' => array('secretId' => $secretId,'secretKey' => $secretKey)));try {// Image processing - quick thumbnail template. For more information, visit htt$imageViewRule = new Qcloud\\Cos\\ImageParamTemplate\\ImageViewTemplate();$imageViewRule->setMode(1); // /<mode>$imageViewRule->setWidth(400); // /w/<Width>$imageViewRule->setHeight(600); // /h/<Height>$imageViewRule->setFormat('jpg'); // /format/<Format>$imageViewRule->setQuality(1, 85); // 1-/q/<Quality>; 2-/rq/<quality>; 3-/lq/<q$imageViewRule->ignoreError(); // /ignore-error/1$picOperations = new Qcloud\\Cos\\ImageParamTemplate\\PicOperationsTransformati$picOperations->setIsPicInfo(1); // is_pic_info$picOperations->addRule($imageViewRule, "output.png"); // rules// -------------------- 1. Processing during download -------------------- //////$downloadUrl = $cosClient->getObjectUrl('examplebucket-1250000000', 'xxx.jpg'$downloadUrl = 'https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/$rule = $imageViewRule->queryString();echo "{$downloadUrl}?{$rule}";echo "{$downloadUrl}&{$rule}"; // The URL of an image with a signature is con// -------------------- 1. Processing during download -------------------- //// -------------------- 2. Processing during upload -------------------- //$result = $cosClient->putObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'object.jpg','Body' => fopen('/tmp/local.jpg', 'rb'), // Local file
'PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 2. Processing during upload -------------------- //// -------------------- 3. Processing in-cloud data -------------------- //$result = $cosClient->ImageProcess(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'test.png','PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 3. Processing in-cloud data -------------------- //} catch (\\Exception $e) {©2013-2022 Tencent Cloud. All rights reserved.

Page 1179 of 1869

Cloud Infinite// Request failedecho($e);}

Parameters
Parameter/1/w/<Width>/h/<Height>

Description
Specifies the minimum width and height of the thumbnail. In this mode, theimage will be first scaled down until one of the minimum values set isreached. Then, the image will be centered and evenly cropped on bothsides to meet the specified values. If only one value is set, a square
thumbnail will be generated. For example, if the input image size is
1000x500 and this parameter is set to ?
imageView2/1/w/500/h/400 , the image will be scaled down to
800x400 first. Then, 150 pixels will be cropped from the left and right sides
respectively, outputting a 500x400 thumbnail.

/2/w/<Width>/h/<Height>

Specifies the maximum width and height of the thumbnail. In this mode, theimage is scaled down until both the width and length are not greater thanthe maximum values set. For example, if the input image size is 1000x500
and this parameter is set to ?imageView2/2/w/500/h/400 , theimage is scaled down to 500x250. If only one value is set, the image will be
adapted.

/3/w/<Width>/h/<Height>

Specifies the minimum width and height of the thumbnail. In this mode, theimage will be scaled down until both the width and height are not smaller
than the minimum values set. For example, if the input image size is
1000x500 and this parameter is set to ?
imageView2/3/w/500/h/400 , the image will be scaled down to
800x400. If only one value is set, a square thumbnail will be generated.

/4/w/<LongEdge>/h/<ShortEdge>

Specifies the minimum values of the long edge and short edge of thethumbnail to scale down the image. If only one value is set, a square
thumbnail will be generated.

/5/w/<LongEdge>/h/<ShortEdge>

Specifies the maximum values of the long edge and short edge of thethumbnail to scale down the image. The image will be centered andcropped. If only one value is set, a square thumbnail will be generated.
After the scaling, the excess will be cropped.

/format/<Format>

Format of the thumbnail, which can be JPG, BMP, GIF, PNG, or WebP.
Default value: Format of the input image.

/q/<Quality>

Image quality. The value can be 0–100. Use the value of the original image
quality (default) or the specified quality, whichever is smaller. If there is an©2013-2022 Tencent Cloud. All rights reserved.

Page 1180 of 1869

Cloud Infinite

exclamation mark (!) after <Quality> , the specified quality value is forciblyused.

/rq/<quality>

Image quality relative to that of the input image. The value can be 0−100.
For example, if the input image quality is 80 and rquality is set to
80 , the quality of the output image will be 64 (80 * 80%).

/lq/<quality>

Minimum quality of the image. Value range: 0−100. If the input image
quality is 85 and lquality is set to 80, the quality of the output image
will be 85. If the input image quality is 60 and lquality is set to 80,
the quality of the output image will be improved to 80.

Image Size Limiting
Feature description
COS uses the imageMogr2/size-limit API provided by CI to limit the size of an image processed (e.g., scaled orcompressed).
Sample codes©2013-2022 Tencent Cloud. All rights reserved.

Page 1181 of 1869

Cloud Infinite<?php

require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,©2013-2022 Tencent Cloud. All rights reserved.

Page 1182 of 1869

Cloud Infinite'schema' => 'https', // Protocol, which is `http` by default'credentials' => array('secretId' => $secretId,'secretKey' => $secretKey)));try {// Image processing - image size limiting. For more information, visit https://$imageRule = new Qcloud\\Cos\\ImageParamTemplate\\ImageMogrTemplate();$imageRule->sizeLimit(15, 1); // Limit the size of an output image, such as a s$imageRule->ignoreError(); // /ignore-error/1$picOperations = new Qcloud\\Cos\\ImageParamTemplate\\PicOperationsTransformati$picOperations->setIsPicInfo(1); // is_pic_info$picOperations->addRule($imageRule, "output.png"); // rules////// -------------------- 1. Processing during download -------------------- //$downloadUrl = $cosClient->getObjectUrl('examplebucket-1250000000', 'xxx.jpg'$downloadUrl = 'https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/$rule = $imageRule->queryString();echo "{$downloadUrl}?{$rule}";echo "{$downloadUrl}&{$rule}"; // The URL of an image with a signature is con// -------------------- 1. Processing during download -------------------- //// -------------------- 2. Processing during upload -------------------- //$result = $cosClient->putObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'object.jpg','Body' => fopen('/tmp/local.jpg', 'rb'), // Local file
'PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 2. Processing during upload -------------------- //// -------------------- 3. Processing in-cloud data -------------------- //$result = $cosClient->ImageProcess(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'test.png','PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 3. Processing in-cloud data -------------------- //} catch (\\Exception $e) {// Request failedecho($e);}©2013-2022 Tencent Cloud. All rights reserved.

Page 1183 of 1869

Cloud Infinite

Parameters
Operation: size-limit
Parameter

Description
Limits the size of the output image. The unit can be k (KB) or m (MB). 1. Only JPG
images are supported. 2. Appending an exclamation mark (!) means to compare the sizes of
the input and output images. If the output image is smaller, the output image will be returned;
otherwise, the input image will be returned; for example, examplebucket-

size-limit

1250000000.cos.ap-shanghai.myqcloud.com/picture.jpg?
imageMogr2/size-limit/15k! . 3. We recommend you use this parameter together withstrip to remove redundant image metadata, for example, examplebucket1250000000.cos.ap-shanghai.myqcloud.com/picture.jpg?
imageMogr2/strip/format/png/size-limit/15k! .

/ignoreerror/1

If this parameter is carried and the image failed to be processed because it is too large, theinput image will be returned with no error reported.

Pipeline Operator
Feature description
COS uses the pipeline operators (|) provided by CI to separate multiple image processing parameters. In this way,
multiple operations can be performed in sequence in a single request. The input image cannot be larger than 32 MB,with its width and height not exceeding 30,000 pixels, and the total number of pixels not exceeding 250 million. The
width and height of the output image cannot exceed 9,999 pixels. For an input animated image, the total number ofpixels (Width x Height x Number of frames) cannot exceed 250 million pixels.
Sample codes©2013-2022 Tencent Cloud. All rights reserved.

Page 1184 of 1869

Cloud Infinite<?php

require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,©2013-2022 Tencent Cloud. All rights reserved.

Page 1185 of 1869

Cloud Infinite'schema' => 'https', // Protocol, which is `http` by default'credentials' => array('secretId' => $secretId,'secretKey' => $secretKey)));try {// Image processing - pipeline operator. For more information, visit https://cl$imageMogrRule = new Qcloud\\Cos\\ImageParamTemplate\\ImageMogrTemplate();$imageMogrRule->thumbnailByScale(50);$imageMogrRule->rotate(50);$imageViewRule = new Qcloud\\Cos\\ImageParamTemplate\\ImageViewTemplate();$imageViewRule->setMode(1);$imageViewRule->setWidth(400);$imageViewRule->setHeight(600);$imageViewRule->setQuality(1, 85);$ciParamChannel = new Qcloud\\Cos\\ImageParamTemplate\\CIParamTransformation();$ciParamChannel->addRule($imageMogrRule); // Multiple processing methods connec$ciParamChannel->addRule($imageViewRule); // Multiple processing methods connec$picOperations = new Qcloud\\Cos\\ImageParamTemplate\\PicOperationsTransformati$picOperations->setIsPicInfo(1); // is_pic_info$picOperations->addRule($ciParamChannel, "output.png"); // rules////// -------------------- 1. Processing during download -------------------- //$downloadUrl = $cosClient->getObjectUrl('examplebucket-1250000000', 'xxx.jpg'$downloadUrl = 'https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/$rule = $ciParamChannel->queryString();echo "{$downloadUrl}?{$rule}";echo "{$downloadUrl}&{$rule}"; // The URL of an image with a signature is con// -------------------- 1. Processing during download -------------------- //// -------------------- 2. Processing during upload -------------------- //$result = $cosClient->putObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'object.jpg','Body' => fopen('/tmp/local.jpg', 'rb'), // Local file
'PicOperations' => $picOperations->queryString(),));// Request succeeded
print_r($result);// -------------------- 2. Processing during upload -------------------- //// -------------------- 3. Processing in-cloud data -------------------- //$result = $cosClient->ImageProcess(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'test.png','PicOperations' => $picOperations->queryString(),));©2013-2022 Tencent Cloud. All rights reserved.

Page 1186 of 1869

Cloud Infinite// Request succeeded
print_r($result);// -------------------- 3. Processing in-cloud data -------------------- //} catch (\\Exception $e) {// Request failedecho($e);}

Parameters
Multiple processing styles are separated by the pipeline operator | and executed in sequence. Currently, there canbe a maximum of 10 pipelines.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1187 of 1869

Cloud Infinite

Image Style：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for image styles.
API

Description

Adding style

Adds a style to a bucket.

Querying styles

Queries styles set for a bucket.

Deleting style

Deletes a style from a bucket.

Adding Style
Feature description
This API is used to add a style to a bucket. This style will be added to images subsequently uploaded to this bucket.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1188 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1189 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->PutBucketImageStyle(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'StyleName' => 'style_name',// Style name
'StyleBody' => 'imageMogr2/thumbnail/!50px', // Style information));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Type

Description

Required

BucketStringBucket name in the format of BucketName-APPID

Yes

StyleName

StringStyle name

Yes

StyleBody

StringStyle information

Yes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1190 of 1869

Cloud Infinite

Guzzle\\Service\\Resource\\Model Object([structure:protected] =>[data:protected] => Array([RequestId] => NWQwOGRkNDdfMjJiMjU4NjRfNzVjXzEwNmVjY2M=[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.pic.ap-beijing.myqcloud.com/))©2013-2022 Tencent Cloud. All rights reserved.

Page 1191 of 1869

Cloud Infinite

Response description
Parameter

Type

Description

Parent NodeRequestId

StringRequest ID

None

BucketStringBucket name in the format of BucketName-APPID

None

Location

StringAddress of the requested resource

None

Querying Styles
Feature description
This API is used to query the styles set for a bucket.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1192 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1193 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->GetBucketImageStyle(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'StyleName' => 'style_name', // Style name));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Type

Description

Required

BucketStringBucket name in the format of BucketName-APPID

Yes

StyleName

StringStyle nameNo

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1194 of 1869

Cloud Infinite

Guzzle\\Service\\Resource\\Model Object([structure:protected] =>[data:protected] => Array([RequestId] => NWQwOGRkNDdfMjJiMjU4NjRfNzVjXzEwNmVjY2M=[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.pic.ap-beijing.myqcloud.com/[StyleRule] => Array([0] => Array([StyleName] => style_name©2013-2022 Tencent Cloud. All rights reserved.

Page 1195 of 1869

Cloud Infinite[StyleBody] => imageMogr2/thumbnail/!50px))))

Response description
Parameter

Type

Description

Parent NodeRequestId

StringRequest ID

None

BucketStringBucket name in the format of BucketName-APPID

None

Location

StringAddress of the requested resource

None

StyleRule

Array

List of style information

None

Deleting Style
Feature description
This API is used to delete a style from a bucket.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1196 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1197 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->DeleteBucketImageStyle(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'StyleName' => 'style_name', // Style name));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Type

Description

Required

BucketStringBucket name in the format of BucketName-APPID

Yes

StyleName

StringStyle nameYes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1198 of 1869

Cloud Infinite

Guzzle\\Service\\Resource\\Model Object([structure:protected] =>[data:protected] => Array([RequestId] => NWQwOGRkNDdfMjJiMjU4NjRfNzVjXzEwNmVjY2M=[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.pic.ap-beijing.myqcloud.com/))©2013-2022 Tencent Cloud. All rights reserved.

Page 1199 of 1869

Cloud Infinite

Response description
Parameter

Type

Description

Parent NodeRequestId

StringRequest ID

None

BucketStringBucket name in the format of BucketName-APPID

None

Location

StringAddress of the requested resourceNone©2013-2022 Tencent Cloud. All rights reserved.

Page 1200 of 1869

Cloud Infinite

Persistent Image Processing：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for persistent image processing.
API

Description

Persistent image
processing

Processes an image during upload, or processes an image stored in COS and saves
the processing result to COS.

Processing During Upload
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1201 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1202 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$imageMogrTemplate = new Qcloud\\Cos\\ImageParamTemplate\\ImageMogrTemplate$imageMogrTemplate->thumbnailByScale(50);// Scale an image to 50% of its or$picOperationsTemplate = new \\Qcloud\\Cos\\ImageParamTemplate\\PicOperatio$picOperationsTemplate->setIsPicInfo(1);// Set whether to return the input$picOperationsTemplate->addRule($imageMogrTemplate, "resultobject");// Set$result = $cosClient->putObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'exampleobject','Body' => fopen('path/to/localFile', 'rb'),'PicOperations' => $picOperationsTemplate->queryString(),// Generate parame));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Type

Description

Required

BucketStringBucket name in the format of BucketName-APPID

YesStringObject key, which is the unique identifier of the object in thebucket. For example, if an object's access endpoint isexamplebucket-1250000000.cos.ap-

Yes

Key

guangzhou.myqcloud.com/doc/pic.jpg , its key is
doc/pic.jpg .
BodyFile/String

Uploaded content

Yes

PicOperations

Json/String

Persistent image processing information

Yes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1203 of 1869

Cloud Infinite

Guzzle\\Service\\Resource\\Model Object([structure:protected] =>[data:protected] => Array([Body] =>[ETag] => "698d51a19d8a121ce581499d7b701668"[RequestId] => NWQwOGRkNDdfMjJiMjU4NjRfNzVjXzEwNmVjY2M=[ContentLength] => 238186[Key] => exampleobject[Bucket] => examplebucket-1250000000©2013-2022 Tencent Cloud. All rights reserved.

Page 1204 of 1869

Cloud Infinite[Location] => examplebucket-1250000000.cos.ap-beijing.myqcloud.com/exam[Data] => Array([OriginalInfo] => Array([Key] => exampleobject[Location] => examplebucket-1250000000.cos.ap-beijing.myqcloud.
[ETag] => "7037fb6fb4cca43b958a28789605e73d98088720"[ImageInfo] => Array([Format] => JPEG
[Width] => 600[Height] => 500[Quality] => 90[Ave] => 0x46442e[Orientation] => 0))
[ProcessResults] => Array([Object] => Array([0] => Array([Key] => resultobject[Location] => examplebucket-1250000000.cos.ap-beijing.m[Format] => JPEG
[Width] => 300[Height] => 200[Size] => 30000[Quality] => 90[ETag] => "87c153bc2909aa0ba111ca126b675c510d36b817"
)
)
)
)
)
)

Response description
Parameter

Type

Description

Parent Node

Body

File/String

Response body

None

ETag

String

MD5 checksum of the fileNone©2013-2022 Tencent Cloud. All rights reserved.

Page 1205 of 1869

Cloud Infinite

RequestId

StringRequest ID

None

ContentLength

Int

Length of the response body

None

Key

StringObject key

None

BucketStringBucket name in the format of BucketName-APPID

None

Location

StringAddress of the requested resource

None

Data

Array

Image processing result

None

Processing In-Cloud Data
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1206 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1207 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$imageMogrTemplate = new Qcloud\\Cos\\ImageParamTemplate\\ImageMogrTemplate$imageMogrTemplate->thumbnailByScale(50);// Scale an image to 50% of its or$picOperationsTemplate = new \\Qcloud\\Cos\\ImageParamTemplate\\PicOperatio$picOperationsTemplate->setIsPicInfo(1);// Set whether to return the input$picOperationsTemplate->addRule($imageMogrTemplate, "resultobject");// Set$result = $cosClient->ImageProcess(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'exampleobject','PicOperations' => $picOperationsTemplate->queryString(),// Generate parame));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Type

Description

Required

BucketStringBucket name in the format of BucketName-APPID

YesStringObject key, which is the unique identifier of the object in thebucket. For example, if an object's access endpoint isexamplebucket-1250000000.cos.ap-

Yes

Key

guangzhou.myqcloud.com/doc/pic.jpg , its key is
doc/pic.jpg .
PicOperations

Json/String

Persistent image processing information

Yes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1208 of 1869

Cloud Infinite

Guzzle\\Service\\Resource\\Model Object([structure:protected] =>[data:protected] => Array([RequestId] => NWQwOGRkNDdfMjJiMjU4NjRfNzVjXzEwNmVjY2M=[Key] => exampleobject[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.cos.ap-beijing.myqcloud.com/exam[OriginalInfo] => Array(©2013-2022 Tencent Cloud. All rights reserved.

Page 1209 of 1869

Cloud Infinite[Key] => exampleobject[Location] => examplebucket-1250000000.cos.ap-beijing.myqcloud.com/[ETag] => "7037fb6fb4cca43b958a28789605e73d98088720"[ImageInfo] => Array([Format] => JPEG
[Width] => 600[Height] => 500[Quality] => 90[Ave] => 0x46442e[Orientation] => 0))
[ProcessResults] => Array([Object] => Array([0] => Array([Key] => resultobject[Location] => examplebucket-1250000000.cos.ap-beijing.myqcl[Format] => JPEG
[Width] => 300[Height] => 200[Size] => 30000[Quality] => 90[ETag] => "87c153bc2909aa0ba111ca126b675c510d36b817"
)
)
)
)
)

Response description
Parameter

Type

Description

Parent NodeRequestId

StringRequest ID

None

Key

StringObject key

None

BucketStringBucket name in the format of BucketName-APPID

None

Location

StringAddress of the requested resource

None

OriginalInfo

Array

Input image informationNone©2013-2022 Tencent Cloud. All rights reserved.

Page 1210 of 1869

Cloud Infinite

ProcessResults

Array

Image processing result©2013-2022 Tencent Cloud. All rights reserved.

None

Page 1211 of 1869

Cloud Infinite

Blind Watermark：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for blind watermarking.
API

Description

Blindwatermarking

Adds blind watermark to or extracts blind watermark from local image and uploads it tobucketAdding Blind Watermark
Adding during upload
The specified watermark image must:
1. Be stored in the same bucket as the input image.
2. Be accessible at a URL containing a COS domain name (CDN acceleration domain names such as
examplebucket-1250000000.file.myqcloud.com/shuiyin_2.png are not supported). If the image
watermark is set to privately readable, the URL must carry a signature.
3. Have a URL starting with http:// . Note that "http://" cannot be omitted or changed to "https://". For example,
examplebucket-1250000000.cos.ap-shanghai.myqcloud.com/shuiyin_2.png andhttps://examplebucket-1250000000.cos.ap-shanghai.myqcloud.com/shuiyin_2.png areinvalid watermark URLs.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1212 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1213 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$blindWatermarkTemplate = new Qcloud\\Cos\\ImageParamTemplate\\BlindWaterma$blindWatermarkTemplate->setType(3);// Blind watermark type. Valid values:$blindWatermarkTemplate->setImage("imageUrl");// Set the blind watermark im$blindWatermarkTemplate->setText("Test");// Set the blind watermark text
$blindWatermarkTemplate->setLevel(3);// Blind watermark level, which only t$picOperationsTemplate = new \\Qcloud\\Cos\\ImageParamTemplate\\PicOperatio$picOperationsTemplate->setIsPicInfo(1);// Set whether to return the input$picOperationsTemplate->addRule($blindWatermarkTemplate, "resultobject");//$result = $cosClient->putObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'exampleobject','Body' => fopen('path/to/localFile', 'rb'),'PicOperations' => $picOperationsTemplate->queryString(),// Generate parame));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Type

Description

Required

BucketStringBucket name in the format of BucketName-APPID

YesStringObject key, which is the unique identifier of the object in thebucket. For example, if an object's access endpoint isexamplebucket-1250000000.cos.ap-

Yes

Key

guangzhou.myqcloud.com/doc/pic.jpg , its key is
doc/pic.jpg .
BodyFile/String

Uploaded content

Yes

PicOperations

Json/String

Persistent image processing information

Yes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1214 of 1869

Cloud Infinite

Guzzle\\Service\\Resource\\Model Object([structure:protected] =>[data:protected] => Array([Body] =>[ETag] => "698d51a19d8a121ce581499d7b701668"[RequestId] => NWQwOGRkNDdfMjJiMjU4NjRfNzVjXzEwNmVjY2M=[ContentLength] => 10000[Key] => exampleobject[Bucket] => examplebucket-1250000000©2013-2022 Tencent Cloud. All rights reserved.

Page 1215 of 1869

Cloud Infinite[Location] => examplebucket-1250000000.cos.ap-beijing.myqcloud.com/exam[Data] => Array([OriginalInfo] => Array([Key] => exampleobject[Location] => examplebucket-1250000000.cos.ap-beijing.myqcloud.
[ETag] => "7037fb6fb4cca43b958a28789605e73d98088720"[ImageInfo] => Array([Format] => JPEG
[Width] => 600[Height] => 500[Quality] => 90[Ave] => 0x46442e[Orientation] => 0))
[ProcessResults] => Array([Object] => Array([0] => Array([Key] => resultobject[Location] => examplebucket-1250000000.cos.ap-beijing.m[Format] => JPEG
[Width] => 300[Height] => 200[Size] => 30000[Quality] => 90[ETag] => "87c153bc2909aa0ba111ca126b675c510d36b817"
)
)
)
)
)
)

Response description
Parameter

Type

Description

Parent Node

Body

File/String

Response body

None

ETag

String

MD5 checksum of the fileNone©2013-2022 Tencent Cloud. All rights reserved.

Page 1216 of 1869

Cloud Infinite

RequestId

StringRequest ID

None

ContentLength

Int

Length of the response body

None

Key

StringObject key

None

BucketStringBucket name in the format of BucketName-APPID

None

Location

StringAddress of the requested resource

None

Data

Array

Image processing result

None

Adding during download
The specified watermark image must:
1. Be stored in the same bucket as the input image.
2. Be accessible at a URL containing a COS domain name (CDN acceleration domain names such as
examplebucket-1250000000.file.myqcloud.com/shuiyin_2.png are not supported). If the image
watermark is set to privately readable, the URL must carry a signature.
3. Have a URL starting with http:// . Note that "http://" cannot be omitted or changed to "https://". For example,
examplebucket-1250000000.cos.ap-shanghai.myqcloud.com/shuiyin_2.png andhttps://examplebucket-1250000000.cos.ap-shanghai.myqcloud.com/shuiyin_2.png areinvalid watermark URLs.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1217 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1218 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$blindWatermarkTemplate = new Qcloud\\Cos\\ImageParamTemplate\\BlindWaterma$blindWatermarkTemplate->setType(3);// Blind watermark type. Valid values:$blindWatermarkTemplate->setImage("imageUrl");// Set the blind watermark im$blindWatermarkTemplate->setText("Test");// Set the blind watermark text
$blindWatermarkTemplate->setLevel(3);// Blind watermark level, which only t$result = $cosClient->getObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'exampleobject','ImageHandleParam' => $blindWatermarkTemplate->queryString(),// Generate bl));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Type

Description

Required

BucketStringBucket name in the format of BucketName-APPID

Yes

Object key, which is the unique identifier of the object in theKey

Stringbucket. For example, if an object's access endpoint isexamplebucket-1250000000.cos.ap-

Yesguangzhou.myqcloud.com/doc/pic.jpg , its key is
doc/pic.jpg .
ImageHandleParamStringBlind watermark parameter

Yes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1219 of 1869

Cloud Infinite

Guzzle\\Service\\Resource\\Model Object([structure:protected] =>[data:protected] => Array([Body] =>[RequestId] => NWQwOGRkNDdfMjJiMjU4NjRfNzVjXzEwNmVjY2M=[ContentLength] => 100[CacheControl] => max-age=2592000[ContentType] => image/jpeg[Key] => exampleobject©2013-2022 Tencent Cloud. All rights reserved.

Page 1220 of 1869

Cloud Infinite[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.cos.ap-beijing.myqcloud.com/exam))

Response description
Parameter

Type

Description

Parent Node

Body

File/String

Downloaded content

NoneRequestId

StringRequest ID

None

CacheControl

StringCache policy. Sets Cache-Control .

None

ContentType

StringContent type. Sets Content-Type

None

ContentLength

Int

Length of the response body

None

Key

StringObject key

None

BucketStringBucket name in the format of BucketName-APPID

None

Location

StringAddress of the requested resource

None

Extracting Blind Watermark
The image URL should be entered according to the blind watermark type:1. For a semi-blind watermark, the blind watermark image URL is required and must be the URL of the input image.
2. For a blind watermark, the blind watermark image URL is required and must be the URL of the watermark image.
3. For a text blind watermark, the blind watermark image URL is invalid and does not need to be entered.
The specified watermark image must:
1. Be stored in the same bucket as the input image.
2. Be accessible at a URL containing a COS domain name (CDN acceleration domain names such as
examplebucket-1250000000.file.myqcloud.com/shuiyin_2.png are not supported). If the image
watermark is set to privately readable, the URL must carry a signature.
3. Have a URL starting with http:// . Note that "http://" cannot be omitted or changed to "https://". For example,
examplebucket-1250000000.cos.ap-shanghai.myqcloud.com/shuiyin_2.png andhttps://examplebucket-1250000000.cos.ap-shanghai.myqcloud.com/shuiyin_2.png areinvalid watermark URLs.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1221 of 1869

Cloud Infinite

Sample code<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array(©2013-2022 Tencent Cloud. All rights reserved.

Page 1222 of 1869

Cloud Infinite'region' => $region,'schema' => 'https', // Protocol header, which is `http` by default'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$blindWatermarkTemplate = new Qcloud\\Cos\\ImageParamTemplate\\BlindWaterma$blindWatermarkTemplate->setPick();// Set to extract a blind watermark$blindWatermarkTemplate->setType(3);// Blind watermark type. Valid values:$blindWatermarkTemplate->setImage("imageUrl");// Set the blind watermark im$blindWatermarkTemplate->setText("Test");// Set the blind watermark text
$blindWatermarkTemplate->setLevel(3);// Blind watermark level, which only t$picOperationsTemplate = new \\Qcloud\\Cos\\ImageParamTemplate\\PicOperatio$picOperationsTemplate->setIsPicInfo(1);// Set whether to return the input$picOperationsTemplate->addRule($blindWatermarkTemplate, "resultobject");//$result = $cosClient->putObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'exampleobject','Body' => fopen('path/to/localFile', 'rb'),'PicOperations' => $picOperationsTemplate->queryString(),// Generate parame));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Type

Description

Required

BucketStringBucket name in the format of BucketName-APPID

YesStringObject key, which is the unique identifier of the object in thebucket. For example, if an object's access endpoint isexamplebucket-1250000000.cos.ap-

Yes

Key

guangzhou.myqcloud.com/doc/pic.jpg , its key is
doc/pic.jpg .
BodyFile/String

Uploaded content

Yes

PicOperations

Json/String

Persistent image processing information

Yes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1223 of 1869

Cloud Infinite

Guzzle\\Service\\Resource\\Model Object([structure:protected] =>[data:protected] => Array([Body] =>[ETag] => "698d51a19d8a121ce581499d7b701668"[RequestId] => NWQwOGRkNDdfMjJiMjU4NjRfNzVjXzEwNmVjY2M=[ContentLength] => 10000[Key] => exampleobject[Bucket] => examplebucket-1250000000©2013-2022 Tencent Cloud. All rights reserved.

Page 1224 of 1869

Cloud Infinite[Location] => examplebucket-1250000000.cos.ap-beijing.myqcloud.com/exam[Data] => Array([OriginalInfo] => Array([Key] => exampleobject[Location] => examplebucket-1250000000.cos.ap-beijing.myqcloud.
[ETag] => "7037fb6fb4cca43b958a28789605e73d98088720"[ImageInfo] => Array([Format] => JPEG
[Width] => 600[Height] => 500[Quality] => 90[Ave] => 0x46442e[Orientation] => 0))
[ProcessResults] => Array([Object] => Array([0] => Array([Key] => resultobject[Location] => examplebucket-1250000000.cos.ap-beijing.m[Format] => JPEG
[Width] => 300[Height] => 200[Size] => 30000[Quality] => 90[WatermarkStatus] => 90[ETag] => "87c153bc2909aa0ba111ca126b675c510d36b817"
)
)
)
)
)
)

Response description
Parameter

Type

Description

Parent Node

Body

File/String

Response bodyNone©2013-2022 Tencent Cloud. All rights reserved.

Page 1225 of 1869

Cloud Infinite

ETag

String

MD5 checksum of the file

None

RequestId

StringRequest ID

None

ContentLength

Int

Length of the response body

None

Key

StringObject key

None

BucketStringBucket name in the format of BucketName-APPID

None

Location

StringAddress of the requested resource

None

Data

Array

Image processing resultNone©2013-2022 Tencent Cloud. All rights reserved.

Page 1226 of 1869

Cloud Infinite

Image Advanced Compression：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for image advanced compression.
API

Description

Imageadvanced

Allows you to easily convert images into formats that provide a high compression ratio, such as
TPG and HEIF. This effectively reduces the transfer time, loading time, and the use ofcompression

bandwidth and traffic.

Image Advanced Compression
Feature description
CI uses the imageMogr2 API to provide the image advanced compression feature.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1227 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1228 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$imageMogrTemplate = new Qcloud\\Cos\\ImageParamTemplate\\ImageMogrTemplate$imageMogrTemplate->format('tpg');// Convert the input image to TPG format$imageMogrTemplate->format('heif');// Convert the input image to HEIF forma$result = $cosClient->getObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'exampleobject','ImageHandleParam' => $imageMogrTemplate->queryString(),// Generate basic i));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Type

Description

Required

BucketStringBucket name in the format of BucketName-APPID

YesStringObject key, which is the unique identifier of the object in thebucket. For example, if an object's access endpoint isexamplebucket-1250000000.cos.ap-

Yes

Key

guangzhou.myqcloud.com/doc/pic.jpg , its key is
doc/pic.jpg .
ImageHandleParamStringCI image processing parameters, such asimageMogr2/format/tpg .

Yes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1229 of 1869

Cloud Infinite

Guzzle\\Service\\Resource\\Model Object([structure:protected] =>[data:protected] => Array([Body] =>[ETag] => "698d51a19d8a121ce581499d7b701668"[RequestId] => NWQwOGRkNDdfMjJiMjU4NjRfNzVjXzEwNmVjY2M=[ContentLength] => 100[ContentType] => image/jpeg[Key] => exampleobject©2013-2022 Tencent Cloud. All rights reserved.

Page 1230 of 1869

Cloud Infinite[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.cos.ap-beijing.myqcloud.com/exam))

Response description
Parameter

Type

Description

Parent Node

Body

File/String

Downloaded content

None

ETag

String

MD5 checksum of the file

None

ContentLength

Int

Length of the response body

None

ContentType

StringContent type. Sets Content-Type

NoneRequestId

StringRequest ID

None

Key

StringObject key

None

BucketStringBucket name in the format of BucketName-APPID

None

Location

StringAddress of the requested resourceNone©2013-2022 Tencent Cloud. All rights reserved.

Page 1231 of 1869

Cloud Infinite

Guetzli Compression：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for Guetzli compression.
API

Description

Enabling Guetzli compression

Enables the Guetzli compression feature for a bucket.

Querying Guetzli status

Queries whether the Guetzli compression feature is enabled.

Disabling Guetzli compression

Disables the Guetzli compression feature.

Enabling Guetzli Compression
Feature description
This API is used to enable the Guetzli compression feature for a bucket.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1232 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1233 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->PutBucketGuetzli(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Type

Description

Required

BucketStringBucket name in the format of BucketName-APPID

Yes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1234 of 1869

Cloud Infinite

Guzzle\\Service\\Resource\\Model Object([structure:protected] =>[data:protected] => Array([RequestId] => NWQwOGRkNDdfMjJiMjU4NjRfNzVjXzEwNmVjY2M=[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.pic.ap-beijing.myqcloud.com/))©2013-2022 Tencent Cloud. All rights reserved.

Page 1235 of 1869

Cloud Infinite

Response description
Parameter

Type

Description

Parent NodeRequestId

StringRequest ID

None

BucketStringBucket name in the format of BucketName-APPID

None

Location

StringAddress of the requested resource

None

Querying Guetzli Status
Feature description
This API is used to query whether the Guetzli compression feature is enabled.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1236 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1237 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->GetBucketGuetzli(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Type

Description

Required

BucketStringBucket name in the format of BucketName-APPID

Yes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1238 of 1869

Cloud Infinite

Guzzle\\Service\\Resource\\Model Object([structure:protected] =>[data:protected] => Array([RequestId] => NWQwOGRkNDdfMjJiMjU4NjRfNzVjXzEwNmVjY2M=[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.pic.ap-beijing.myqcloud.com/[GuetzliStatus] => on))©2013-2022 Tencent Cloud. All rights reserved.

Page 1239 of 1869

Cloud Infinite

Response description
Parameter

Type

Description

Parent NodeRequestId

StringRequest ID

None

BucketStringBucket name in the format of BucketName-APPID

None

Location

StringAddress of the requested resource

None

GuetzliStatus

StringGuetzli status. Valid values: on, off.

None

Disabling Guetzli Compression
This API is used to disable the Guetzli compression feature.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1240 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1241 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->DeleteBucketGuetzli(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Type

Description

Required

BucketStringBucket name in the format of BucketName-APPID

Yes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1242 of 1869

Cloud Infinite

Guzzle\\Service\\Resource\\Model Object([structure:protected] =>[data:protected] => Array([RequestId] => NWQwOGRkNDdfMjJiMjU4NjRfNzVjXzEwNmVjY2M=[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.pic.ap-beijing.myqcloud.com/))©2013-2022 Tencent Cloud. All rights reserved.

Page 1243 of 1869

Cloud Infinite

Response description

Parameter

Type

Description

Parent NodeRequestId

StringRequest ID

None

BucketStringBucket name in the format of BucketName-APPID

None

Location

StringAddress of the requested resourceNone©2013-2022 Tencent Cloud. All rights reserved.

Page 1244 of 1869

Cloud Infinite

Media Processing
Media Bucket APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for querying the media processing activation
status.
API

Description

Querying media processing activation status

Queries media processing activation status

Querying Media Processing Activation Status
Feature description
This API is used to query buckets with media processing enabled.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1245 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model describeMediaBuckets(array $args = array())

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1246 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1247 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->describeMediaBuckets(array('Regions' => '', // Optional region information, such as `ap-shanghai` and'BucketNames' => '', // Optional bucket name. To specify multiple bucket na'BucketName' => '', // Optional bucket name prefix for prefix search'PageNumber' => 1, // Optional page number'PageSize' => 20, // Optional number of entries per page));// Request successful
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Name

Description

Type

Required

stringNo

string

No

Region information, such as ap-shanghai and ap-beijing .
regions

To specify multiple regions, separate them with commas. For more
information, see Regions and Domain Names.

bucketNames

Bucket name. To specify multiple bucket names, separate them withcommas. Exact search is supported.

bucketName

Bucket name prefix for prefix search.

stringNo

pageNumber

Page number.

stringNo

pageSize

Number of entries per page.

stringNo

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1248 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([RequestId] => NjI2MTE5OTlfNzgSxDxIHF0ZF8xZjk0MmQ=[ContentType] => application/xml[ContentLength] => 4744
[TotalCount] => 51[PageNumber] => 1
[PageSize] => 5
[MediaBucketList] => Array([0] => Array©2013-2022 Tencent Cloud. All rights reserved.

Page 1249 of 1869

Cloud Infinite([BucketId] => examplebucket-1250000000[Name] => examplebucket-1250000000[Region] => ap-guangzhou[CreateTime] => 2022-04-07T22:06:57+0800)[1] => Array([BucketId] => examplebucket-1250000000[Name] => examplebucket-1250000000[Region] => ap-guangzhou[CreateTime] => 2022-04-07T22:06:57+0800)[2] => Array([BucketId] => examplebucket-1250000000[Name] => examplebucket-1250000000[Region] => ap-guangzhou[CreateTime] => 2022-04-07T22:06:57+0800)[3] => Array([BucketId] => examplebucket-1250000000[Name] => examplebucket-1250000000[Region] => ap-guangzhou[CreateTime] => 2022-04-07T22:06:57+0800)[4] => Array([BucketId] => examplebucket-1250000000[Name] => examplebucket-1250000000[Region] => ap-guangzhou[CreateTime] => 2022-04-07T22:06:57+0800))[Location] => ci.ap-guangzhou.myqcloud.com/mediabucket)©2013-2022 Tencent Cloud. All rights reserved.

Page 1250 of 1869

Cloud Infinite

Media Information APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides code samples for getting media file information.
Note:
COS PHP SDK v2.3.2 or later is required. Earlier versions may contain bugs and need to be upgraded to the latest
version when used.
API

Operation

Description

GetMediaInfo

Querying file information

Queries media file information

Querying File Information
Feature description
This API is used to query the information of a media file.
Note:
Before using this API, make sure that the media processing feature has been enabled in the data processing sectionin the console; otherwise, the error media bucket unbinded, bucket's host is unavailable will bereported.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1251 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1252 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->GetMediaInfo(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of'Key' => 'exampleobject', // Media file object path, such as `folder/mo'ci-process' => 'videoinfo' // Operation type, which is fixed at `video));// Request successfulecho($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Description

Type

Required

BucketBucket name in the format of BucketName-APPID .

StringYes

StringYes

StringYes

Keyci-process

Object key (object name), which is the unique identifier of the object (amedia file here) in the bucket. For more information, see Object Overview.
Operation type, which is fixed at videoinfo .

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1253 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([RequestId] => NjE0NTkxMWNfYTkyZTJjMGJfNTgyZF84ZDY2NWY=[ContentType] => application/xml[ContentLength] => 1787
[MediaInfo] => Array([Stream] => Array([Audio] => Array(©2013-2022 Tencent Cloud. All rights reserved.

Page 1254 of 1869

Cloud Infinite[Bitrate] => 383.727000[Channel] => 6
[ChannelLayout] => 5.1[CodecLongName] => AAC (Advanced Audio Coding)[CodecName] => aac[CodecTag] => 0x6134706d[CodecTagString] => mp4a
[CodecTimeBase] => 1/48000[Duration] => 62.314667[Index] => 1
[Language] => und[SampleFmt] => fltp
[SampleRate] => 48000[StartTime] => 0.000000[Timebase] => 1/48000)[Subtitle] => Array()[Video] => Array([CodecTagString] => avc1
[Rotation] => 0.000000[Index] => 0
[CodecName] => h264
[CodecLongName] => H.264 / AVC / MPEG-4 AVC / MPEG-4 pa[CodecTimeBase] => 1/12800[CodecTag] => 0x31637661[Profile] => Main
[Height] => 720[Width] => 1280
[HasBFrame] => 0
[RefFrames] => 1
[Sar] => 1:1[Dar] => 16:9
[PixFormat] => yuv420p[Level] => 31[Fps] => 25.500000[AvgFps] => 25/1
[Timebase] => 1/12800[StartTime] => 0.000000[Duration] => 62.280000[Bitrate] => 959.963000[NumFrames] => 1557
[Language] => und©2013-2022 Tencent Cloud. All rights reserved.

Page 1255 of 1869

Cloud Infinite))[Format] => Array([NumStream] => 2
[NumProgram] => 0
[FormatName] => mov,mp4,m4a,3gp,3g2,mj2[FormatLongName] => QuickTime / MOV[StartTime] => 0.000000[Duration] => 62.315000[Bitrate] => 1347.820000[Size] => 10498677))[Key] => exampleobject[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/exampleobj)©2013-2022 Tencent Cloud. All rights reserved.

Page 1256 of 1869

Cloud Infinite

Media Screenshot APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides code samples for screencapturing a media file at some time point.
Note:
COS PHP SDK v2.3.2 or later is required. Earlier versions may contain bugs and need to be upgraded to the latest
version when used.
API

Operation

Description

GetSnapshot

Querying screenshot

Query the screenshot of media file at some time point

Querying Screenshot
Feature description
This API is used to query the screenshot of a media file at some time point.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1257 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1258 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));$time = 3.14; // Video frame capturing time pointtry {$result = $cosClient->getSnapshot(
array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of'Key' => 'exampleobject', // Media file object path, such as `folder/mo'ci-process' => 'snapshot', // Operation type, which is fixed at `snaps'Time' => $time, // Video frame capturing time point'SaveAs' => '/data/test.jpg', // Local path to save the screenshot));// Request successfulecho($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Description

Type

Required

BucketBucket name in the format of BucketName-APPID .

StringYes

Key

Object key (object name), which is the unique identifier of the object (amedia file here) in the bucket. For more information, see Object Overview.

StringYes

ci-process

Operation type, which is fixed at snapshot .

StringYes

Time

Video frame capturing time point.

float

Yes

SaveAsLocal path to save the screenshot.

StringYes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1259 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([Body] => GuzzleHttp\\Psr7\\Stream Object([stream:GuzzleHttp\\Psr7\\Stream:private] => Resource id #91[size:GuzzleHttp\\Psr7\\Stream:private] =>[seekable:GuzzleHttp\\Psr7\\Stream:private] => 1
[readable:GuzzleHttp\\Psr7\\Stream:private] => 1
[writable:GuzzleHttp\\Psr7\\Stream:private] => 1
[uri:GuzzleHttp\\Psr7\\Stream:private] => php://temp[customMetadata:GuzzleHttp\\Psr7\\Stream:private] => Array©2013-2022 Tencent Cloud. All rights reserved.

Page 1260 of 1869

Cloud Infinite())[ContentLength] => 153613[ContentType] => image/jpeg[RequestId] => NjE0NThmNGNfNWIyZjJjMGJfNTE1MV84YmJlODI=[Key] => exampleobject[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/exampleobj)©2013-2022 Tencent Cloud. All rights reserved.

Page 1261 of 1869

Cloud Infinite

Private M3U8 APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for the private M3U8 API.
API

Description

GetPrivateM3U8

Gets the download authorization for M3U8 and TS resources (requests are forwarded to CI
by COS).

GetPrivateM3U8
Feature description
This API is used to get the download authorization for M3U8 and TS resources (requests are forwarded to CI by
COS).
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1262 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model getPrivateM3U8(array $args = array());

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1263 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1264 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->GetPrivateM3U8(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'xxx.m3u8', // Bucket file'ci-process' => 'pm3u8', // Operation type, which is fixed at `pm3u8`'expires' => '3600', // Relative validity period of the download credential));// Request successful
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Parameter

Description

Type

Required

ci-process

Operation type, which is fixed at pm3u8 .

StringYes

expires

Relative validity period of the download credential for the private TS
resource URL in seconds. Value range: [3600, 43200].

StringYes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1265 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([Body] => GuzzleHttp\\Psr7\\Stream Object([stream:GuzzleHttp\\Psr7\\Stream:private] => Resource id #89[size:GuzzleHttp\\Psr7\\Stream:private] =>[seekable:GuzzleHttp\\Psr7\\Stream:private] => 1
[readable:GuzzleHttp\\Psr7\\Stream:private] => 1
[writable:GuzzleHttp\\Psr7\\Stream:private] => 1
[uri:GuzzleHttp\\Psr7\\Stream:private] => php://temp[customMetadata:GuzzleHttp\\Psr7\\Stream:private] => Array©2013-2022 Tencent Cloud. All rights reserved.

Page 1266 of 1869

Cloud Infinite())[RequestId] => NjI2MTFjYSDHIUsdsdSJDOIDTRfMjVjYzcw[ContentType] => application/x-mpegURL[ContentLength] => 4310
[Key] => xxx.m3u8[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.cos.ap-beijing.myqcloud.com/xxx.m3u8[Data] => M3U8 file content)©2013-2022 Tencent Cloud. All rights reserved.

Page 1267 of 1869

Cloud Infinite

Queue APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for media processing queues.
API

Description

Searching for media processing queues

Searches for media processing queues.

Updating a media processing queue

Updates a media processing queue.

Searching for Media Processing Queues
Feature description
This API is used to search for media processing queues.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1268 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model describeMediaQueues(array $args = array());

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1269 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; //Replace it with the actual `region`, which can be viewed$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1270 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// https://cloud.tencent.com/document/product/436/54045: Searching for Media Pr

//
//
//
//

$result = $cosClient->describeMediaQueues(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'QueueIds' => '', // Queue ID (optional). If you enter multiple IDs, sepa
'Category' => 'Transcoding', // Category (optional). `CateAll`: All types'State' => 'Paused', // Status (optional). 1. `Active`: Jobs in the queue'PageNumber' => '1', // Page number (optional)//'PageSize' => '2', // Number of entries per page (optional)));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request parameters are as described below:
Parameter Name
(Keyword)

Description

Type

Required

QueueIds

Queue ID. If you enter multiple IDs, separate them by comma.

StringNo

StringNo

StringNo

Active : Jobs in the queue will be scheduled and executed
Stateby the media processing service.
Paused : The queue is paused, and jobs in it will no longer bescheduled and executed. All jobs in the queue will remain in the
Paused status, while jobs being executed will not be affected.
CateAll : All types. <li> Transcoding : Media

Category

processing queue.
SpeedTranscoding : Media processing and accelerated
transcoding queue. <li> Default value: Transcoding .

PageNumber

Page number. Default value: 1 .

StringNo

PageSize

Number of entries per page. Default value: 10 .

StringNo

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1271 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([RequestId] => NjNkOGM2NmVfZTYxNmY5MSAASJPOJCIANSIDNAI=[ContentType] => application/xml[ContentLength] => 751[TotalCount] => 1
[PageNumber] => 1
[PageSize] => 10[QueueList] => Array([0] => Array©2013-2022 Tencent Cloud. All rights reserved.

Page 1272 of 1869

Cloud Infinite([BucketId] => examplebucket-1250000000[QueueId] => pcc3ae89sa9d807fs89dg789sdg[Name] => queue-1[State] => Active[MaxSize] => 10000[MaxConcurrent] => 10[Category] => Transcoding[UpdateTime] => 2022-07-13T10:41:34+0800[CreateTime] => 2022-07-13T10:41:34+0800[NotifyConfig] => Array([Url] =>
[State] => Off[Type] =>[Event] =>[ResultFormat] => XML)))[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-guangzhou.myqcloud.com/queue)

Updating a Media Processing Queue
Feature description
This API is used to update a media processing queue.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1273 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model updateMediaQueue(array $args = array());

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1274 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; //Replace it with the actual `region`, which can be viewed$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1275 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// https://cloud.tencent.com/document/product/436/54046: Updating Media Process$result = $cosClient->updateMediaQueue(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'xxx', // queueId'Name' => '', // Template name. Length limit: 100 characters.
'State' => 'Active', // Pipeline status'NotifyConfig' => array('State' => 'Off','Event' => '','ResultFormat' => '','Type' => '','Url' => '','MqMode' => '','MqRegion' => '',

//
//
//
//
//
//
//

'MqName' => '',),));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description

Type

Required

Default
Value

Restrictions

Name

RequestQueue name (up to
128 characters).

String

Yes

None.

None.

State

RequestActive : Jobs inString

Yes

None.

None.

the queue will bescheduled andexecuted by the media
processing service.
Paused : The
queue is paused, andjobs in it will no longer©2013-2022 Tencent Cloud. All rights reserved.

Page 1276 of 1869

Cloud Infinite

be scheduled andexecuted. All jobs inthe queue will remainin the Paused
status, while jobs
being executed will not
be affected.
NotifyConfig

RequestCallback configuration

Container

Yes

None.

None.

NotifyConfig has the following sub-nodes:
Node Name(Keyword)

State

Parent NodeRequest.NotifyConfig

Description
Callback
switch.
Validvalues:
Off ,

Type

Required

String

No

Default
Value

Off

Restrictions

On/Off

On .

Event

Request.NotifyConfig

Callback
event

StringYes if
State

None.

is On .

Job completed:
TaskFinish;workflowcompleted:
WorkflowFinish.

ResultFormat

Type

Request.NotifyConfig

Callback
formatRequest.NotifyConfig

Callback
type

StringNo

XML

JSON/XML

StringYes if
State

None.

URL or TDMQ

is On .
Yes ifState

Url

Request.NotifyConfig

Callback
Address

String

is On
and
Type

The callback
None.

is Url .
MqModeRequest.NotifyConfig

TDMQ
queue
mode

StringYes if
State
is On
and

©2013-2022 Tencent Cloud. All rights reserved.

Queueaddress cannot
be a private
networkaddress.

Topic: Topic
subscription.
Queue: Queue
service.

Page 1277 of 1869

Cloud Infinite

Type
is
TDMQ .
Valid values:shYes ifState
MqRegion

Request.NotifyConfig

TDMQ
region(Shanghai),bj (Beijing),

is On
String

and
Type

None.

is

gz
(Guangzhou),cd(Chengdu),
hk (Hong

TDMQ .

Kong, China).
Yes ifState
MqNameRequest.NotifyConfig

TDMQ
topic nameis On
String

and
Type

None.

None.

is
TDMQ .

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1278 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([Body] => GuzzleHttp\\Psr7\\Stream Object([stream:GuzzleHttp\\Psr7\\Stream:private] => Resource id #88[size:GuzzleHttp\\Psr7\\Stream:private] =>[seekable:GuzzleHttp\\Psr7\\Stream:private] => 1
[readable:GuzzleHttp\\Psr7\\Stream:private] => 1
[writable:GuzzleHttp\\Psr7\\Stream:private] => 1
[uri:GuzzleHttp\\Psr7\\Stream:private] => php://temp[customMetadata:GuzzleHttp\\Psr7\\Stream:private] => Array©2013-2022 Tencent Cloud. All rights reserved.

Page 1279 of 1869

Cloud Infinite())[RequestId] => NjNkOGM2NmVfZTYxNmY5MSAASJPOJCIANSIDNAI=[ContentType] => application/xml[ContentLength] => 668[Key] => fcd32dbdaa13b11esa9ds8g0d98gd0h85[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-guangzhou.myqcloud.com/queue/fcd32[Response] => Array([RequestId] => NjNkOGM2NmVfZTYxNmY5MSAASJPOJCIANSIDNAI=[Queue] => Array([QueueId] => fcd32dbdaa13b11esa9ds8g0d98gd0h85[Name] => media-queue-1[State] => Active[NotifyConfig] => Array([Url] =>
[Event] =>[Type] =>[State] => Off[ResultFormat] => XML[MqMode] =>[MqName] =>[MqRegion] =>)[MaxSize] => 10000[MaxConcurrent] => 10[CreateTime] => 2022-07-13T10:41:34+0800[UpdateTime] => 2023-01-31T17:32:18+0800[BucketId] => examplebucket-1250000000[Category] => Transcoding)))©2013-2022 Tencent Cloud. All rights reserved.

Page 1280 of 1869

Cloud Infinite

File Processing
Querying File Preview Feature Status：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for querying the file preview feature status.
API

Description

Querying file preview feature status

Queries whether the file preview feature is enabled for a bucket.

Querying File Preview Feature Status
Feature description
This API is used to query the buckets with the file preview feature enabled.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1281 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model describeDocProcessBuckets(array $args = arr

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1282 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; //Replace it with the actual `region`, which can be viewed$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', //Protocol header, which is http by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1283 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// Query the file preview feature status. For more information, visit https://c$result = $cosClient->describeDocProcessBuckets(array('Regions' => '', // Optional region information, such as `ap-shanghai` and'BucketNames' => '', // Bucket name (optional). To specify multiple bucket'BucketName' => '', // Optional bucket name prefix for prefix search'PageNumber' => 1, // Optional page number'PageSize' => 20, // Optional number of entries per page));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Name
Regions

Description
Region. Separate multiple regions by comma. Valid values: All ,ap-shanghai , ap-beijing .

Type

Required

stringNo

BucketNames

Bucket name. Separate multiple bucket names by comma. Exact
search is supported.

stringNo

BucketName

Bucket name prefix. Prefix search is supported.

stringNo

PageNumber

Page number

stringNo

PageSize

Number of entries per pagestringNo

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1284 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([RequestId] => NjMxMDcwZDlfAHDKAJHSDKJASHDKY3[ContentType] => application/xml[ContentLength] => 4600
[TotalCount] => 59[PageNumber] => 1
[PageSize] => 3
[DocBucketList] => Array([0] => Array©2013-2022 Tencent Cloud. All rights reserved.

Page 1285 of 1869

Cloud Infinite([BucketId] => xxx-123[Name] => xxx-123[Region] => ap-chongqing[CreateTime] => 2022-08-30T10:41:31+0800[AliasBucketId] =>)[1] => Array([BucketId] => xxx-123[Name] => xxx-123[Region] => ap-chongqing[CreateTime] => 2022-08-30T10:41:31+0800[AliasBucketId] =>)[2] => Array([BucketId] => xxx-123[Name] => xxx-123[Region] => ap-chongqing[CreateTime] => 2022-08-30T10:41:31+0800[AliasBucketId] =>))[Location] => ci.ap-guangzhou.myqcloud.com/docbucket)©2013-2022 Tencent Cloud. All rights reserved.

Page 1286 of 1869

Cloud Infinite

File Transcoding
Sync Request API：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for file preview.
API

Operation

Description

File transcoding

Getting the request URL for file transcoding

Gets the request URL for file transcoding

Sync File Transcoding
Feature description
This API is used to get the request URL for file transcoding.
Note:
Before using this API, make sure that the file processing feature has been enabled in the data processing section in
the console; otherwise, the error doc bucket unbinded, bucket's host is unavailable will bereported.
To use the file to HTML conversion feature, directly put the request parameters after the URL. The SDK is only
responsible for calculating the signature.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1287 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; //Replace it with the actual `region`, which can be viewed$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', //Protocol header, which is http by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1288 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// 1. For more information on file transcoding, visit https://cloud.tencent.com$bucket = 'examplebucket-1250000000';//$key = 'exampleobject';$url = $cosClient->getObjectUrl($bucket, $key);$params = array('ci-process' => 'doc-preview','srcType' => '','page' => 3,

//
//
//
//
//
//
//
//
//
//
//

'dstType' => 'png','password' => '','comment' => '','sheet' => '','excelPaperDirection' => '','excelRow' => '','excelCol' => '','excelPaperSize' => '','txtPagination' => '','ImageParams' => 'imageMogr2/thumbnail/!50p','quality' => '','scale' => '','imageDpi' => '',);$query = http_build_query($params);
echo $url . $query; // The generated accessible URL} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Common request parameters
Parameter

Description

Type

RequiredKey

Object name, such as folder/document.pdf .

StringYes

StringYes

StringNo

ci-process

srcTypeCI's processing capability, which is fixed at doc-preview forfile preview.
Source data type. Currently, the file conversion feature determines
the source data type according to the file extension of the COS
object. If the object has no extension, you can set this value.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1289 of 1869

Cloud Infinite

page

Number of the page to be converted, which is counted from 1 by

Int

No

StringNo

String

No

Int

No

default. For spreadsheets, page indicates to convert the xth
image in the xth sheet.
Type of the output target file. Valid values: png , jpg , pdf
dstType(the page number cannot be selected, and the page parameter
does not take effect), txt . If the input file format cannot berecognized, the jpg format will be used by default.

password

Password to open the Office file. If you need to convert a passwordprotected file, set this field.
Whether to hide comments and apply track changes. 0 : Hidecomment

comments and apply track changes. 1 : Show comments andtrack changes. Default value: 0 .

Parameters for spreadsheet files (Excel)
HeaderDescription

Type

Required

sheet

Sheet parameter, indicating to convert the xth sheet.
Default value: 1 .

Int

No

Int

No

Int

No

Int

No

Int

No

excelPaperDirection

excelRow

excelCol

Paper orientation of the spreadsheet. 0 : vertical; othervalues: horizontal. Default value: 0 .
The value 1 indicates that all rows will be formatted on
one page. Default value: 0 .
The value 1 indicates that all columns will be formatted
on one page. Default value: 0 .
Paper (canvas) size. Valid values: 0 (A4), 1 (A2),excelPaperSize

2 (A0). Default value: 0 . This parameter should be
used together with excelRow or excelCol .

Parameters for transcoding into .txt files
Parameter

Description

Type

Required

Bool

No

Whether to convert to long text. When this parameter is set totrue , the text in the pages to be exported can be combined before
txtPagination

export, and the pagination range can be controlled by Ranges .
The default value is false , indicating to generate .txt files by
page. This parameter takes effect only if ExportType is txt .

©2013-2022 Tencent Cloud. All rights reserved.

Page 1290 of 1869

Cloud Infinite

Parameters for transcoding to .png/.jpg images
Name

ImageParams

quality

Description
Processing parameters for the output image. All parameters of basic
image processing are supported. To specify multiple parameters,
separate them with pipeline operators. In this way, the image can beprocessed by multiple parameters in sequence in the same request.
Quality of the generated preview image. Value range: [1, 100]. Default
value: 100 . For example, if the value is 100 , the quality of theType

Required

String

No

Int

No

Int

No

Int

No

generated image will be 100%.

scale

Scaling parameter of the preview image. Value range: [10, 200].
Default value: 100 . For example, if the value is 200 , the image
will be scaled up (enlarged) by 200%.

imageDpi

Renders the image based on the specified DPI. This parameter works
together with scale . Value range: 96–600. Default value: 96 .
The width of the output image must be less than 65500 px.

Note:
Currently supported input file types include:
Presentation files: PPTX, PPT, POT, POTX, PPS, PPSX, DPS, DPT, PPTM, POTM, PPSM.
Text files: DOC, DOT, WPS, WPT, DOCX, DOTX, DOCM, DOTM.
Spreadsheet files: XLS, XLT, ET, ETT, XLSX, XLTX, CSV, XLSB, XLSM, XLTM, ETS.
A spreadsheet file may be split into multiple pages, with multiple images generated.
Other files: PDF, LRC, C, CPP, H, ASM, S, JAVA, ASP, BAT, BAS, PRG, CMD, RTF, TXT, LOG, XML, HTM, HTML.
The input file size cannot exceed 200 MB.
The number of pages in the input file cannot exceed 5,000.
Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1291 of 1869

Cloud Infinite

Sync request URL
https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/example.ppt?sign=q-s©2013-2022 Tencent Cloud. All rights reserved.

Page 1292 of 1869

Cloud Infinite

Async Processing Job APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for async processing jobs.
Note:
COS PHP SDK v2.4.0 or later is required. Earlier versions may contain bugs and need to be upgraded to the latest
version when used.
API

Operation

Description

CreateDocProcessJobs

Submitting a file preview job

Submits a file preview job.

DescribeDocProcessJob

Querying file preview job

Queries specified file preview job.

DescribeDocProcessJobs

Pulling file preview jobs

Pulls eligible file preview jobs.

Submitting File Preview Job
Feature description
This API ( CreateDocProcessJobs ) is used to submit a file preview job.
Note:
Before using this API, make sure that the file processing feature has been enabled in the data processing section in
the console; otherwise, the error doc bucket unbinded, bucket's host is unavailable will bereported.
To use the file to HTML conversion feature, directly put the request parameters after the URL. The SDK is only
responsible for calculating the signature.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1293 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; //Replace it with the actual `region`, which can be viewed$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', //Protocol header, which is http by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1294 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->createDocProcessJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'DocProcess', // Job tag: DocProcess'QueueId' => 'pd8e422a2ea134165a92f2012ea43****', // Queue ID of the job'Input' => array('Object' => 'Append Test Feature.pdf' // The object to be processed),'Operation' => array('DocProcess' => array('SrcType' => 'pdf', // Source file extension'TgtType' => 'png', // Target file extension'SheetId' => 0, // Sheet parameter, indicating to convert the xth s'StartPage' => 1, // Start page number, indicating to convert the f'EndPage' => 3, // End page number, indicating to convert the file
'ImageParams' => '', // Image processing parameters after the conve'DocPassword' => '', // Office file password'Comments' => 0, // Whether to hide comments and apply track change'PaperDirection' => 0, // Paper orientation of the spreadsheet. Def'Quality' => 100, // Quality of the generated preview image. Value'Zoom' => 100, // Scaling parameter of the preview image. Value ran),'Output' => array('Region' => $region, // Bucket region'Bucket' => 'examplebucket-1250000000', // Result storage bucket'Object' => 'pic-${Page}.jpg', // Output file path
),
),
));
// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Parameter NameType

Description

Required

BucketStringBucket name in the format of BucketName-APPID

Yes©2013-2022 Tencent Cloud. All rights reserved.

Page 1295 of 1869

Cloud Infinite

Operation

Array

Operation rule

Yes

Tag

StringJob tag, which currently can only be DocProcess .

Yes

Input

Array

The object to be processed

Yes

QueueId

StringQueue ID of the job

Yes

Input has the following sub-nodes:
Parameter NameType

Description

ObjectFile URL in COS. Bucket is specified by Host .

Yes

RequiredOperation has the following sub-nodes:
Parameter
Name

Type

Description

Required

DocProcess

Array

Specifies the parameter for the job, which takes effect only if
Tag is DocProcess .

Yes

OutputArray

Result output address

Yes

DocProcess has the following sub-nodes:
Parameter
Name

Type

Description

Required

Source data type. Currently, the file conversion featuresrcType

Stringdetermines the source data type according to the file extensionof the COS object. If the object has no extension, you can set
this value.

No

Type of the output target file. Valid values: png , jpg ,tgtType

StringsheetId

IntegerstartPage

Integer

pdf . If the input file format cannot be recognized, the jpg
format will be used by default. You cannot specify pages for the
pdf format.
Sheet parameter, indicating to convert the xth sheet. Default
value: 1 . If it is set to 0 , all sheets will be converted.

No

No

Starts conversion from page X. A spreadsheet file may be split
into multiple pages, with multiple images generated, andStartPage indicates to start the conversion from page X ofNo

the specified SheetId . Default value: 1 .

©2013-2022 Tencent Cloud. All rights reserved.

Page 1296 of 1869

Cloud Infinite

endPage

IntegerEnds conversion on page X. A spreadsheet file may be split into
multiple pages, with multiple images generated, andEndPage indicates to end the conversion on page X of theNo

specified SheetId . Default value: -1 (converting all
pages).

imageParams

StringProcessing parameters for the output image. All parameters ofbasic image processing are supported. To specify multiple
parameters, separate them by pipeline operator. In this way, theimage can be processed by multiple parameters in sequence inNothe same request.
StringPassword to open the Office file. If you need to convert apassword-protected file, set this field.

Nocomments

Integer

Whether to hide comments and apply track changes. 0: hidecomments and apply track changes; 1: show comments andtrack changes. Default value: 0 .

NopaperDirection

IntegerdocPassword

quality

IntegerPaper orientation of the spreadsheet. 0 : vertical; otherNovalues: horizontal. Default value: 0 .
Quality of the generated preview image. Value range: [1-100].
Default value: 100 . For example, if the value is 100 , theNo

quality of the generated image will be 100%.

zoom

Integer

Scaling parameter of the preview image. Value range: [10,200]. Default value: 100 . For example, if the value is 200 ,No

the image will be scaled up (enlarged) by 200%.

Output has the following sub-nodes:
Parameter NameType

Description

RequiredRegionStringBucket region

Yes

BucketStringResult storage bucket

Yes

ObjectStringOutput file path

Yes

Response parameters
Parameter

Type

Description

CodeStringError code, which will be meaningful only if State is Failed .

©2013-2022 Tencent Cloud. All rights reserved.

Page 1297 of 1869

Cloud Infinite

Message

StringError description, which will be meaningful only if State is Failed .

JobId

StringJob ID

Tag

StringJob tag: DocProcess

State

StringCreationTime

StringJob creation time

QueueId

StringID of the queue which the job is in

Input

Array

Input file path of the job

Operation

Array

Operation rule

Job status. Valid values: Submitted , Running , Success , Failed ,Pause , Cancel .

Querying Specified File Preview Job
Feature description
This API ( DescribeDocProcessJob ) is used to query a specified file preview job.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1298 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; //Replace it with the actual `region`, which can be viewed$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', //Protocol header, which is http by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1299 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->describeDocProcessJob(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'examplejobid', // JobId));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Type

Description

Bucket

COS bucket name

StringKey

Job ID

StringParameter

Type

Description

jobsDetailJob details

Array

Response parameters

Pulling File Preview Job
Feature description
The API ( DescribeDocProcessJobs ) is used to pull file preview jobs that meet specified conditions.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1300 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; //Replace it with the actual `region`, which can be viewed$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', //Protocol header, which is http by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1301 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->getDescribeDocProcessJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu

//
//
//
//

'QueueId' => 'pd8e422a2ea134165a92f2012ea43****', // ID of the queue from w'Tag' => 'DocProcess', // Job tag: DocProcess'NextToken' => '143486', // Context token for pagination'OrderByTime' => 'Desc', // `Desc` (default) or `Asc`'Size' => 2, // Maximum number of jobs that can be pulled. Default value: `'States' => 'All', // Status of the jobs to pull. If you enter multiple job////'StartCreationTime' => '2021-10-10T16:20:07+0800', // Start time of the tim'EndCreationTime' => '2021-10-10T16:20:07+0800', // End time of the time ra));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Type

Description

Required

BucketString

COS bucket name

Yes

QueueId

StringID of the queue from which jobs are pulled

Yes

Tag

StringJob tag: DocProcess

Yes

OrderByTime

StringDesc (default) or Asc

No

NextToken

StringContext token for pagination

No

Size

IntegerMaximum number of jobs that can be pulled. The default value
is 10. The maximum value is 100.

No

StatesStringStatus of the jobs to pull. If you enter multiple job statuses,
separate them by comma. Valid values: All (default),
Submitted , Running , Success , Failed ,No

Pause , Cancel .
StartCreationTime

StringStart time of the time range for job pulling in the format of%Y-%m-%dT%H:%m:%S%z .

©2013-2022 Tencent Cloud. All rights reserved.

No

Page 1302 of 1869

Cloud Infinite

EndCreationTime

String

End time of the time range for job pulling in the format of %Y-No%m-%dT%H:%m:%S%z .

Response parameters
Parameter

Type

Description

JobDetail

Array

List of job details

nextToken

StringContext token for pagination©2013-2022 Tencent Cloud. All rights reserved.

Page 1303 of 1869

Cloud Infinite

Async Processing Queue APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for async processing queues.
API

Operation

Description

DescribeDocProcessQueues

Querying file transcoding queues

Queries file transcoding queues.

UpdateDocProcessQueue

Querying file transcoding queues

Queries file transcoding queues.

Querying File Transcoding Queue
Feature description
This API ( DescribeDocProcessQueues ) is used to query the file transcoding queue. It can also be used to get
the ID of the queue where the specified bucket is in.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1304 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; //Replace it with the actual `region`, which can be viewed$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', //Protocol header, which is http by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1305 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->describeDocProcessQueues(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Type

Description

Bucket

COS bucket name

StringResponse parameters
Response has the following sub-nodes:
Parameter

Type

Description

RequestId

StringUnique ID of the request

TotalCount

Integer

Total number of queues

PageNumber

IntegerCurrent page number. Same as pageNumber in the request.

PageSize

IntegerNumber of entries per page. Same as pageSize in the request.

QueueList

Array

Queue array

QueueList has the following sub-nodes:
Parameter

Type

Description

QueueId

StringQueue ID

Name

StringQueue name

State

StringCurrent status: Active or Paused

NotifyConfig

Array

Callback configuration©2013-2022 Tencent Cloud. All rights reserved.

Page 1306 of 1869

Cloud Infinite

MaxSize

IntegerMaximum queue length

MaxConcurrent

IntegerMaximum number of concurrent jobs in the current queue

UpdateTime

StringUpdate time

CreateTime

StringCreation time

NotifyConfig has the following sub-nodes:
Parameter

Type

Description

Url

StringCallback address

State

StringStatus: On or Off

Type

StringCallback type: Url

Event

String

The event that triggers the callback

Updating File Transcoding Queue
Feature description
This API ( UpdateDocProcessQueue ) is used to update a file transcoding queue.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1307 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; //Replace it with the actual `region`, which can be viewed$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', //Protocol header, which is http by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1308 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// Update the file transcoding queue as instructed at https://cloud.tencent.com$result = $cosClient->updateDocProcessQueue(array('Bucket' => 'examplebucket-125000000', // Bucket name in the format of `Buc
'Key' => '', // QueueID'Name' => '','QueueID' => '','State' => '','NotifyConfig' => array('Url' => '','Type' => '','Event' => '','State' => '',),));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description

Type

RequiredConstraints

NameRequestQueue name

StringYes

Up to 100 characters

QueueID

RequestQueue ID

StringYes

None
1. Active: Jobs in the queue will

State

RequestQueue status

StringYes

be scheduled and executed by
the file preview service.
2. Paused: The queue ispaused, and jobs in it will nolonger be scheduled andexecuted. All jobs in the queue
will remain in the Submitted
status, while jobs being
executed will continue without
being affected.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1309 of 1869

Cloud Infinite

NotifyConfig

RequestNotification
channelContainer

Yes

Third-party callback URL

NotifyConfig has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeDescription

Type

RequiredConstraints

Url

Request.NotifyConfig

Callback configuration

StringNo

Up to 100
characters

Type

Request.NotifyConfig

Callback type. General
callback: Url .

StringNo

Up to 100
characters

Event

Request.NotifyConfig

Callback event: Filepreview job completed.

StringNo

Up to 100
characters

State

Request.NotifyConfig

StringNo

Up to 100
characters

Callback status: Offor On .

Response parameters
Response has the following sub-nodes:
Node Name

Parent(Keyword)

NodeRequestId
Queue

Description

Type

Response

Unique ID of the request

StringResponse

Queue information. For more information, see
Response.QueueList in DescribeDocProcessQueues.

Container©2013-2022 Tencent Cloud. All rights reserved.

Page 1310 of 1869

Cloud Infinite

File-to-HTML Conversion：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for file preview.
API

Operation

Description

File-to-HTML

Getting the request URL for file-to-HTML

Gets the request URL for file-to-HTMLconversion

conversion

conversion.

File-to-HTML Conversion
Feature description
This API is used to get the request URL for file-to-HTML conversion.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1311 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; //Replace it with the actual `region`, which can be viewed$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', //Protocol header, which is http by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1312 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// 2. Convert the file to HTML. For more information, visit https://cloud.tence$bucket = 'examplebucket-1250000000';//$key = 'exampleobject';$url = $cosClient->getObjectUrl($bucket, $key, "+30 minutes");$params = array('ci-process' => 'doc-preview','srcType' => '','dstType' => 'html',

//
//
//
//
//
//
//

'sign' => '','copyable' => '','htmlParams' => '','htmlwaterword' => '','htmlfillstyle' => '','htmlfront' => '','htmlrotate' => '',////'htmlhorizontal' => '','htmlvertical' => '',);$query = http_build_query($params);
echo $url . $query; // The generated accessible URL} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Name

Description

Type

RequiredKey

Object filename, such as folder/document.pdf .

StringYes

StringYes

StringYes

ci-process

dstTypeCI's processing capability, which is fixed at doc-preview forfile preview in HTML.
Output target file type, which is fixed at html for HTMLpreview.

srcType

Source file type as listed below.

StringNo

sign

Object download signature, which must be URL-encoded. If thepreviewed object is privately readable, the signature needs to be

StringNo

passed in.
For more information, see Request Signature.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1313 of 1869

Cloud Infinite

copyable

htmlParams

Whether the file content is copyable. Valid values: 1 (yes), 0(no).
Custom configuration parameters in JSON structure, which must
be URL-safe Base64-encoded as described in FAQs. Default
configuration: { commonOptions: { isShowTopArea: true,

StringNo

StringNo

isShowHeader: true } }. For supported configurations, see Custom
Configuration Overview.
htmlwaterword

Watermark text, which must be URL-safe Base64-encoded as
described in FAQs and is empty by default.

StringNo

htmlfillstyle

Watermark RGBA (color and transparency), which must be URLsafe Base64-encoded as described in FAQs and isrgba(192,192,192,0.6) by default.

StringNo

StringNo

htmlfront

Watermark text style, which must be URL-safe Base64-encoded
as described in FAQs and is bold 20px Serif by default.

htmlrotate

Rotation angle of the watermark text in degrees. Value range: 0–360. Default value: 315 .

StringNo

htmlhorizontal

Horizontal spacing of the watermark text in px. Default value:
50 .

StringNo

htmlvertical

Vertical spacing of the watermark text in px. Default value: 100 .

StringNo

Note:Currently supported input file types include:
Presentation files: PPTX, PPT, POT, POTX, PPS, PPSX, DPS, DPT, PPTM, POTM, PPSM.
Text files: DOC, DOT, WPS, WPT, DOCX, DOTX, DOCM, DOTM.
Spreadsheet files: XLS, XLT, ET, ETT, XLSX, XLTX, CSV, XLSB, XLSM, XLTM, ETS.
Other files: PDF, LRC, C, CPP, H, ASM, S, JAVA, ASP, BAT, BAS, PRG, CMD, RTF, TXT, LOG, XML, HTM, HTML.
The input file size cannot exceed 200 MB.
The number of pages in the input file cannot exceed 5,000.
Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1314 of 1869

Cloud Infinite

Sync request URL
https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/example.ppt?sign=q-s©2013-2022 Tencent Cloud. All rights reserved.

Page 1315 of 1869

Cloud Infinite

Content Recognition
Image Tagging：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for image tagging.
API

Description

Image tagging

Recognizes tags in images stored in COS by using the persistent processing API.

Image Tagging
Feature description
The image tagging feature recognizes tags in images stored in COS by using the persistent processing API and
returns tags with a high confidence.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1316 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1317 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->DetectLabel(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'exampleobject',));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Type

Description

Required

BucketStringBucket name in the format of BucketName-APPID

Yes

Object key, which is the unique identifier of the object in the bucket.
For example, if an object's access endpoint is examplebucketKey

String

1250000000.cos.ap-

Yesguangzhou.myqcloud.com/doc/pic.jpg , its key is
doc/pic.jpg .

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1318 of 1869

Cloud Infinite

Guzzle\\Service\\Resource\\Model Object([structure:protected] =>[data:protected] => Array([RequestId] => NWQwOGRkNDdfMjJiMjU4NjRfNzVjXzEwNmVjY2M=[Key] => exampleobject[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.cos.ap-beijing.myqcloud.com/exam[Labels] => Array(©2013-2022 Tencent Cloud. All rights reserved.

Page 1319 of 1869

Cloud Infinite[0] => Array([Confidence] => 83[Name] => Toy)[1] => Array([Confidence] => 77[Name] => Stuffed toy)[2] => Array([Confidence] => 15[Name] => Art))))

Response description
Parameter

Type

Description

Parent NodeRequestId

StringRequest ID

None

Key

StringObject key

None

BucketStringBucket name in the format of BucketName-APPID

None

Location

StringAddress of the requested resource

None

LabelsArray

Tag informationNone©2013-2022 Tencent Cloud. All rights reserved.

Page 1320 of 1869

Cloud Infinite

Image QR Code：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for image QR codes.
API

Description

QR coderecognition

Recognizes the location and content of valid QR codes in an image, outputs the text
information (URL or text) contained in the QR codes, and pixelates the recognized QR
codes.

QR codegeneration

Generates QR codes or barcodes based on the specified text information (URL or text).

QR Code Recognition
Feature description
The QR code recognition feature recognizes the location and content of valid QR codes in an image, outputs the text
information (URL or text) contained in the QR codes, and pixelates the recognized QR codes.
Sample request 1: Recognizing during upload©2013-2022 Tencent Cloud. All rights reserved.

Page 1321 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1322 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$imageQrcodeTemplate = new Qcloud\\Cos\\ImageParamTemplate\\ImageQrcodeTemp$imageQrcodeTemplate->setMode(0);// Pixelate the recognized QR code. Valid$picOperationsTemplate = new \\Qcloud\\Cos\\ImageParamTemplate\\PicOperatio$picOperationsTemplate->setIsPicInfo(1);// Set whether to return the input$picOperationsTemplate->addRule($imageQrcodeTemplate, "resultobject");// Se$result = $cosClient->putObject(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'exampleobject','Body' => fopen('path/to/localFile', 'rb'),'PicOperations' => $picOperationsTemplate->queryString(),// Generate parame));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Type

Description

Required

BucketStringBucket name in the format of BucketName-APPID

Yes

Object key, which is the unique identifier of the object in thebucket. For example, if an object's access endpoint is
Key

Stringexamplebucket-1250000000.cos.ap-

Yesguangzhou.myqcloud.com/doc/pic.jpg , its key is
doc/pic.jpg .
BodyFile/String

Uploaded content

Yes

PicOperations

Json/String

Persistent image processing information

Yes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1323 of 1869

Cloud Infinite

Guzzle\\Service\\Resource\\Model Object([structure:protected] =>[data:protected] => Array([Body] =>[ETag] => "698d51a19d8a121ce581499d7b701668"[RequestId] => NWQwOGRkNDdfMjJiMjU4NjRfNzVjXzEwNmVjY2M=[ContentLength] => 238186[Key] => exampleobject[Bucket] => examplebucket-1250000000©2013-2022 Tencent Cloud. All rights reserved.

Page 1324 of 1869

Cloud Infinite[Location] => examplebucket-1250000000.cos.ap-beijing.myqcloud.com/exam[Data] => Array([OriginalInfo] => Array([Key] => exampleobject[Location] => examplebucket-1250000000.cos.ap-beijing.myqcloud.
[ETag] => "7037fb6fb4cca43b958a28789605e73d98088720"[ImageInfo] => Array([Format] => JPEG
[Width] => 600[Height] => 500[Quality] => 90[Ave] => 0x46442e[Orientation] => 0))
[ProcessResults] => Array([Object] => Array([0] => Array([Key] => resultobject[Location] => examplebucket-1250000000.cos.ap-beijing.m[Format] => JPEG
[Width] => 300[Height] => 200[Size] => 30000[Quality] => 90[CodeStatus] => 1
[QRcodeInfo] => Array([0] => Array([CodeUrl] => xxxxxxxxxxxxx[CodeLocation] => Array([Point] => Array([0] => 100,100[1] => 100,200[2] => 200,200[3] => 200,100))©2013-2022 Tencent Cloud. All rights reserved.

Page 1325 of 1869

Cloud Infinite))[ETag] => "87c153bc2909aa0ba111ca126b675c510d36b817"
)
)
)
)
)
)

Response description
Parameter

Type

Description

Parent Node

Body

File/String

Response body

None

ETag

String

MD5 checksum of the file

None

RequestId

StringRequest ID

None

ContentLength

Int

Length of the response body

None

Key

StringObject key

None

BucketStringBucket name in the format of BucketName-APPID

None

Location

StringAddress of the requested resource

None

Data

Array

Image processing result (QR code information)

None

Sample request 2: Recognizing during download©2013-2022 Tencent Cloud. All rights reserved.

Page 1326 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1327 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->Qrcode(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'exampleobject','Cover' => 1,// QR code pixelation feature));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Type

Description

Required

BucketStringBucket name in the format of BucketName-APPID

Yes

Object key, which is the unique identifier of the object in the bucket.
For example, if an object's access endpoint is examplebucketKey

String

1250000000.cos.ap-

Yesguangzhou.myqcloud.com/doc/pic.jpg , its key is
doc/pic.jpg .
Cover

Int

Pixelates the recognized QR code. Valid values: 0 (no), 1 (yes).
Default value: 0.

Yes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1328 of 1869

Cloud Infinite

Guzzle\\Service\\Resource\\Model Object([structure:protected] =>[data:protected] => Array([RequestId] => NWQwOGRkNDdfMjJiMjU4NjRfNzVjXzEwNmVjY2M=[ContentLength] => 238186[Key] => exampleobject[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.cos.ap-beijing.myqcloud.com/exam[CodeStatus] => 1©2013-2022 Tencent Cloud. All rights reserved.

Page 1329 of 1869

Cloud Infinite[QRcodeInfo] => Array([0] => Array([CodeUrl] => xxxxxxxxxxxxx[CodeLocation] => Array([Point] => Array([0] => 100,100[1] => 100,200[2] => 200,200[3] => 200,100))))[ResultImage] =>))Response description
Parameter

Type

Description

Parent
NodeRequestId

StringRequest ID

None

ContentLength

Int

Length of the response body

None

Key

StringObject key

None

BucketStringBucket name in the format of BucketName-APPID

None

Location

StringAddress of the requested resource

None

CodeStatus

Int

Whether QR codes are recognized. 0: no; 1: yes.

None

QRcodeInfo

Array

Recognized QR code. There may be multiple ones.

None

ResultImage

StringBase64-encoded result image data, which will be returned if
the request parameter cover is 1.

None©2013-2022 Tencent Cloud. All rights reserved.

Page 1330 of 1869

Cloud Infinite

QR Code Generation
Feature description
The QR code generation feature generates QR codes or barcodes based on the specified text information (URL ortext).
Sample code<?php©2013-2022 Tencent Cloud. All rights reserved.

Page 1331 of 1869

Cloud Infinite

require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->QrcodeGenerate(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'QrcodeContent' => '<https://www.example.com>',// Recognizable QR code text
'QrcodeMode' => 0 // Type of the QR code to be generated. Valid values: 0 ('QrcodeWidth' => '200',// Width of the QR code or barcode to be generated.
));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Parameter

Type

Description

Required

BucketStringBucket name in the format of BucketName-APPID

Yes

QrcodeContent

StringRecognizable QR code text information

Yes

QrcodeMode

Int

QrcodeWidth

StringType of the QR code to be generated. Valid values: 0 (QR code),
1 (barcode). Default value: 0.
Width of the QR code or barcode to be generated. The height will
be compressed proportionally.

Yes

Yes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1332 of 1869

Cloud Infinite

Guzzle\\Service\\Resource\\Model Object([structure:protected] =>[data:protected] => Array([RequestId] => NWQwOGRkNDdfMjJiMjU4NjRfNzVjXzEwNmVjY2M=[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.cos.ap-beijing.myqcloud.com/[ResultImage] =>))©2013-2022 Tencent Cloud. All rights reserved.

Page 1333 of 1869

Cloud Infinite

Response description
Parameter

Type

Description

Parent NodeRequestId

StringRequest ID

None

BucketStringBucket name in the format of BucketName-APPID

None

Location

StringAddress of the requested resource

None

ResultImage

StringBase64-encoded result image dataNone©2013-2022 Tencent Cloud. All rights reserved.

Page 1334 of 1869

Cloud Infinite

Job APIs
Animated Image Job APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for submitting an animated image job.
API

Description

Submitting an animated image job

Submits an animated image job.

Submitting Animated Image Job
Feature description
This API is used to submit an animated image job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1335 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model createMediaAnimationJobs(array $args = arra

Sample request
Sample 1. Using a template©2013-2022 Tencent Cloud. All rights reserved.

Page 1336 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1337 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->createMediaAnimationJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'Animation','QueueId' => 'p81e648af2aee49688xxxxxxxxxxxxxxxx','Input' => array('Object' => 'video01.mp4'),'Operation' => array(////'TemplateId' => 't1de276cbdab16xxxxxxxxxxxxxxxxxxxxx','Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'Animation.gif',),'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher),'CallBack' => '',));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Sample 2. Customizing parameters©2013-2022 Tencent Cloud. All rights reserved.

Page 1338 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1339 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->createMediaAnimationJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'Animation','QueueId' => 'p81e648af2aee49688xxxxxxxxxxxxxxxx','Input' => array('Object' => 'video01.mp4'),'Operation' => array('Animation' => array('Container' => array('Format' => '',),'Video' => array('Codec' => '','Width' => '','Height' => '','Fps' => '','AnimateOnlyKeepKeyFrame' => '','AnimateTimeIntervalOfFrame' => '','AnimateFramesPerSecond' => '','Quality' => '',),'TimeInterval' => array('Start' => '','Duration' => '',
),

//
//

),
'Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'Animation.gif',),'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher),'CallBack' => '',));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}©2013-2022 Tencent Cloud. All rights reserved.

Page 1340 of 1869

Cloud Infinite

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description

Type

Required

Tag

RequestJob tag: Animation

StringYes

Input

RequestInformation of the media file to be processed

Container

Yes

Operation

RequestOperation ruleContainer

Yes

QueueId

RequestQueue ID of the job

StringYes

StringNo

StringNo

StringNo

ContainerNo

Job callback format, which can be JSON or
CallBackFormat

RequestXML (default value). It takes priority over thatof the queue.
Job callback type, which can be Url (default

CallBackType

Requestvalue) or TDMQ . It takes priority over that of
the queue.

CallBack

RequestCallBackMqConfig

RequestJob callback address, which takes priority overthat of the queue. If it is set to no , nocallbacks will be generated at the callback
address of the queue.
TDMQ configuration for job callback as
described in Structure, which is required if
CallBackType is TDMQ .

Input has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

ObjectRequest.Input

Media filename

StringYes

Operation has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

RequiredAnimation

Request.Operation

Job type parameterContainerNo

TemplateId

Request.Operation

Template ID

StringNo©2013-2022 Tencent Cloud. All rights reserved.

Page 1341 of 1869

Cloud Infinite

OutputUserData

Request.Operation

Result output address

Container

Yes

Request.Operation

The user information passed through, which
is printable ASCII codes of up to 1,024 inlength.

StringNo

StringNo

Type

RequiredContainerNo

ContainerNo

ContainerNo

Job priority. The greater the value, theJobLevel

Request.Operation

higher the priority. Valid values: 0 , 1 ,2 . Default value: 0 .

Note:
TemplateId is used first. If TemplateId is unavailable, Animation is used.
Animation has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription
Same asRequest.Container in theContainer

Request.Operation.Animation

animated image template
creation API
CreateMediaTemplate.
Same as Request.Video in

Video

Request.Operation.Animation

the animated image template
creation API
CreateMediaTemplate.
Same asRequest.TimeInterval in

TimeInterval

Request.Operation.Animation

the animated image template
creation API
CreateMediaTemplate.

Output has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

RequiredRegionRequest.Operation.Output

Bucket region

StringYes

BucketRequest.Operation.Output

Result storage bucket

StringYes

ObjectRequest.Operation.Output

Result file name

StringYes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1342 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([Body] => GuzzleHttp\\Psr7\\Stream Object([stream:GuzzleHttp\\Psr7\\Stream:private] => Resource id #88[size:GuzzleHttp\\Psr7\\Stream:private] =>[seekable:GuzzleHttp\\Psr7\\Stream:private] => 1
[readable:GuzzleHttp\\Psr7\\Stream:private] => 1
[writable:GuzzleHttp\\Psr7\\Stream:private] => 1
[uri:GuzzleHttp\\Psr7\\Stream:private] => php://temp[customMetadata:GuzzleHttp\\Psr7\\Stream:private] => Array©2013-2022 Tencent Cloud. All rights reserved.

Page 1343 of 1869

Cloud Infinite())[RequestId] => NjI2MTQHOAIHDOIDUOIA7879ADJOIMDc2YTk=[ContentType] => application/xml[ContentLength] => 797[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-beijing.myqcloud.com/jobs[Response] => Array([JobsDetail] => Array([Code] => Success[CreationTime] => 2022-04-21T19:29:36+0800[EndTime] => [Input] => Array([BucketId] => examplebucket-1250000000[Object] => video01.mp4[Region] => ap-beijing)[JobId] => j5318zx9c890zx8c0z98c0fa6355174de[Message] =>[Operation] => Array([Output] => Array([Bucket] => examplebucket-1250000000[Object] => Animation.gif[Region] => ap-beijing)[TemplateId] => t1de276cbdz78xcz09xc80zx901af71[TemplateName] => Animation-gif-1[UserData] => xxx[JobLevel] => 0)
[QueueId] => p81e648af2aeez87c6z78xc7z98xc79ca86[StartTime] => [State] => Submitted[Tag] => Animation)©2013-2022 Tencent Cloud. All rights reserved.

Page 1344 of 1869

Cloud Infinite))©2013-2022 Tencent Cloud. All rights reserved.

Page 1345 of 1869

Cloud Infinite

Screenshot Job APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for submitting a screenshot job.
API

Description

Submitting a screenshot job

Submits a screenshot job.

Submitting Screenshot Job
Feature description
This API is used to submit a screenshot job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1346 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model createMediaSnapshotJobs(array $args = array

Sample request
Sample 1. Using a template©2013-2022 Tencent Cloud. All rights reserved.

Page 1347 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1348 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->createMediaSnapshotJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'Snapshot','QueueId' => 'asdadadfafsdkjhfjghdfjg','CallBack' => 'https://example.com/callback','Input' => array('Object' => 'video01.mp4'),//'Operation' => array('TemplateId' => 'asdfafiahfiushdfisdhfuis','Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'snapshot-${Number}.jpg','SpriteObject' => 'sprite-${Number}.jpg',
),

//
//

'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher
),

//
//
//
//
//

'CallBackMqConfig' => array('MqRegion' => '','MqMode' => '','MqName' => '',),));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Sample 2. Customizing parameters©2013-2022 Tencent Cloud. All rights reserved.

Page 1349 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1350 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->createMediaSnapshotJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'Snapshot','QueueId' => 'asdadadfafsdkjhfjghdfjg','CallBack' => 'https://example.com/callback','Input' => array('Object' => 'video01.mp4'),'Operation' => array('Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'snapshot-${Number}.jpg',),'Snapshot' => array('Mode' => 'Average','Start' => 3,'TimeInterval' => '','Count' => 3,'Width' => '1280','Height' => '',
),
//
//

'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher),));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description

Type

Required

Tag

RequestJob tag: Snapshot

StringYes

Input

RequestInformation of the media file to be processed

Container

Yes©2013-2022 Tencent Cloud. All rights reserved.

Page 1351 of 1869

Cloud Infinite

Operation

RequestOperation ruleContainer

Yes

QueueId

RequestQueue ID of the job

StringYes

StringNo

StringNo

StringNo

ContainerNo

Job callback format, which can be JSON or
CallBackFormat

RequestXML (default value). It takes priority over thatof the queue.
Job callback type, which can be Url (default

CallBackType

Requestvalue) or TDMQ . It takes priority over that of
the queue.
Job callback address, which takes priority over

CallBack

RequestCallBackMqConfig

Requestthat of the queue. If it is set to no , nocallbacks will be generated at the callback
address of the queue.
TDMQ configuration for job callback as
described in Structure, which is required if
CallBackType is TDMQ .

Input has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

ObjectRequest.Input

Media filename

StringYes

Operation has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeDescription

Type

RequiredContainerNo

Job type parameter. Same as
Snapshot

Request.Operation

Request.Snapshot in the screenshot
template creation API CreateMediaTemplate.

TemplateId

Request.Operation

Template ID

StringNo

OutputRequest.Operation

Result output address

Container

Yes

UserData

Request.Operation

The user information passed through, which
is printable ASCII codes of up to 1,024 inlength.

StringNo

JobLevel

Request.Operation

Job priority. The greater the value, the higher

StringNo©2013-2022 Tencent Cloud. All rights reserved.

Page 1352 of 1869

Cloud Infinite

the priority. Valid values: 0 , 1 , 2 .
Default value: 0 .

Note:
TemplateId is used first. If TemplateId is unavailable, Snapshot is used.
Output has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

RequiredRegionRequest.Operation.Output

Bucket region

StringYes

BucketRequest.Operation.Output

Result storage bucket

StringYes

StringNo

StringNo

ObjectRequest.Operation.Output

Result filename. ${Number} must be
included in the filename. For
example, you can set Object tosnapshot-${Number}.jpg .

SpriteObject

Request.Operation.Output

Image sprite name. ${Number} must
be included in the filename. For
example, you can set
sprite-${Number}.jpg . Only the.jpg format is supported.

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1353 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([Body] => GuzzleHttp\\Psr7\\Stream Object([stream:GuzzleHttp\\Psr7\\Stream:private] => Resource id #88[size:GuzzleHttp\\Psr7\\Stream:private] =>[seekable:GuzzleHttp\\Psr7\\Stream:private] => 1
[readable:GuzzleHttp\\Psr7\\Stream:private] => 1
[writable:GuzzleHttp\\Psr7\\Stream:private] => 1
[uri:GuzzleHttp\\Psr7\\Stream:private] => php://temp[customMetadata:GuzzleHttp\\Psr7\\Stream:private] => Array©2013-2022 Tencent Cloud. All rights reserved.

Page 1354 of 1869

Cloud Infinite())[RequestId] => NjI2MTNkYAHDUIAHDRfNjQ0OF8yMGI4MjQ=[ContentType] => application/xml[ContentLength] => 829[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-beijing.myqcloud.com/jobs[Response] => Array([JobsDetail] => Array([Code] => Success[CreationTime] => 2022-04-21T19:19:25+0800[EndTime] => [Input] => Array([BucketId] => examplebucket-1250000000[Object] => video01.mp4[Region] => ap-beijing)[JobId] => je6dcd3d6a80d98a09ds8ac4214b9b[Message] =>[Operation] => Array([Output] => Array([Bucket] => examplebucket-1250000000[Object] => snapshot-${Number}.jpg[Region] => ap-beijing[SpriteObject] =>)[TemplateId] => t0778zc908zc908z0c8z0adcffd54a[TemplateName] => snapshot_1280*720_3[UserData] => xxx[JobLevel] => 0)
[QueueId] => p81e648afz7zc08c0z8xc09e086[StartTime] => [State] => Submitted[Tag] => Snapshot)©2013-2022 Tencent Cloud. All rights reserved.

Page 1355 of 1869

Cloud Infinite))©2013-2022 Tencent Cloud. All rights reserved.

Page 1356 of 1869

Cloud Infinite

Transcoding Job APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for submitting a transcoding job.
API

Description

Submitting transcoding job

Submits transcoding job

Submitting Transcoding Job
Feature description
Submitting a Transcoding Task
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1357 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model createMediaTranscodeJobs(array $args = arra

Sample request
Sample 1. Using a template©2013-2022 Tencent Cloud. All rights reserved.

Page 1358 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1359 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->createMediaTranscodeJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'Transcode','QueueId' => 'paaf4fce5521a40888a3034a5de80f6ca','Input' => array('Object' => 'example.mp4'),'Operation' => array(////'TemplateId' => 't04e1ab86554984f1aa17c062fbf6c007c','UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher'Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'video02.mp4',),'Watermark' => array(
array('Type' => 'Text','LocMode' => 'Absolute','Dx' => '64','Dy' => '64','Pos' => 'TopRight','Text' => array('Text' => 'The first watermark','FontSize' => '30','FontType' => 'simfang.ttf','FontColor' => '#99ff00','Transparency' => '100', // Opacity),),
array('Type' => 'Text','LocMode' => 'Absolute','Dx' => '64','Dy' => '64','Pos' => 'TopLeft','Text' => array('Text' => 'The second watermark','FontSize' => '30','FontType' => 'simfang.ttf','FontColor' => '#99ff00','Transparency' => '100', // Opacity©2013-2022 Tencent Cloud. All rights reserved.

Page 1360 of 1869

Cloud Infinite

),
),
),
),
));
// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Sample 2. Customizing parameters©2013-2022 Tencent Cloud. All rights reserved.

Page 1361 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', //Protocol header, which is http by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1362 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->createMediaTranscodeJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'Transcode','QueueId' => 'asdadadfafsdkjhfjghdfjg','CallBack' => 'https://example.com/callback','Input' => array('Object' => 'video01.mp4'
),
//
//

'Operation' => array('UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher'Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'video01.mkv',),'Transcode' => array('Container' => array('Format' => 'mp4'),'Video' => array('Codec' => 'H.264','Profile' => 'high','Bitrate' => '1000','Preset' => 'medium','Width' => '1280','Fps' => '30',),'Audio' => array('Codec' => 'aac','Samplerate' => '44100','Bitrate' => '128','Channels' => '4',),
'TransConfig' => array('AdjDarMethod' => 'scale','IsCheckReso' => 'false','ResoAdjMethod' => '1',),
'TimeInterval' => array('Start' => '0',
'Duration' => '60',),©2013-2022 Tencent Cloud. All rights reserved.

Page 1363 of 1869

Cloud Infinite

),
),
));
// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description

Type

Required

Tag

RequestJob tag: Transcode

StringYes

Input

RequestInformation of the media file to be processed

Container

Yes

Operation

RequestOperation ruleContainer

Yes

QueueId

RequestQueue ID of the job

StringYes

StringNo

StringNo

StringNo

ContainerNo

Job callback format, which can be JSON or
CallBackFormat

RequestXML (default value). It takes priority over thatof the queue.
Job callback type, which can be Url (default

CallBackType

Requestvalue) or TDMQ . It takes priority over that of
the queue.

CallBack

RequestJob callback address, which takes priority overthat of the queue. If it is set to no , nocallbacks will be generated at the callback
address of the queue.
TDMQ configuration for job callback as

CallBackMqConfig

Requestdescribed in Structure, which is required if
CallBackType is TDMQ .

Input has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

ObjectRequest.Input

Media filename

StringYes©2013-2022 Tencent Cloud. All rights reserved.

Page 1364 of 1869

Cloud Infinite

Operation has the following sub-nodes:
Node Name

Parent NodeDescription

Type

RequiredTemplateId

Request.Operation

Template ID

String

No

Transcode

Request.Operation

Transcoding template parameterContainer

No

StringNo

ContainerNo

ContainerNo(Keyword)

Watermark template ID. Multiple
WatermarkTemplateId

WatermarkRequest.Operation

Request.Operationwatermark template IDs can bepassed in.
Watermark template parameter,
which is the same as
Request.Watermark in thewatermark template creation API
CreateMediaTemplate.

RemoveWatermark

Request.Operation

Whether to remove thewatermark. This parameter is notsupported for H.265 currently.

DigitalWatermark

Request.Operation

Specifies the digital watermark
parameter

ContainerNo

OutputRequest.Operation

Result output address

Container

Yes

Request.Operation

The user information passed
through, which is printable ASCII

StringNo

String

No

UserData

codes of up to 1,024 in length.
Job priority. The greater the value,
JobLevel

Request.Operation

the higher the priority. Validvalues: 0 , 1 , 2 . Default
value: 0 .

Note:
For the transcoding parameter, TemplateId is used first, and if TemplateId is unavailable, Transcode isused. For the watermark parameter, WatermarkTemplateId or Watermark can be used for configuration,and WatermarkTemplateId is used first.
Transcode has the following sub-nodes:
Node Name(Keyword)

Parent Node©2013-2022 Tencent Cloud. All rights reserved.

Description

Type

RequiredPage 1365 of 1869

Cloud Infinite

TimeInterval

Request.Operation.Transcode

Same asRequest.TimeInterval inContainerNo

ContainerNo

ContainerNo

ContainerNo

ContainerNo

Container
array

No

the transcoding template
creation API
CreateMediaTemplate.

Container

Request.Operation.Transcode

Same asRequest.Container in thetranscoding template creation
API CreateMediaTemplate.
Same as Request.Video in

Video

Request.Operation.Transcodethe transcoding template
creation API
CreateMediaTemplate.
Same as Request.Audio in

Audio

Request.Operation.Transcodethe transcoding template
creation API
CreateMediaTemplate.
Same asRequest.TransConfig inTransConfig

Request.Operation.Transcodethe transcoding template
creation API
CreateMediaTemplate.

AudioMix

Request.Operation.Transcode

Audio mix parameter as
described in Structure.

RemoveWatermark has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

stringYes

stringYes

X-axis offset of the top-left
Dx

Request.Operation.RemoveWatermark

corner origin. Value range:[1, 4096]

Dy

Request.Operation.RemoveWatermark

Y-axis offset of the top-leftcorner origin. Value range:[1, 4096]

Width

Request.Operation.RemoveWatermark

Width. Value range: [1,4096]

stringYes

HeightRequest.Operation.RemoveWatermark

Height. Value range: [1,stringYes©2013-2022 Tencent Cloud. All rights reserved.

Page 1366 of 1869

Cloud Infinite

4096]

DigitalWatermark has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeDescription

Type

Required

stringYes

StringYes

StringYes

stringYes

The string embedded by thedigital watermark, which can
MessageType

Request.Operation.DigitalWatermark

Request.Operation.DigitalWatermark

contain up to 64 letters, digits,
underscores (_), hyphens (-),
and asterisks (*).
Watermark type, whichcurrently can be set to Text
only
Watermark version, which

VersionRequest.Operation.DigitalWatermark

currently can be set to V1
only

IgnoreError

Request.Operation.DigitalWatermark

Whether to ignore thewatermarking failure andcontinue the job. Valid values:
true , false (default
value).

Output has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

RequiredRegionRequest.Operation.Output

Bucket region

StringYes

BucketRequest.Operation.Output

Result storage bucket

StringYes

ObjectRequest.Operation.Output

Result file name

StringYes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1367 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([Body] => GuzzleHttp\\Psr7\\Stream Object([stream:GuzzleHttp\\Psr7\\Stream:private] => Resource id #88[size:GuzzleHttp\\Psr7\\Stream:private] =>[seekable:GuzzleHttp\\Psr7\\Stream:private] => 1
[readable:GuzzleHttp\\Psr7\\Stream:private] => 1
[writable:GuzzleHttp\\Psr7\\Stream:private] => 1
[uri:GuzzleHttp\\Psr7\\Stream:private] => php://temp[customMetadata:GuzzleHttp\\Psr7\\Stream:private] => Array©2013-2022 Tencent Cloud. All rights reserved.

Page 1368 of 1869

Cloud Infinite())[RequestId] => NjI2MTAzasdaHUISDHUINzE3YV8xZWVmNjU=[ContentType] => application/xml[ContentLength] => 1554
[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/jobs[Response] => Array([JobsDetail] => Array([Code] => Success[CreationTime] => 2022-04-21T15:10:15+0800[EndTime] => [Input] => Array([BucketId] => examplebucket-1250000000[Object] => video01.mp4[Region] => ap-beijing)[JobId] => j1815a4c81h2kj31231gh31kj2f9e223404e[Message] => Array()[Operation] => Array([Output] => Array([Bucket] => examplebucket-1250000000[Object] => Transcode.flv[Region] => ap-beijing)[TemplateId] => t0b612860as90d8a09sd65dca38[TemplateName] => FLV-SD[UserData] => xxx[JobLevel] => 0
[Watermark] => Array([0] => Array([Dx] => 64©2013-2022 Tencent Cloud. All rights reserved.

Page 1369 of 1869

Cloud Infinite[Dy] => 64[EndTime] => Array()[LocMode] => Absolute[Pos] => TopRight[StartTime] => Array()[Text] => Array([FontColor] => #99ff00[FontSize] => 30[FontType] => simfang.ttf[Text] => The first watermark[Transparency] => 100)[Type] => Text)
[1] => Array([Dx] => 64[Dy] => 64[EndTime] => Array()[LocMode] => Absolute[Pos] => TopLeft[StartTime] => Array()[Text] => Array([FontColor] => #99ff00[FontSize] => 30[FontType] => simfang.ttf[Text] => The second watermark[Transparency] => 100)[Type] => Text

©2013-2022 Tencent Cloud. All rights reserved.

Page 1370 of 1869

Cloud Infinite)))[Progress] => 0
[QueueId] => p81e648a7s9d88a09sd89a0757be086[StartTime] => [State] => Submitted[Tag] => Transcode)))©2013-2022 Tencent Cloud. All rights reserved.

Page 1371 of 1869

Cloud Infinite

Splicing Job APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for submitting a splicing job.
API

Description

Submitting a splicing job

Submits a splicing job.

Submitting Splicing Job
Feature description
This API is used to submit a splicing job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1372 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model createMediaConcatJobs(array $args = array()Sample request
Sample 1. Using a template©2013-2022 Tencent Cloud. All rights reserved.

Page 1373 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1374 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->createMediaConcatJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'Concat','QueueId' => 'asdadadfafsdkjhfjghdfjg','CallBack' => 'https://example.com/callback','Input' => array('Object' => 'video01.mp4'),'Operation' => array('TemplateId' => 'asdfafiahfiushdfisdhfuis','Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'concat-video02.mp4',
),
//
//

'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher),));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Sample 2. Customizing parameters©2013-2022 Tencent Cloud. All rights reserved.

Page 1375 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1376 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->createMediaConcatJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'Concat','QueueId' => 'asdadadfafsdkjhfjghdfjg','CallBack' => 'https://example.com/callback','Input' => array('Object' => 'video01.mp4'
),
//
//

//
//

//
//

'Operation' => array('UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher'Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'concat-video03.mp4',),'ConcatTemplate' => array('ConcatFragments' => array(
array('Url' => 'https://example.com/video01.mp4','Mode' => 'Start','StartTime' => '0',
'EndTime' => '7',),
array('Url' => 'https://example.com/video02.mp4','Mode' => 'Start','StartTime' => '0',
'EndTime' => '10',),// ... repeated),'Index' => 1,'Container' => array('Format' => 'mp4'),'Audio' => array('Codec' => 'mp3','Samplerate' => '','Bitrate' => '','Channels' => '',),'Video' => array(©2013-2022 Tencent Cloud. All rights reserved.

Page 1377 of 1869

Cloud Infinite'Codec' => 'H.264','Bitrate' => '1000','Width' => '1280','Height' => '','Fps' => '30',
),
),
),
));
// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Node Name

Parent(Keyword)

Node

Tag

Description

Type

Required

RequestJob tag: Concat

StringYes

Input

RequestInformation of the media file to be processed

Container

No

Operation

RequestOperation ruleContainer

Yes

QueueId

RequestQueue ID of the job

StringYes

StringNo

StringNo

StringNo

ContainerNo

Job callback format, which can be JSON or
CallBackFormat

RequestXML (default value). It takes priority over thatof the queue.
Job callback type, which can be Url (default

CallBackType

Requestvalue) or TDMQ . It takes priority over that of
the queue.

CallBack

RequestJob callback address, which takes priority overthat of the queue. If it is set to no , nocallbacks will be generated at the callback
address of the queue.

CallBackMqConfig

Request

TDMQ configuration for job callback as
described in Structure, which is required if
CallBackType is TDMQ .

©2013-2022 Tencent Cloud. All rights reserved.

Page 1378 of 1869

Cloud Infinite

Input has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

ObjectRequest.Input

Media filename

StringYes

Operation has the following sub-nodes:
Node Name

Parent NodeDescription

Type

RequiredConcatTemplate

Request.Operation

Splicing parameter.

ContainerNo

TemplateId

Request.Operation

Template ID

StringNo

OutputRequest.Operation

Result output address

Container

Yes

Request.Operation

Job priority. The greater the value, thehigher the priority. Valid values: 0 ,StringNo(Keyword)

JobLevel

1 , 2 . Default value: 0 .

Note:
TemplateId is used first. If TemplateId is unavailable, ConcatTemplate is used.
ConcatTemplate has the following sub-nodes:
Node Name(Keyword)
ConcatFragment

Parent NodeDescription

Type

Req

Request.Operation.
ConcatTemplate

Splicing node

Container
array

No

ContainerNo

ContainerNo

Container

Yes

Audio parameter. Same as
Audio

Request.Operation.
ConcatTemplate

Request.ConcatTemplate.Audio in
the splicing template creation API
CreateMediaTemplate.
Video parameter. Same as

VideoContainer

Request.Operation.
ConcatTemplate

Request.ConcatTemplate.Video inthe splicing template creation API
CreateMediaTemplate.

Request.Operation.

Container format. Same as
Request.ConcatTemplate.Container

ConcatTemplatein the splicing template creation API
CreateMediaTemplate.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1379 of 1869

Cloud Infinite

AudioMix

Request.Operation.

Audio mix parameter as described in Structure.

Container

ConcatTemplate

Index

DirectConcat

No

array

Request.Operation.

Index of the Input node in the

ConcatTemplate

ConcatFragment sequence

Request.Operation.
ConcatTemplate

Simple splicing (without transcoding). Other
video and audio parameters become invalid.

StringNo

String

No

ConcatFragment has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

Default
Value

Constraints
Same asUrl

FragmentIndex

Request.Operation.
ConcatTemplate.

Splicing
objectConcatFragment

address

the bucket
object file.

Index

An integer

Request.Operation.
ConcatTemplate.
ConcatFragment

StartTime

EndTime

Request.Operation.
ConcatTemplate.

position of
the spliced

StringString

Yes

No

the
address ofNonegreaterthan or0

objectequal to 0
Video
start

[0, video
duration]

ConcatFragment

time

seconds

Request.Operation.

Video[0, video

end

duration]time

seconds

ConcatTemplate.

Start time

End time

StringString

No

No

ConcatFragment

Output has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

RequiredRegionRequest.Operation.Output

Bucket region

StringYes

BucketRequest.Operation.Output

Result storage bucket

StringYes©2013-2022 Tencent Cloud. All rights reserved.

Page 1380 of 1869

Cloud Infinite

ObjectRequest.Operation.Output

Result file name

StringYes

Sample response

GuzzleHttp\\Command\\Result Object([Body] => GuzzleHttp\\Psr7\\Stream Object([stream:GuzzleHttp\\Psr7\\Stream:private] => Resource id #88[size:GuzzleHttp\\Psr7\\Stream:private] =>©2013-2022 Tencent Cloud. All rights reserved.

Page 1381 of 1869

Cloud Infinite[seekable:GuzzleHttp\\Psr7\\Stream:private] => 1
[readable:GuzzleHttp\\Psr7\\Stream:private] => 1
[writable:GuzzleHttp\\Psr7\\Stream:private] => 1
[uri:GuzzleHttp\\Psr7\\Stream:private] => php://temp[customMetadata:GuzzleHttp\\Psr7\\Stream:private] => Array())[RequestId] => NjI2MjFhOTHASIUDHAUISDHl8yMjMxNmE=[ContentType] => application/xml[ContentLength] => 792[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-beijing.myqcloud.com/jobs[Response] => Array([JobsDetail] => Array([Code] => Success[CreationTime] => 2022-04-22T11:01:42+0800[EndTime] => [Input] => Array([BucketId] => examplebucket-1250000000[Object] => video01.mp4[Region] => ap-beijing)[JobId] => j898f573asd780a8sd90a8sd09e30cf31f[Message] =>[Operation] => Array([Output] => Array([Bucket] => examplebucket-1250000000[Object] => concat-video01.mp4[Region] => ap-beijing)[TemplateId] => t17b9c2e7a0s8d0a8d0a9d43552f648e[TemplateName] => concat-1[UserData] => xxx[TemplateName] => 0)
[QueueId] => p81e648af2aeas78d0a8d09a8d09757be086©2013-2022 Tencent Cloud. All rights reserved.

Page 1382 of 1869

Cloud Infinite[StartTime] => [State] => Submitted[Tag] => Concat)))©2013-2022 Tencent Cloud. All rights reserved.

Page 1383 of 1869

Cloud Infinite

Intelligent Thumbnail Job APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for submitting an intelligent thumbnail job.
API

Description

Submitting an intelligent thumbnail job

Submits an intelligent thumbnail job.

Submitting Intelligent Thumbnail Job
Feature description
This API is used to submit an intelligent thumbnail job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1384 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model createMediaSmartCoverJobs(array $args = arr

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1385 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1386 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// Submit an intelligent thumbnail job. For more information, visit https://www$result = $cosClient->createMediaSmartCoverJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'SmartCover','QueueId' => 'p81e648afxxxxxxxxxxxxxxxxx','Input' => array('Object' => 'video01.mp4'),//'Operation' => array('TemplateId' => '', // Use a template'SmartCover' => array('Format' => '','Width' => '','Height' => '','Count' => '','DeleteDuplicates' => '',),'Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'SmartCover-${Number}.jpg',),'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher

//
//

//
//

),
'CallBack' => '','CallBackFormat' => '','CallBackType' => '',));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description©2013-2022 Tencent Cloud. All rights reserved.

Type

RequiredPage 1387 of 1869

Cloud Infinite

Tag

RequestJob tag: SmartCoverStringYes

Input

RequestInformation of the media file to be processed

Container

Yes

Operation

RequestOperation ruleContainer

Yes

QueueId

RequestQueue ID of the job

StringYes

StringNo

StringNo

StringNo

ContainerNo

Job callback format, which can be JSON or
CallBackFormat

RequestXML (default value). It takes priority overthat of the queue.
Job callback type, which can be Url

CallBackType

Request(default value) or TDMQ . It takes priority overthat of the queue.

CallBack

Job callback address, which takes priority overthat of the queue. If it is set to no , noRequestCallBackMqConfig

callbacks will be generated at the callback
address of the queue.
TDMQ configuration for job callback as
described in Structure, which is required if
CallBackType is TDMQ .

RequestInput has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

ObjectRequest.Input

Media filename

StringYes

Operation has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

RequiredTemplateId

Request.Operation

Intelligent thumbnail template ID

StringNo

SmartCover

Request.Operation

Thumbnail configuration

ContainerNo

OutputRequest.Operation

Result output address

Container

Yes

UserData

Request.Operation

The user information passed through, which
is printable ASCII codes of up to 1,024 inlength.

StringNo

JobLevel

Request.Operation

Job priority. The greater the value, theStringNo©2013-2022 Tencent Cloud. All rights reserved.

Page 1388 of 1869

Cloud Infinite

higher the priority. Valid values: 0 , 1 ,2 . Default value: 0 .

Note:
If both TemplateId and SmartCover are set, TemplateId will be used first.
SmartCover has the following sub-nodes:
Node Name(Keyword)
FormatWidthParent NodeDescription

Type

Required

Request.Operation.SmartCover

Thumbnailimage type.

StringYes

Request.Operation.SmartCoverHeightCount

DeleteDuplicatesThumbnail
image
width

Request.Operation.SmartCover

Thumbnailimage
heightRequest.Operation.SmartCover

Number of
thumbnails.

Request.Operation.SmartCover

Whether todeduplicate

StringStringYes

Yes

Default
Value

Const

None

png, jwebp

None

1. Val
range
[128,
4096]
Unit: pNone

1. Val
range
[128,
4096]
Unit: pStringNo

3

1. Valrange
10].

StringNo

false

true/fa

thumbnails.

Output has the following sub-nodes:
Node
Name

Parent NodeDescription

Type

RequiredRegionRequest.Operation.Output

Bucket region

StringYes

BucketRequest.Operation.Output

Result storage bucket

StringYes

ObjectRequest.Operation.Output

Result filename.

StringYes(Keyword)${Number} must be included in thefilename.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1389 of 1869

Cloud Infinite

For example, if Object is mynew-cover-${Number}.jpg , andthere are three result files, the output
result filenames are as follows:
my-new-cover-0.jpg
my-new-cover-1.jpg
my-new-cover-2.jpg

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1390 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([Body] => GuzzleHttp\\Psr7\\Stream Object([stream:GuzzleHttp\\Psr7\\Stream:private] => Resource id #88[size:GuzzleHttp\\Psr7\\Stream:private] =>[seekable:GuzzleHttp\\Psr7\\Stream:private] => 1
[readable:GuzzleHttp\\Psr7\\Stream:private] => 1
[writable:GuzzleHttp\\Psr7\\Stream:private] => 1
[uri:GuzzleHttp\\Psr7\\Stream:private] => php://temp[customMetadata:GuzzleHttp\\Psr7\\Stream:private] => Array())[RequestId] => NjI2MASOIDUAOIDUJIAOJDIOADJyMjNjZDE=[ContentType] => application/xml[ContentLength] => 832[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-beijing.myqcloud.com/jobs[Response] => Array([JobsDetail] => Array([Code] => Success[CreationTime] => 2022-04-22T11:12:33+0800[EndTime] => [Input] => Array([BucketId] => examplebucket-1250000000[Object] => video01.mp4[Region] => ap-beijing)[JobId] => j0d9bc17z890zx8c9s877z97187147[Message] =>[Operation] => Array([Output] => Array([Bucket] => examplebucket-1250000000[Object] => SmartCover-${Number}.jpg[Region] => ap-beijing)©2013-2022 Tencent Cloud. All rights reserved.

Page 1391 of 1869

Cloud Infinite[SmartCover] => Array([Count] =>[DeleteDuplicates] => false[Format] =>[Height] =>[Width] =>)[UserData] => xxx[JobLevel] => 0)
[QueueId] => p81e648afzx8c09z8xc09zx8c097be086[StartTime] => [State] => Submitted[Tag] => SmartCover)))©2013-2022 Tencent Cloud. All rights reserved.

Page 1392 of 1869

Cloud Infinite

Multi-Job APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for submitting multiple jobs.
API

Description

Submitting multiple jobs

Submits multiple jobs

Submitting Multiple Jobs
Feature description
This API is used to submit multiple jobs.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1393 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model createMediaJobs(array $args = array());

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1394 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your real `secretId`, which can be viewe$secretKey = "SECRETKEY"; // Replace it with your real `secretKey`, which can be vi$region = "ap-beijing"; // Replace it with your real region information, which can$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1395 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// Multi-job APIs: https://cloud.tencent.com/document/product/436/58335$result = $cosClient->CreateMediaJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'Transcode', // If `Operation` has no `Tag` parameter, this option'QueueId' => 'paaf4fce5521a40888a303xxxxxxxxxxxxxx','CallBack' => '','Input' => array('Object' => 'example.mp4'),'Operation' => array(
array('Tag' => 'Transcode','TemplateId' => 't04e1ab86554984f1aa17cxxxxxxxxxxxxxx','Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the f'Object' => 'video01.mp4',),'WatermarkTemplateId' => array('t112d18d9b2a9b430e91dxxxxxxxxxxxxxx',),),
array('Tag' => 'Transcode','TemplateId' => 't04e1ab86554984f1aa17xxxxxxxxxxxxxx','Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the f'Object' => 'video02.mp4',),'WatermarkTemplateId' => array('t1bf713bb5c6a5496e859axxxxxxxxxxxxxx',
),
),
),
));
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}©2013-2022 Tencent Cloud. All rights reserved.

Page 1396 of 1869

Cloud Infinite

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description

Type

Required

Input

RequestInformation of the media file to be processed

Container

Yes

Operation

RequestOperation rule. Up to six operation rules aresupported.

Container

Yes

QueueId

RequestQueue ID of the job

StringYes

Input has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

ObjectRequest.Input

Media filename

StringYes

Operation has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

Tag

Request.Operation

Job type. Valid values: Animation,
Transcode, SmartCover, Snapshot

Container

Yes

TemplateId

Request.Operation

Template ID

StringYes

OutputRequest.Operation

Result output address

Container

Yes

Output has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

RequiredRegionRequest.Operation.Output

Bucket region

StringYes

BucketRequest.Operation.Output

Result storage bucket

StringYes

ObjectRequest.Operation.Output

Output result filename

StringYes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1397 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([Body] => GuzzleHttp\\Psr7\\Stream Object([stream:GuzzleHttp\\Psr7\\Stream:private] => Resource id #88[size:GuzzleHttp\\Psr7\\Stream:private] =>[seekable:GuzzleHttp\\Psr7\\Stream:private] => 1
[readable:GuzzleHttp\\Psr7\\Stream:private] => 1
[writable:GuzzleHttp\\Psr7\\Stream:private] => 1
[uri:GuzzleHttp\\Psr7\\Stream:private] => php://temp[customMetadata:GuzzleHttp\\Psr7\\Stream:private] => Array©2013-2022 Tencent Cloud. All rights reserved.

Page 1398 of 1869

Cloud Infinite())[RequestId] => NjI2MTAJOIDSjoiajsdoSDOASDHJoimY2YTQ=[ContentType] => application/xml[ContentLength] => 1731
[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-beijing.myqcloud.com/jobs[Response] => Array([JobsDetail] => Array([0] => Array([Code] => Success[CreationTime] => 2022-04-21T18:03:31+0800[EndTime] => [Input] => Array([BucketId] => examplebucket-1250000000[Object] => video01.mp4[Region] => ap-beijing)[JobId] => j4c211cas9a87sd90d80a988627cb30[Message] =>[Operation] => Array([Output] => Array([Bucket] => examplebucket-1250000000[Object] => Transcode-01.flv[Region] => ap-beijing)[TemplateId] => t0b6128z8c098z09xcsd89s0a5dca38[TemplateName] => FLV-SD[WatermarkTemplateId] => t185z90x8c9z0da5sd67a5)[Progress] => 0
[QueueId] => pzx8c09za90sd890a8d09aa0757be086[StartTime] => [State] => Submitted[Tag] => Transcode©2013-2022 Tencent Cloud. All rights reserved.

Page 1399 of 1869

Cloud Infinite)[1] => Array([Code] => Success[CreationTime] => 2022-04-21T18:03:31+0800[EndTime] => [Input] => Array([BucketId] => examplebucket-1250000000[Object] => video01.mp4[Region] => ap-beijing)[JobId] => j4cz9x7c8z9xcsda98sd09ad80627cb30[Message] =>[Operation] => Array([Output] => Array([Bucket] => examplebucket-1250000000[Object] => Transcode-02.flv[Region] => ap-beijing)[TemplateId] => t0bz98xc789zxs9d80a8sd90asd37f8[TemplateName] => FLV-HD[WatermarkTemplateId] => t18zc8z90csd876a78sdas)[Progress] => 0
[QueueId] => p81zxc908zaf2aee496a09s8d90as8d90[StartTime] => [State] => Submitted[Tag] => Transcode))))©2013-2022 Tencent Cloud. All rights reserved.

Page 1400 of 1869

Cloud Infinite

Video Enhancement Job APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for submitting a video enhancement job.
API

Description

Submitting a video enhancement job

Submits a video enhancement job.

Submitting Video Enhancement Job
Feature description
This API is used to submit a video enhancement job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1401 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model createMediaVideoProcessJobs(array $args = a

Sample request
Sample 1. Using a template©2013-2022 Tencent Cloud. All rights reserved.

Page 1402 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1403 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->createMediaVideoProcessJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'VideoProcess','QueueId' => 'p81e648afxxxxxxxxxxxxxxxxx','Input' => array('Object' => 'video01.mp4'),'Operation' => array('TemplateId' => 't13466f1ea41a14c0xxxxxxxxxxxxx', // Video enhancement'TranscodeTemplateId' => 't0b6a845f5e42847bd81xxxxxxxxxxxxx', // Transc'WatermarkTemplateId' => 't185e2e24551b24259a0xxxxxxxxxxxxx', // Waterm'Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'VideoProcess.flv',
),
//
//

'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher),'CallBack' => '',));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Sample 2. Customizing parameters©2013-2022 Tencent Cloud. All rights reserved.

Page 1404 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1405 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->createMediaVideoProcessJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'VideoProcess','QueueId' => 'p81e648afxxxxxxxxxxxxxxxxx','Input' => array('Object' => 'video01.mp4'),'Operation' => array('VideoProcess' => array('ColorEnhance' => array('Enable' => '','Contrast' => '','Correction' => '','Saturation' => '',),'MsSharpen' => array('Enable' => '','SharpenLevel' => '',),),'Transcode' => array('Tag' => '','Name' => '','Container' => array('Format' => '',),'Video' => array('Codec' => '','Width' => '','Height' => '','Fps' => '','Remove' => '','Profile' => '','Bitrate' => '','Crf' => '','Gop' => '','Preset' => '','Bufsize' => '','Maxrate' => '','HlsTsTime' => '','Pixfmt' => '','LongShortMode' => '',),©2013-2022 Tencent Cloud. All rights reserved.

Page 1406 of 1869

Cloud Infinite'TimeInterval' => array('Start' => '','Duration' => '',),'Audio' => array('Codec' => '','Samplerate' => '','Bitrate' => '','Channels' => '','Remove' => '','KeepTwoTracks' => '','SwitchTrack' => '','SampleFormat' => '',),'TransConfig' => array('AdjDarMethod' => '','IsCheckReso' => '','ResoAdjMethod' => '','IsCheckVideoBitrate' => '','VideoBitrateAdjMethod' => '','IsCheckAudioBitrate' => '','AudioBitrateAdjMethod' => '','DeleteMetadata' => '','IsHdr2Sdr' => '','HlsEncrypt' => array('IsHlsEncrypt' => '','UriKey' => '',),),),'Watermark' => array('Type' => '','Pos' => '','LocMode' => '','Dx' => '','Dy' => '','StartTime' => '','EndTime' => '','Image' => array('Url' => '','Mode' => '','Width' => '','Height' => '','Transparency' => '','Background' => '',),'Text' => array(©2013-2022 Tencent Cloud. All rights reserved.

Page 1407 of 1869

Cloud Infinite'FontSize' => '','FontType' => '','FontColor' => '','Transparency' => '','Text' => '',),),'Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'VideoProcess.flv',
),
//
//

'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher),'CallBack' => '',));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description

Type

Required

Tag

RequestJob tag: VideoProcess

StringYes

Input

RequestInformation of the media file to be processed

Container

Yes

Operation

RequestOperation ruleContainer

Yes

QueueId

RequestQueue ID of the job

StringYes

StringNo

StringNo

StringNo

Job callback format, which can be JSON or
CallBackFormat

RequestXML (default value). It takes priority over thatof the queue.
Job callback type, which can be Url (default

CallBackType

Requestvalue) or TDMQ . It takes priority over that of
the queue.

CallBack

RequestJob callback address, which takes priority over©2013-2022 Tencent Cloud. All rights reserved.

Page 1408 of 1869

Cloud Infinitethat of the queue. If it is set to no , nocallbacks will be generated at the callback
address of the queue.

CallBackMqConfig

Request

TDMQ configuration for job callback as
described in Structure, which is required if
CallBackType is TDMQ .

Container

No

Input has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

ObjectRequest.Input

Media filename

StringYes

Operation has the following sub-nodes:
Node Name(Keyword)

VideoProcess

Parent NodeRequest.Operation

Description
Video enhancement templateparameter. This node andTemplateId cannot be empty

TypeRequiredContainer

No

StringNo

Container

No

Stringarray

NoContainer
array

No

at the same time.
Template ID. This node andTemplateId

Request.Operation

VideoProcess cannot be
empty at the same time.

Transcode

Request.Operation

Transcoding template parameter.
This node andTranscodeTemplateId
cannot be empty at the same time.

TranscodeTemplateId

Request.Operation

Transcoding template ID. This
node and Transcode cannot
be empty at the same time. Use
this node first.
Watermark template parameter.
Same asRequest.Watermark in the

WatermarkRequest.Operation©2013-2022 Tencent Cloud. All rights reserved.

watermark template creation API
CreateMediaTemplate. Up tothree watermarks can be passed
in.

Page 1409 of 1869

Cloud Infinite

WatermarkTemplateId

Request.Operation

Watermark template ID. Up tothree watermark template IDs canbe passed in. If Watermark

StringNo

and WatermarkTemplateId
exist at the same time, use
WatermarkTemplateId first.
DigitalWatermark

Request.Operation

Specifies the digital watermark
parameter

ContainerNo

OutputRequest.Operation

Result output address

Container

Yes

StringNo

JobLevel

Request.Operation

Job priority. The greater the value,
the higher the priority. Validvalues: 0 , 1 , 2 . Default
value: 0 .

Note:
To submit a video enhancement job, you must pass in the transcoding parameter. For the video enhancement
parameter, TemplateId is used first, and if TemplateId is unavailable, VideoProcess is used. For thetranscoding parameter, TranscodeTemplateId is used first, and if TranscodeTemplateId is unavailable,
Transcode is used. For the watermark parameter, WatermarkTemplateId or Watermark can be used
for configuration, and WatermarkTemplateId is used first.
VideoProcess has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription
Same as Request.ColorEnhance in the video

ColorEnhance

Request.Operation.VideoProcessenhancement template creation API
CreateMediaTemplate.
Same as Request.MsSharpen in the video

MsSharpen

Request.Operation.VideoProcessenhancement template creation API
CreateMediaTemplate.

Transcode has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

TimeInterval

Request.Operation.Transcode

Same asRequest.TimeInterval inContainerNo

the transcoding template©2013-2022 Tencent Cloud. All rights reserved.

Page 1410 of 1869

Cloud Infinite

creation API
CreateMediaTemplate.

Container

Request.Operation.Transcode

Same asRequest.Container in theContainerNo

ContainerNo

ContainerNo

the transcoding template
creation API
CreateMediaTemplate.

Container

No

Audio mix parameter as
described in Structure.

Container
array

No

Description

Type

Required

stringYes

StringYes

StringYestranscoding template creation
API CreateMediaTemplate.
Same as Request.Video in

Video

Request.Operation.Transcodethe transcoding template
creation API
CreateMediaTemplate.
Same as Request.Audio in

Audio

Request.Operation.Transcodethe transcoding template
creation API
CreateMediaTemplate.
Same asRequest.TransConfig inTransConfig

Request.Operation.Transcode

AudioMix

Request.Operation.Transcode

DigitalWatermark has the following sub-nodes:
Node
Name
(Keyword)

Message

Parent NodeRequest.Operation.DigitalWatermark

The string embedded by thedigital watermark, which cancontain up to 64 letters, digits,
underscores (_), hyphens (-),
and asterisks (*).
Watermark type, whichType

Request.Operation.DigitalWatermark

currently can be set to Text
only

VersionRequest.Operation.DigitalWatermark

Watermark version, whichcurrently can be set to V1
only©2013-2022 Tencent Cloud. All rights reserved.

Page 1411 of 1869

Cloud Infinite

IgnoreError

Request.Operation.DigitalWatermark

Whether to ignore thestringYeswatermarking failure andcontinue the job. Valid values:
true , false (default)

Output has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

RequiredRegionRequest.Operation.Output

Bucket region

StringYes

BucketRequest.Operation.Output

Result storage bucket

StringYes

ObjectRequest.Operation.Output

Result file name

StringYes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1412 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([Body] => GuzzleHttp\\Psr7\\Stream Object([stream:GuzzleHttp\\Psr7\\Stream:private] => Resource id #88[size:GuzzleHttp\\Psr7\\Stream:private] =>[seekable:GuzzleHttp\\Psr7\\Stream:private] => 1
[readable:GuzzleHttp\\Psr7\\Stream:private] => 1
[writable:GuzzleHttp\\Psr7\\Stream:private] => 1
[uri:GuzzleHttp\\Psr7\\Stream:private] => php://temp[customMetadata:GuzzleHttp\\Psr7\\Stream:private] => Array©2013-2022 Tencent Cloud. All rights reserved.

Page 1413 of 1869

Cloud Infinite())[RequestId] => NjI2MjNjYHAOIHDOIADJHOIA18yMjFlMWE=[ContentType] => application/xml[ContentLength] => 965[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-beijing.myqcloud.com/jobs[Response] => Array([JobsDetail] => Array([Code] => Success[CreationTime] => 2022-04-22T11:19:15+0800[EndTime] => [Input] => Array([BucketId] => examplebucket-1250000000[Object] => video01.mp4[Region] => ap-beijing)[JobId] => jfd27519z8zx90c8z90c7809z9f35eb[Message] =>[Operation] => Array([Output] => Array([Bucket] => examplebucket-1250000000[Object] => VideoProcess.flv[Region] => ap-beijing)[TemplateId] => t13466f1eazx08c09zx8c09zx8e9cd[TemplateName] => video-process-1[TranscodeTemplateId] => t0b612860z087xc09zx8c09xz8c095[WatermarkTemplateId] => t185e2e24zxc780z8c0z98c323c642[UserData] => xxx[JobLevel] => 0)
[QueueId] => p81e648af2aee496885zx098c09z8xc09zxc086[StartTime] => [State] => Submitted[Tag] => VideoProcess©2013-2022 Tencent Cloud. All rights reserved.

Page 1414 of 1869

Cloud Infinite)))©2013-2022 Tencent Cloud. All rights reserved.

Page 1415 of 1869

Cloud Infinite

Video Montage Job APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for submitting a montage job.
API

Description

Submitting a video montage job

Submits a video montage job.

Submitting Video Montage Job
Feature description
This API is used to submit a montage job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1416 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model createMediaVideoMontageJobs(array $args = a

Sample request
Sample 1. Using a template©2013-2022 Tencent Cloud. All rights reserved.

Page 1417 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1418 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->createMediaVideoMontageJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'VideoMontage','QueueId' => 'p81e648af2aeexxxxxxxxxxxxxxxxxxx','Input' => array('Object' => 'video01.mp4'),'Operation' => array(////'TemplateId' => 't1fcc3770199e04737axxxxxxxxxxxxxx','Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'VideoMontage.mp4',),'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher),'CallBack' => '',));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Sample 2. Customizing parameters©2013-2022 Tencent Cloud. All rights reserved.

Page 1419 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1420 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->createMediaVideoMontageJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'VideoMontage','QueueId' => 'p81e648af2aeexxxxxxxxxxxxxxxxxxx','Input' => array('Object' => 'video01.mp4'),'Operation' => array('VideoMontage' => array('Duration' => '','Container' => array('Format' => '',),'Video' => array('Codec' => '','Width' => '','Height' => '','Fps' => '','Bitrate' => '','Crf' => '',),'Audio' => array('Codec' => '','Samplerate' => '','Bitrate' => '','Channels' => '','Remove' => '',
),

//
//

),
'Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'VideoMontage.mp4',),'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher),'CallBack' => '',));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failed©2013-2022 Tencent Cloud. All rights reserved.

Page 1421 of 1869

Cloud Infinite

echo($e);}

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description

Type

Required

Tag

RequestJob tag: VideoMontage

StringYes

Input

RequestInformation of the media file to be processed

Container

Yes

Operation

RequestOperation ruleContainer

Yes

QueueId

RequestQueue ID of the job

StringYes

StringNo

StringNo

StringNo

ContainerNo

Job callback format, which can be JSON or
CallBackFormat

RequestXML (default value). It takes priority over thatof the queue.
Job callback type, which can be Url (default

CallBackType

Requestvalue) or TDMQ . It takes priority over that of
the queue.

CallBack

RequestCallBackMqConfig

RequestJob callback address, which takes priority overthat of the queue. If it is set to no , nocallbacks will be generated at the callback
address of the queue.
TDMQ configuration for job callback as
described in Structure, which is required if
CallBackType is TDMQ .

Input has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

ObjectRequest.Input

Media filename

StringYes

Operation has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription©2013-2022 Tencent Cloud. All rights reserved.

Type

RequiredPage 1422 of 1869

Cloud Infinite

VideoMontage

Request.Operation

Video montage template parameterContainerNo

TemplateId

Request.Operation

Template ID

StringNo

OutputRequest.Operation

Result output address

Container

Yes

Request.Operation

The user information passed through,which is printable ASCII codes of up to
1,024 in length.

StringNo

StringNo

Type

RequiredContainerNo

ContainerNo

ContainerNo

ContainerNo

Container

No

UserData

JobLevel

Request.Operation

Job priority. The greater the value, thehigher the priority. Valid values: 0 , 1 ,2 . Default value: 0 .

Note:
TemplateId is used first. If TemplateId is unavailable, VideoMontage is used.
VideoMontage has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription
Same asRequest.TimeInterval in

TimeInterval

Request.Operation.Transcodethe transcoding template
creation API
CreateMediaTemplate.

Container

Request.Operation.Transcode

Same asRequest.Container in thetranscoding template creation
API CreateMediaTemplate.
Same as Request.Video in

Video

Request.Operation.Transcodethe transcoding template
creation API
CreateMediaTemplate.
Same as Request.Audio in

Audio

Request.Operation.Transcodethe transcoding template
creation API
CreateMediaTemplate.

TransConfig

Request.Operation.Transcode

Same asRequest.TransConfig in
the transcoding template©2013-2022 Tencent Cloud. All rights reserved.

Page 1423 of 1869

Cloud Infinite

creation API
CreateMediaTemplate.
AudioMix

Request.Operation.Transcode

Audio mix parameter as
described in Structure.

Container
array

No

Output has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

RequiredRegionRequest.Operation.Output

Bucket region

StringYes

BucketRequest.Operation.Output

Result storage bucket

StringYes

ObjectRequest.Operation.Output

Result file name

StringYes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1424 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([Body] => GuzzleHttp\\Psr7\\Stream Object([stream:GuzzleHttp\\Psr7\\Stream:private] => Resource id #88[size:GuzzleHttp\\Psr7\\Stream:private] =>[seekable:GuzzleHttp\\Psr7\\Stream:private] => 1
[readable:GuzzleHttp\\Psr7\\Stream:private] => 1
[writable:GuzzleHttp\\Psr7\\Stream:private] => 1
[uri:GuzzleHttp\\Psr7\\Stream:private] => php://temp[customMetadata:GuzzleHttp\\Psr7\\Stream:private] => Array©2013-2022 Tencent Cloud. All rights reserved.

Page 1425 of 1869

Cloud Infinite())[RequestId] => NjI2MjIxNDVfHAUOSDHAOIHDOIyMmZkOTQ=[ContentType] => application/xml[ContentLength] => 803[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-beijing.myqcloud.com/jobs[Response] => Array([JobsDetail] => Array([Code] => Success[CreationTime] => 2022-04-22T11:30:13+0800[EndTime] => [Input] => Array([BucketId] => examplebucket-1250000000[Object] => video01.mp4[Region] => ap-beijing)[JobId] => j85803a96zx7c98z7xc987z9c6eb232[Message] =>[Operation] => Array([Output] => Array([Bucket] => examplebucket-1250000000[Object] => VideoMontage.mp4[Region] => ap-beijing)[TemplateId] => t1fcc3770199e0zx7cz897c9zxc9b[TemplateName] => video-montage-1[UserData] => xxx[JobLevel] => 0)
[QueueId] => p81e648af2aezx7c9z7xc98zx7c98e086[StartTime] => [State] => Submitted[Tag] => VideoMontage)©2013-2022 Tencent Cloud. All rights reserved.

Page 1426 of 1869

Cloud Infinite))©2013-2022 Tencent Cloud. All rights reserved.

Page 1427 of 1869

Cloud Infinite

Voice/Sound Separation Job APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for submitting a voice/sound separation job.
API

Description

Submitting a voice/sound separation job

Submits a voice/sound separation job.

Submitting Voice/Sound Separation Job
Feature description
This API is used to submit a voice/sound separation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1428 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model createMediaVoiceSeparateJobs(array $args =Sample request
Sample 1. Using a template©2013-2022 Tencent Cloud. All rights reserved.

Page 1429 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1430 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->createMediaVoiceSeparateJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'VoiceSeparate','QueueId' => '','CallBack' => '','Input' => array('Object' => 'test.mp3'),'Operation' => array('TemplateId' => '','Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'VoiceSeparate01.mp3','AuObject' => 'VoiceSeparate02.mp3',
),
//
//

'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher),));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Sample 2. Customizing parameters©2013-2022 Tencent Cloud. All rights reserved.

Page 1431 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1432 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->createMediaVoiceSeparateJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'VoiceSeparate','QueueId' => '','CallBack' => '','Input' => array('Object' => 'test.mp3'),'Operation' => array('Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'VoiceSeparate01.mp3','AuObject' => 'VoiceSeparate02.mp3',),'VoiceSeparate' => array('AudioMode' => 'AudioAndBackground','AudioConfig' => array('Codec' => 'mp3','Samplerate' => '11025','Bitrate' => '256','Channels' => '2',),),
'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher

//
//
),

));
// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description

Type

Required

Tag

RequestJob tag: VoiceSeparate

StringYes©2013-2022 Tencent Cloud. All rights reserved.

Page 1433 of 1869

Cloud Infinite

Input

RequestInformation of the media file to be processed

Container

Yes

Operation

RequestOperation ruleContainer

Yes

QueueId

RequestQueue ID of the job

StringYes

StringNo

StringNo

StringNo

ContainerNo

Job callback format, which can be JSON or
CallBackFormat

RequestXML (default value). It takes priority over thatof the queue.
Job callback type, which can be Url (default

CallBackType

Requestvalue) or TDMQ . It takes priority over that of
the queue.

CallBack

RequestJob callback address, which takes priority overthat of the queue. If it is set to no , nocallbacks will be generated at the callback
address of the queue.

CallBackMqConfig

Request

TDMQ configuration for job callback as
described in Structure, which is required if
CallBackType is TDMQ .

Input has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

ObjectRequest.Input

Media filename

StringYes

Operation has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

VoiceSeparate

Request.Operation

Transcoding template parameterContainerNo

TemplateId

Request.Operation

Template ID

StringNo

OutputRequest.Operation

Result output address

Container

Yes

Request.Operation

Job priority. The greater the value, thehigher the priority. Valid values: 0 ,StringNo

JobLevel

1 , 2 . Default value: 0 .

Note:©2013-2022 Tencent Cloud. All rights reserved.

Page 1434 of 1869

Cloud Infinite

TemplateId is used first. If TemplateId is unavailable, VoiceSeparate is used.
VoiceSeparate has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

RequiredContainerNo

Container

No

Same asRequest.AudioMode in
AudioMode

Request.Operation.VoiceSeparate

the voice/sound separation
template creation API
CreateMediaTemplate.
Same asRequest.AudioConfig

AudioConfig

Request.Operation.VoiceSeparate

in the voice/soundseparation template creation
API CreateMediaTemplate.

Output has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeDescription

Type

RequiredRegionRequest.Operation.Output

Bucket region

StringYes

BucketRequest.Operation.Output

Result storage bucket

StringYes

Request.Operation.Output

Background audio result filename.
This node and AuObject cannot

StringNo

StringNo

Objectbe empty at the same time.
Voice/Sound result filename. This
AuObject

Request.Operation.AuObject

node and Object cannot be empty
at the same time.

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1435 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([Body] => GuzzleHttp\\Psr7\\Stream Object([stream:GuzzleHttp\\Psr7\\Stream:private] => Resource id #88[size:GuzzleHttp\\Psr7\\Stream:private] =>[seekable:GuzzleHttp\\Psr7\\Stream:private] => 1
[readable:GuzzleHttp\\Psr7\\Stream:private] => 1
[writable:GuzzleHttp\\Psr7\\Stream:private] => 1
[uri:GuzzleHttp\\Psr7\\Stream:private] => php://temp[customMetadata:GuzzleHttp\\Psr7\\Stream:private] => Array©2013-2022 Tencent Cloud. All rights reserved.

Page 1436 of 1869

Cloud Infinite())[RequestId] => NjI2MjIyOTHADOHDOADJHOjQ0OV8yMmU0OWM=[ContentType] => application/xml[ContentLength] => 857[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-beijing.myqcloud.com/jobs[Response] => Array([JobsDetail] => Array([Code] => Success[CreationTime] => 2022-04-22T11:35:47+0800[EndTime] => [Input] => Array([BucketId] => examplebucket-1250000000[Object] => test.mp3[Region] => ap-beijing)[JobId] => j4c70446zxc780z98xc09zxc6eb232[Message] =>[Operation] => Array([Output] => Array([AuObject] => VoiceSeparate02.mp3[Bucket] => examplebucket-1250000000[Object] => VoiceSeparate01.mp3[Region] => ap-beijing)[TemplateId] => t1456ea89fczx8c0z8c09z8c0985[TemplateName] => VoiceSeparate-1[UserData] => xxx[JobLevel] => 0)
[QueueId] => p81e648af2azc709zx8c09z8xc0z7be086[StartTime] => [State] => Submitted[Tag] => VoiceSeparate)©2013-2022 Tencent Cloud. All rights reserved.

Page 1437 of 1869

Cloud Infinite))©2013-2022 Tencent Cloud. All rights reserved.

Page 1438 of 1869

Cloud Infinite

SDR-to-HDR Job APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for SDR-to-HDR jobs.
API

Description

Submitting an SDR-to-HDR job

Submits an SDR-to-HDR job.

Submitting SDR-to-HDR Job
Feature description
This API is used to submit an SDR-to-HDR job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1439 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model createMediaSDRtoHDRJobs(array $args = array

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1440 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1441 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// Submit an SDR-to-HDR job. For more information, visit https://www.tencentclo$result = $cosClient->createMediaSDRtoHDRJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'SDRtoHDR','QueueId' => 'p81e648af2aee496885a8d09a8s09d8a0sd6','Input' => array('Object' => 'video01.mp4'),'Operation' => array('TranscodeTemplateId' => '','WatermarkTemplateId' => '','SDRtoHDR' => array('HdrMode' => 'HLG',),'Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'SDRtoHDR.flv',
),
//
//

'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher),'CallBack' => '',));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description

Type

Required

Tag

RequestJob tag: SDRtoHDR

StringYes

Input

RequestInformation of the media file to be processed

Container

Yes

Operation

RequestOperation ruleContainer

Yes©2013-2022 Tencent Cloud. All rights reserved.

Page 1442 of 1869

Cloud Infinite

QueueId

RequestQueue ID of the job

StringYes

StringNo

StringNo

StringNo

ContainerNo

Job callback format, which can be JSON or
CallBackFormat

RequestXML (default value). It takes priority over thatof the queue.
Job callback type, which can be Url (default

CallBackType

Requestvalue) or TDMQ . It takes priority over that of
the queue.
Job callback address, which takes priority over

CallBack

CallBackMqConfig

RequestRequestthat of the queue. If it is set to no , nocallbacks will be generated at the callback
address of the queue.
TDMQ configuration for job callback as
described in Structure, which is required if
CallBackType is TDMQ .

Input has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

ObjectRequest.Input

Media filename

StringYes

Operation has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

SDRtoHDR

Request.Operation

SDR-to-HDR parameterContainer

Yes

Container

No

StringNo

Container
array

No

Transcoding template parameter.
Transcode

Request.Operation

This node andTranscodeTemplateId
cannot be empty at the same time.

TranscodeTemplateId

Request.Operation

WatermarkRequest.Operation

Transcoding template ID. This
node and Transcode cannot
be empty at the same time. Use
this node first.
Watermark template parameter.
Same asRequest.Watermark in thewatermark template creation API©2013-2022 Tencent Cloud. All rights reserved.

Page 1443 of 1869

Cloud Infinite

CreateMediaTemplate. Up tothree watermarks can be passedin.
Watermark template ID. Up tothree watermark template IDs can
WatermarkTemplateId

Request.Operation

be passed in. If Watermark
and WatermarkTemplateId

Stringarray

NoContainer

Yes

StringNo

StringNoexist at the same time, use
WatermarkTemplateId first.
OutputRequest.Operation

Result output address
The user information passed

UserData

JobLevel

Request.Operation

Request.Operation

through, which is printable ASCII
codes of up to 1,024 in length.
Job priority. The greater the value,
the higher the priority. Validvalues: 0 , 1 , 2 . Default
value: 0 .

Note:
To submit an SDR-to-HDR job, you must pass in the transcoding parameter. For the transcoding parameter,
TranscodeTemplateId is used first, and if TranscodeTemplateId is unavailable, Transcode is used.
For the watermark parameter, WatermarkTemplateId or Watermark can be used for configuration, andWatermarkTemplateId is used first.
SDRtoHDR has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

HdrModeRequest.Operation.SDRtoHDR

HDR mode

StringYes

Constraints
1. HLG. 2.
HDR10.

Transcode has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

TimeInterval

Request.Operation.Transcode

Same asRequest.TimeInterval inContainerNo

the transcoding template
creation API
CreateMediaTemplate.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1444 of 1869

Cloud Infinite

Container

Request.Operation.Transcode

Same asRequest.Container in thetranscoding template creation

ContainerNo

ContainerNo

ContainerNo

ContainerNo

Container
array

No

API CreateMediaTemplate.
Same as Request.Video in
Video

Request.Operation.Transcodethe transcoding template
creation API
CreateMediaTemplate.
Same as Request.Audio in

Audio

Request.Operation.Transcodethe transcoding template
creation API
CreateMediaTemplate.
Same asRequest.TransConfig inTransConfig

Request.Operation.Transcodethe transcoding template
creation API
CreateMediaTemplate.

AudioMix

Request.Operation.Transcode

Audio mix parameter as
described in Structure.

Output has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

RequiredRegionRequest.Operation.Output

Bucket region

StringYes

BucketRequest.Operation.Output

Result storage bucket

StringYes

ObjectRequest.Operation.Output

Result file name

StringYes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1445 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([Body] => GuzzleHttp\\Psr7\\Stream Object([stream:GuzzleHttp\\Psr7\\Stream:private] => Resource id #88[size:GuzzleHttp\\Psr7\\Stream:private] =>[seekable:GuzzleHttp\\Psr7\\Stream:private] => 1
[readable:GuzzleHttp\\Psr7\\Stream:private] => 1
[writable:GuzzleHttp\\Psr7\\Stream:private] => 1
[uri:GuzzleHttp\\Psr7\\Stream:private] => php://temp[customMetadata:GuzzleHttp\\Psr7\\Stream:private] => Array©2013-2022 Tencent Cloud. All rights reserved.

Page 1446 of 1869

Cloud Infinite())[RequestId] => NjI2N2I1NWFfZmNjYTNHDOASJDOIA1Yw==[ContentType] => application/xml[ContentLength] => 902[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-guangzhou.myqcloud.com/jobs[Response] => Array([JobsDetail] => Array([Code] => Success[CreationTime] => 2022-04-26T17:03:22+0800[EndTime] => [Input] => Array([BucketId] => examplebucket-1250000000[Object] => video01.mp4[Region] => ap-guangzhou)[JobId] => jb9289626c53f11ec8a9c4f3d8d099dcb[Message] =>[Operation] => Array([Output] => Array([Bucket] => examplebucket-1250000000[Object] => SDRtoHDR.flv[Region] => ap-guangzhou)[SDRtoHDR] => Array([HdrMode] => HLG)[TranscodeTemplateId] => t0b612860a293f410785ba7s8d09a8[WatermarkTemplateId] => t185e2e24551b242d09a80d8a0d804[UserData] => xxx[JobLevel] => 0)
[QueueId] => t185e2e24551b242d09a80d8a0d80428a19c©2013-2022 Tencent Cloud. All rights reserved.

Page 1447 of 1869

Cloud Infinite[StartTime] => [State] => Submitted[Tag] => SDRtoHDR)))©2013-2022 Tencent Cloud. All rights reserved.

Page 1448 of 1869

Cloud Infinite

Digital Watermark Job APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for digital watermark.
API

Description

Submitting a digital watermark adding job

Submits a digital watermark adding job.

Submitting a digital watermark extracting job

Submits a digital watermark extracting job.

Digital Watermark Adding Job
Feature description
This API is used to submit a digital watermark adding job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1449 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model createMediaDigitalWatermarkJobs(array $args

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1450 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1451 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// Submit a digital watermark adding job. For more information, visit https://w$result = $cosClient->createMediaDigitalWatermarkJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'DigitalWatermark','QueueId' => 'p81e648af2aee496885707caxxxxxxxxxxxx','Input' => array('Object' => 'video01.mp4'),'Operation' => array('DigitalWatermark' => array('Message' => '123456789ab','Type' => 'Text','Version' => 'V1',),'Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'DigitalWatermark.mp4',
),
//
//

'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher),'CallBack' => '',));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description

Type

Required

Tag

RequestJob tag: DigitalWatermark

StringYes

Input

RequestInformation of the media file to be processed

Container

Yes

Operation

RequestOperation ruleContainer

Yes©2013-2022 Tencent Cloud. All rights reserved.

Page 1452 of 1869

Cloud Infinite

QueueId

RequestQueue ID of the job

StringYes

StringNo

StringNo

StringNo

ContainerNo

Job callback format, which can be JSON or
CallBackFormat

RequestXML (default value). It takes priority over thatof the queue.
Job callback type, which can be Url (default

CallBackType

Requestvalue) or TDMQ . It takes priority over that of
the queue.

CallBack

RequestCallBackMqConfig

RequestJob callback address, which takes priority overthat of the queue. If it is set to no , nocallbacks will be generated at the callback
address of the queue.
TDMQ configuration for job callback as
described in Structure, which is required if
CallBackType is TDMQ .

Input has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

ObjectRequest.Input

Media filename

StringYes

Operation has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

OutputRequest.Operation

Result output address

Container

Yes

DigitalWatermark

Request.Operation

Digital watermark configuration

Container

Yes

Request.Operation

Job priority. The greater the value, thehigher the priority. Valid values: 0 ,StringNo

StringNo

JobLevel

1 , 2 . Default value: 0 .

UserData

Request.Operation

The user information passed through,which is printable ASCII codes of up to
1,024 in length.

DigitalWatermark has the following sub-nodes:
Node
Name

Parent Node©2013-2022 Tencent Cloud. All rights reserved.

Description

Type

RequiredConstraints

Page 1453 of 1869

Cloud Infinite(Keyword)

MessageRequest.Operation.DigitalWatermark

The string
embedded by
the digitalwatermarkType

Request.Operation.DigitalWatermark

Watermarktype

VersionRequest.Operation.DigitalWatermark

Watermarkversion

It can containup to 64
letters, digits,
underscores(_), hyphens(-), andasterisks (*).

stringYes

StringYes

Text

StringYes

V1

Output has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

RequiredRegionRequest.Operation.Output

Bucket region

StringYes

BucketRequest.Operation.Output

Result storage bucket

StringYes

ObjectRequest.Operation.Output

Result file name

StringYes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1454 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([Body] => GuzzleHttp\\Psr7\\Stream Object([stream:GuzzleHttp\\Psr7\\Stream:private] => Resource id #88[size:GuzzleHttp\\Psr7\\Stream:private] =>[seekable:GuzzleHttp\\Psr7\\Stream:private] => 1
[readable:GuzzleHttp\\Psr7\\Stream:private] => 1
[writable:GuzzleHttp\\Psr7\\Stream:private] => 1
[uri:GuzzleHttp\\Psr7\\Stream:private] => php://temp[customMetadata:GuzzleHttp\\Psr7\\Stream:private] => Array©2013-2022 Tencent Cloud. All rights reserved.

Page 1455 of 1869

Cloud Infinite())[RequestId] => NjI2N2JlMDFfZmNjYAJSDIOAJDOIAJD9lZDYxOA==[ContentType] => application/xml[ContentLength] => 828[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-guangzhou.myqcloud.com/jobs[Response] => Array([JobsDetail] => Array([Code] => Success[CreationTime] => 2022-04-26T17:40:17+0800[EndTime] => [Input] => Array([BucketId] => examplebucket-1250000000[Object] => video01.mp4[Region] => ap-guangzhou)[JobId] => je1dc03f0c544as09d8as09d8a09dec25a93[Message] =>[Operation] => Array([DigitalWatermark] => Array([Message] => 123456789ab[Type] => Text
[Version] => V1)[Output] => Array([Bucket] => examplebucket-1250000000[Object] => DigitalWatermark.mp4[Region] => ap-guangzhou)[UserData] => xxx[JobLevel] => 0)
[QueueId] => p81e648af2aee49688570s8a90d80a9d86©2013-2022 Tencent Cloud. All rights reserved.

Page 1456 of 1869

Cloud Infinite[StartTime] => [State] => Submitted[Tag] => DigitalWatermark)))

Digital Watermark Extracting Job
Feature description
This API is used to submit a digital watermark extracting job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1457 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model createMediaExtractDigitalWatermarkJobs(arraSample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1458 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1459 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// Submit a digital watermark extracting job. For more information, visit https$result = $cosClient->createMediaExtractDigitalWatermarkJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'ExtractDigitalWatermark','QueueId' => 'p81e648af2aee496885707caxxxxxxxxx','Input' => array('Object' => 'DigitalWatermark.mp4'
),

//
//

'Operation' => array('ExtractDigitalWatermark' => array('Type' => 'Text','Version' => 'V1',),'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher),'CallBack' => '',));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Node Name

Parent(Keyword)

Node

Tag

Description

Type

Required

RequestJob tag: ExtractDigitalWatermark

StringYes

Input

RequestInformation of the media file to be processed

Container

Yes

Operation

RequestOperation ruleContainer

Yes

QueueId

RequestQueue ID of the job

StringYes

StringNo

Job callback format, which can be JSON or
CallBackFormat

RequestXML (default value). It takes priority over thatof the queue.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1460 of 1869

Cloud Infinite

CallBackType

RequestJob callback type, which can be Url (default

StringNo

StringNo

ContainerNo

value) or TDMQ . It takes priority over that of
the queue.
Job callback address, which takes priority over
CallBack

RequestCallBackMqConfig

Requestthat of the queue. If it is set to no , nocallbacks will be generated at the callback
address of the queue.
TDMQ configuration for job callback as
described in Structure, which is required if
CallBackType is TDMQ .

Input has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

ObjectRequest.Input

Media filename

StringYes

Operation has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

ExtractDigitalWatermark

Request.Operation

Digital watermark extraction
configuration

Container

Yes

StringNo

StringNo

JobLevel

Request.Operation

Job priority. The greater thevalue, the higher the priority.
Valid values: 0 , 1 , 2 .
Default value: 0 .

UserData

Request.Operation

The user information passed
through, which is printable
ASCII codes of up to 1,024 inlength.

ExtractDigitalWatermark has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeDescription

Type

RequiredConstraints

Type

Request.Operation.ExtractDigitalWatermark

Watermarktype

StringYes

Text

VersionRequest.Operation.ExtractDigitalWatermark

WatermarkStringYes

V1©2013-2022 Tencent Cloud. All rights reserved.

Page 1461 of 1869

Cloud Infinite

versionSample response

GuzzleHttp\\Command\\Result Object([Body] => GuzzleHttp\\Psr7\\Stream Object([stream:GuzzleHttp\\Psr7\\Stream:private] => Resource id #88[size:GuzzleHttp\\Psr7\\Stream:private] =>©2013-2022 Tencent Cloud. All rights reserved.

Page 1462 of 1869

Cloud Infinite[seekable:GuzzleHttp\\Psr7\\Stream:private] => 1
[readable:GuzzleHttp\\Psr7\\Stream:private] => 1
[writable:GuzzleHttp\\Psr7\\Stream:private] => 1
[uri:GuzzleHttp\\Psr7\\Stream:private] => php://temp[customMetadata:GuzzleHttp\\Psr7\\Stream:private] => Array())[RequestId] => NjI2OGI4YmZfZmNjYTNiAOISDAOIDUOMjU4ZjE=[ContentType] => application/xml[ContentLength] => 680[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-guangzhou.myqcloud.com/jobs[Response] => Array([JobsDetail] => Array([Code] => Success[CreationTime] => 2022-04-27T11:30:07+0800[EndTime] => [Input] => Array([BucketId] => examplebucket-1250000000[Object] => DigitalWatermark.mp4[Region] => ap-guangzhou)[JobId] => j56038a4cc5da1a8s0d98a90sd806cf06[Message] =>[Operation] => Array([ExtractDigitalWatermark] => Array([Type] => Text
[Version] => V1)[UserData] => xxx[JobLevel] => 0)
[QueueId] => p81e648af2aee4z9x8c09z8xc09zbe086[StartTime] => [State] => Submitted[Tag] => ExtractDigitalWatermark)©2013-2022 Tencent Cloud. All rights reserved.

Page 1463 of 1869

Cloud Infinite))©2013-2022 Tencent Cloud. All rights reserved.

Page 1464 of 1869

Cloud Infinite

Super Resolution Job APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for super resolution.
API

Description

Submitting a super resolution job

Submits a super resolution job.

Submitting Super Resolution Job
Feature description
Submitting a Super Resolution Task
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1465 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model createMediaSuperResolutionJobs(array $args

Sample request
Sample 1. Using a template©2013-2022 Tencent Cloud. All rights reserved.

Page 1466 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1467 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->createMediaSuperResolutionJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'SuperResolution','QueueId' => 'p81e648af2aee49688570xxxxxxxxxxx','Input' => array('Object' => 'video01.mp4'),'Operation' => array('TemplateId' =>'t19ea5e0c0b7054d7b904axxxxxxxxxxx','TranscodeTemplateId' =>'t0b612860a293f41078xxxxxxxxxxx','WatermarkTemplateId' =>'t185e2e24551b24259a02xxxxxxxxxxx','DigitalWatermark' => array('Message' => 'xxx','Type' => 'Text','Version' => 'V1',////'IgnoreError' => 'true',),'Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'SuperResolution.flv',),'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher),'CallBack' => '',));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Sample 2. Customizing parameters©2013-2022 Tencent Cloud. All rights reserved.

Page 1468 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1469 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->createMediaSuperResolutionJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'SuperResolution','QueueId' => 'p81e648af2aee49688570xxxxxxxxxxx','Input' => array('Object' => 'video01.mp4'),'Operation' => array('SuperResolution' => array('Resolution' => '','EnableScaleUp' => '',),'Transcode' => array('Tag' => '','Name' => '','Container' => array('Format' => '',),'Video' => array('Codec' => '','Width' => '','Height' => '','Fps' => '','Remove' => '','Profile' => '','Bitrate' => '','Crf' => '','Gop' => '','Preset' => '','Bufsize' => '','Maxrate' => '','HlsTsTime' => '','Pixfmt' => '','LongShortMode' => '',),'TimeInterval' => array('Start' => '','Duration' => '',),'Audio' => array('Codec' => '','Samplerate' => '','Bitrate' => '',©2013-2022 Tencent Cloud. All rights reserved.

Page 1470 of 1869

Cloud Infinite'Channels' => '','Remove' => '','KeepTwoTracks' => '','SwitchTrack' => '','SampleFormat' => '',),'TransConfig' => array('AdjDarMethod' => '','IsCheckReso' => '','ResoAdjMethod' => '','IsCheckVideoBitrate' => '','VideoBitrateAdjMethod' => '','IsCheckAudioBitrate' => '','AudioBitrateAdjMethod' => '','DeleteMetadata' => '','IsHdr2Sdr' => '','HlsEncrypt' => array('IsHlsEncrypt' => '','UriKey' => '',),),),'Watermark' => array('Type' => '','Pos' => '','LocMode' => '','Dx' => '','Dy' => '','StartTime' => '','EndTime' => '','Image' => array('Url' => '','Mode' => '','Width' => '','Height' => '','Transparency' => '','Background' => '',),'Text' => array('FontSize' => '','FontType' => '','FontColor' => '','Transparency' => '','Text' => '',),),'DigitalWatermark' => array(©2013-2022 Tencent Cloud. All rights reserved.

Page 1471 of 1869

Cloud Infinite'Message' => '','Type' => '','Version' => '','IgnoreError' => '',),'Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'SuperResolution.flv',
),
//
//

'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher),'CallBack' => '',));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description

Type

Required

Tag

RequestJob tag: SuperResolution

StringYes

Input

RequestInformation of the media file to be processed

Container

Yes

Operation

RequestOperation ruleContainer

Yes

QueueId

RequestQueue ID of the job

StringYes

StringNo

StringNo

StringNo

Job callback format, which can be JSON or
CallBackFormat

RequestXML (default value). It takes priority over thatof the queue.
Job callback type, which can be Url (default

CallBackType

Requestvalue) or TDMQ . It takes priority over that of
the queue.

CallBack

RequestJob callback address, which takes priority overthat of the queue. If it is set to no , no©2013-2022 Tencent Cloud. All rights reserved.

Page 1472 of 1869

Cloud Infinite

callbacks will be generated at the callback
address of the queue.

CallBackMqConfig

Request

TDMQ configuration for job callback as
described in Structure, which is required if

ContainerNo

CallBackType is TDMQ .

Input has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

ObjectRequest.Input

Media filename

StringYes

Operation has the following sub-nodes:
Node Name(Keyword)

SuperResolution

Parent NodeRequest.Operation

Description
Super resolution templateparameter. This node andTemplateId cannot be empty

TypeRequiredContainer

No

StringNo

Container

No

StringNoat the same time.

TemplateId

Request.Operation

Super resolution template ID,
which is used first. This node andSuperResolution cannot be
empty at the same time.
Transcoding template parameter.

Transcode

Request.Operation

This node andTranscodeTemplateId
cannot be empty at the same time.
Transcoding template ID. This

TranscodeTemplateId

Request.Operation

node and Transcode cannot
be empty at the same time. Use
this node first.
Watermark template parameter.
Same asRequest.Watermark in the

WatermarkRequest.Operationwatermark template creation API
CreateMediaTemplate. Up toContainer
array

No

three watermarks can be passedin.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1473 of 1869

Cloud Infinite

WatermarkTemplateId

Request.Operation

Watermark template ID. Up tothree watermark template IDs canStringarray

Nobe passed in. If Watermark
and WatermarkTemplateId
exist at the same time, use
WatermarkTemplateId first.
DigitalWatermark

Request.Operation

Specifies the digital watermark
parameter

ContainerNo

OutputRequest.Operation

Result output address

Container

Yes

Request.Operation

The user information passed
through, which is printable ASCII

StringNo

String

No

UserData

codes of up to 1,024 in length.

JobLevel

Request.Operation

Job priority. The greater the value,
the higher the priority. Validvalues: 0 , 1 , 2 . Default
value: 0 .

Note:
To submit a super resolution job, you must pass in the transcoding parameter. For the super resolution parameter,
TemplateId is used first, and if TemplateId is unavailable, SuperResolution is used. For thetranscoding parameter, TranscodeTemplateId is used first, and if TranscodeTemplateId is unavailable,
Transcode is used. For the watermark parameter, WatermarkTemplateId or Watermark can be used
for configuration, and WatermarkTemplateId is used first.
SuperResolution has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

RequireStringYes

StringNo

String

No

Same asRequest.Resolution in
Resolution

Request.Operation.SuperResolution

the super resolution template
creation API
CreateMediaTemplate.
Same asRequest.EnableScaleUp

EnableScaleUp

Request.Operation.SuperResolution

in the super resolution template
creation API
CreateMediaTemplate.

VersionRequest.Operation.SuperResolution©2013-2022 Tencent Cloud. All rights reserved.

Same asPage 1474 of 1869

Cloud Infinite

Request.Version in the
super resolution template
creation API
CreateMediaTemplate.

Transcode has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

RequiredContainerNo

ContainerNo

ContainerNo

ContainerNo

Container

No

Same asRequest.TimeInterval in
TimeInterval

Request.Operation.Transcodethe transcoding template
creation API
CreateMediaTemplate.
Same asContainer

Request.Operation.Transcode

Request.Container in thetranscoding template creation
API CreateMediaTemplate.
Same as Request.Video in

Video

Request.Operation.Transcodethe transcoding template
creation API
CreateMediaTemplate.
Same as Request.Audio in

Audio

Request.Operation.Transcodethe transcoding template
creation API
CreateMediaTemplate.
Same asRequest.TransConfig inTransConfig

Request.Operation.Transcodethe transcoding template
creation API
CreateMediaTemplate.

AudioMix

Request.Operation.Transcode

Audio mix parameter asContainer

described in Structure.

array

No

DigitalWatermark has the following sub-nodes:
Node
Name
(Keyword)

Parent Node©2013-2022 Tencent Cloud. All rights reserved.

Description

Type

RequiredPage 1475 of 1869

Cloud Infinite

MessageRequest.Operation.DigitalWatermark

The string embedded by theStringYes

StringYes

StringYes

stringNo

digital watermark, which cancontain up to 64 letters, digits,
underscores (_), hyphens (-),
and asterisks (*).
Watermark type, whichType

Request.Operation.DigitalWatermark

currently can be set to Text
only
Watermark version, which

VersionRequest.Operation.DigitalWatermark

currently can be set to V1
only

IgnoreError

Request.Operation.DigitalWatermark

Whether to ignore thewatermarking failure andcontinue the job. Valid values:
true , false (default).

Output has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

RequiredRegionRequest.Operation.Output

Bucket region

StringYes

BucketRequest.Operation.Output

Result storage bucket

StringYes

ObjectRequest.Operation.Output

Result file name

StringYes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1476 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([Body] => GuzzleHttp\\Psr7\\Stream Object([stream:GuzzleHttp\\Psr7\\Stream:private] => Resource id #88[size:GuzzleHttp\\Psr7\\Stream:private] =>[seekable:GuzzleHttp\\Psr7\\Stream:private] => 1
[readable:GuzzleHttp\\Psr7\\Stream:private] => 1
[writable:GuzzleHttp\\Psr7\\Stream:private] => 1
[uri:GuzzleHttp\\Psr7\\Stream:private] => php://temp[customMetadata:GuzzleHttp\\Psr7\\Stream:private] => Array©2013-2022 Tencent Cloud. All rights reserved.

Page 1477 of 1869

Cloud Infinite())[RequestId] => NjI2OGY4ZDdfZmNjYTNiMGAJODIJAOIDJAOMmVmNDU=[ContentType] => application/xml[ContentLength] => 1170
[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-guangzhou.myqcloud.com/jobs[Response] => Array([JobsDetail] => Array([Code] => Success[CreationTime] => 2022-04-27T16:03:35+0800[EndTime] => [Input] => Array([BucketId] => examplebucket-1250000000[Object] => video01.mp4[Region] => ap-guangzhou)[JobId] => j89be22b8c60011ec9070fasd8a09d80a9b8[Message] =>[Operation] => Array([DigitalWatermark] => Array([IgnoreError] => true
[Message] => xxx[State] => Running[Type] => Text
[Version] => V1)[Output] => Array([Bucket] => examplebucket-1250000000[Object] => SuperResolution.flv[Region] => ap-guangzhou)[TemplateId] => t19ea5e0c0b7b904a8sd09a8sd09a80sd10[TemplateName] => SuperResolution-1[TranscodeTemplateId] => t19ea5e0c0b7b904a8sd09a8sd09a8©2013-2022 Tencent Cloud. All rights reserved.

Page 1478 of 1869

Cloud Infinite[WatermarkTemplateId] => t19ea5e0c0b7b904a8sd09a8asdasd[UserData] => xxx[JobLevel] => 0)
[QueueId] => p81e648af2aee49688570asd8a90sd6[StartTime] => [State] => Submitted[Tag] => SuperResolution)))©2013-2022 Tencent Cloud. All rights reserved.

Page 1479 of 1869

Cloud Infinite

Video Tagging Job APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for video tagging.
API

Description

Submitting a video tagging job

Submits a video tagging job.

Submitting Video Tagging Job
Feature description
This API is used to submit a video tagging job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1480 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model createMediaVideoTagJobs(array $args = array

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1481 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1482 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// Submit a video tagging job. For more information, visit https://cloud.tencen$result = $cosClient->createMediaVideoTagJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'VideoTag','QueueId' => 'p81e648af2aee496885707ca0xxxxxxxxx','Input' => array('Object' => 'video01.mp4'
),

//
//

'Operation' => array('VideoTag' => array('Scenario' => 'Stream',),'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher),'CallBack' => '',));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description

Type

Required

Tag

RequestJob tag: VideoTag

StringYes

Input

RequestInformation of the media file to be processed

Container

Yes

Operation

RequestOperation ruleContainer

Yes

QueueId

RequestQueue ID of the job

StringYes

StringNo

StringNo

Job callback format, which can be JSON or
CallBackFormat

RequestXML (default value). It takes priority over thatof the queue.

CallBackType

RequestJob callback type, which can be Url (default©2013-2022 Tencent Cloud. All rights reserved.

Page 1483 of 1869

Cloud Infinite

value) or TDMQ . It takes priority over that of
the queue.
Job callback address, which takes priority over
CallBackthat of the queue. If it is set to no , noRequestCallBackMqConfig

callbacks will be generated at the callback
address of the queue.
TDMQ configuration for job callback as
described in Structure, which is required if
CallBackType is TDMQ .

RequestStringNo

Container

No

Input has the following sub-nodes:
Node
Name
(Keyword)

ObjectParent NodeDescription

Type

Required

Request.Input

Name of the media file on which to perform the video
tagging job. Currently, .mp4, .avi, .mkv, .wmv, .rmvb,.flv, and .mov formats are supported. For videos longer
than 30 minutes, submit a ticket for assistance.

StringYes

Operation has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeDescription

Type

RequiredVideoTag

Request.Operation

VideoTag job parameterContainer

Yes

StringNo

StringNo

JobLevel

Request.Operation

Job priority. The greater thevalue, the higher the priority.
Valid values: 0 , 1 , 2 .
Default value: 0 .

UserData

Response.JobsDetail.Operation

The user information passed
through.

VideoTag has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeDescription

Type

RequiredConstraints

Scenario

Request.Operation.VideoTag

Scenario type. You canstringYes

The©2013-2022 Tencent Cloud. All rights reserved.

Page 1484 of 1869

Cloud Infinite

select the application

current

scenario of the video
tag. The used algorithm,
input, and output varyby scenario.

version is
only
adapted totheStreamscenario

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1485 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([Body] => GuzzleHttp\\Psr7\\Stream Object([stream:GuzzleHttp\\Psr7\\Stream:private] => Resource id #88[size:GuzzleHttp\\Psr7\\Stream:private] =>[seekable:GuzzleHttp\\Psr7\\Stream:private] => 1
[readable:GuzzleHttp\\Psr7\\Stream:private] => 1
[writable:GuzzleHttp\\Psr7\\Stream:private] => 1
[uri:GuzzleHttp\\Psr7\\Stream:private] => php://temp[customMetadata:GuzzleHttp\\Psr7\\Stream:private] => Array())[RequestId] => NjI2OTI2ZTdfZaOAUSIODUJAIODJAIODViNWQ=[ContentType] => application/xml[ContentLength] => 610[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-guangzhou.myqcloud.com/jobs[Response] => Array([JobsDetail] => Array([Code] => Success[CreationTime] => 2022-04-27T19:20:07+0800[EndTime] => [Input] => Array([BucketId] => examplebucket-1250000000[Object] => video01.mp4[Region] => ap-guangzhou)[JobId] => jfe591374c61b11ec9ad8a098sd09asd8aa[Message] =>[Operation] => Array([VideoTag] => Array([Scenario] => Stream)[UserData] => xxx[JobLevel] => 0)©2013-2022 Tencent Cloud. All rights reserved.

Page 1486 of 1869

Cloud Infinite[QueueId] => p81e648af2aeea8d90a8s90d8a0de086[StartTime] => [State] => Submitted[Tag] => VideoTag)))©2013-2022 Tencent Cloud. All rights reserved.

Page 1487 of 1869

Cloud Infinite

Image Processing Job APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for image processing.
API

Description

Submitting an image processing job

Submits an image processing job.

Submit Image Processing Job
Feature description
This API is used to submit an image processing job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1488 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model createMediaPicProcessJobs(array $args = arr

Sample request
Sample 1. Using a template©2013-2022 Tencent Cloud. All rights reserved.

Page 1489 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1490 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->createMediaPicProcessJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'PicProcess','QueueId' => 'pcf4d6d9e5e734asd0as8d09as8d09a8d0','Input' => array('Object' => 'test01.png'),'Operation' => array(////'TemplateId' => 't1648745f76c354e8ad8a09sd890ad80a8d','Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'picprocess.jpg',),'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher),'CallBack' => '',));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Sample 2. Customizing parameters©2013-2022 Tencent Cloud. All rights reserved.

Page 1491 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1492 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {$result = $cosClient->createMediaPicProcessJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'PicProcess','QueueId' => 'pcf4d6d9e5e734asd0as8d09as8d09a8d0','Input' => array('Object' => 'test01.png'),'Operation' => array('PicProcess' => array('IsPicInfo' => '','ProcessRule' => '',),'Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'picprocess.jpg',
),
//
//

'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher),'CallBack' => '',));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description

Type

Required

Tag

RequestJob tag: PicProcess

StringYes

Input

RequestInformation of the media file to be processed

Container

Yes

Operation

RequestOperation ruleContainer

Yes

QueueId

RequestQueue ID of the job

StringYes©2013-2022 Tencent Cloud. All rights reserved.

Page 1493 of 1869

Cloud Infinite

CallBackFormat

RequestJob callback format, which can be JSON or

StringNo

StringNo

StringNo

ContainerNo

XML (default value). It takes priority over thatof the queue.
Job callback type, which can be Url (default
CallBackType

Requestvalue) or TDMQ . It takes priority over that of
the queue.

CallBack

RequestCallBackMqConfig

RequestJob callback address, which takes priority overthat of the queue. If it is set to no , nocallbacks will be generated at the callback
address of the queue.
TDMQ configuration for job callback as
described in Structure, which is required if
CallBackType is TDMQ .

Input has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

ObjectRequest.Input

Media filename

StringYes

Operation has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeDescription

Job type parameter. Same as
Request.PicProcess in the image

Type

RequiredContainerNo

PicProcess

Request.Operation

TemplateId

Request.Operation

Template ID

StringNo

OutputRequest.Operation

Result output address

Container

Yes

Request.Operation

The user information passed through, which
is printable ASCII codes of up to 1,024 inlength.

StringNo

String

No

UserData

processing template creation API
CreateMediaTemplate .

Job priority. The greater the value, the higher
JobLevel

Request.Operation

the priority. Valid values: 0 , 1 , 2 .
Default value: 0 .

©2013-2022 Tencent Cloud. All rights reserved.

Page 1494 of 1869

Cloud Infinite

Note:
TemplateId is used first. If TemplateId is unavailable, the corresponding job type parameter is used.
Output has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

RequiredRegionRequest.Operation.Output

Bucket region

StringYes

BucketRequest.Operation.Output

Result storage bucket

StringYes

ObjectRequest.Operation.Output

Result filename.

StringYes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1495 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([Body] => GuzzleHttp\\Psr7\\Stream Object([stream:GuzzleHttp\\Psr7\\Stream:private] => Resource id #88[size:GuzzleHttp\\Psr7\\Stream:private] =>[seekable:GuzzleHttp\\Psr7\\Stream:private] => 1
[readable:GuzzleHttp\\Psr7\\Stream:private] => 1
[writable:GuzzleHttp\\Psr7\\Stream:private] => 1
[uri:GuzzleHttp\\Psr7\\Stream:private] => php://temp[customMetadata:GuzzleHttp\\Psr7\\Stream:private] => Array©2013-2022 Tencent Cloud. All rights reserved.

Page 1496 of 1869

Cloud Infinite())[RequestId] => NjI2N2E4NTRfNzgwYzAJODIAUSIODUAU3ZQ==[ContentType] => application/xml[ContentLength] => 795[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-guangzhou.myqcloud.com/pic_jobs[Response] => Array([JobsDetail] => Array([Code] => Success[CreationTime] => 2022-04-26T16:07:48+0800[EndTime] => [Input] => Array([BucketId] => examplebucket-1250000000[Object] => test01.png[Region] => ap-guangzhou)[JobId] => cf62e1d50c5sa98d09a8d0a6cf06[Message] =>[Operation] => Array([Output] => Array([Bucket] => examplebucket-1250000000[Object] => picprocess.jpg[Region] => ap-guangzhou)[TemplateId] => t1648745f76asd70as8d90as8d0aa8a09[TemplateName] => PicProcess-1[UserData] => xxx[UserData] => 0)
[QueueId] => pcf4d6d9e5e734d0b82eas90d8a90sdd0[StartTime] => [State] => Submitted[Tag] => PicProcess)©2013-2022 Tencent Cloud. All rights reserved.

Page 1497 of 1869

Cloud Infinite))©2013-2022 Tencent Cloud. All rights reserved.

Page 1498 of 1869

Cloud Infinite

Remuxing Job APIs：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for remuxing.
API

Description

Submitting a remuxing job

Submits a remuxing job

Submitting Remuxing Job
Feature description
Submitting Remuxing Job
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1499 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model createMediaSegmentJobs(array $args = array(

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1500 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1501 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// Submit a remuxing job. For more information, visit https://www.tencentcloud.
$result = $cosClient->createMediaSegmentJobs(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'Segment','QueueId' => 'p81e648af2aee496885707ca0xxxxxxxxx','Input' => array('Object' => 'video01.mp4'),'Operation' => array('Segment' => array('Format' => 'mkv','Duration' => '5',
'HlsEncrypt' => array('IsHlsEncrypt' => 'false','UriKey' => '',),),'Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000','Object' => 'Segment-trans${Number}.mkv',),'UserData' => 'xxx', // The user information passed through.
'JobLevel' => '0', // Job priority. The greater the value, the higher

//
//

),
'CallBack' => '',));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description

Type

Required

Tag

RequestTask type: Segment

StringYes©2013-2022 Tencent Cloud. All rights reserved.

Page 1502 of 1869

Cloud Infinite

Input

RequestInformation of the media file to beprocessed

Container

Yes

Operation

RequestOperation ruleContainer

Yes

QueueId

RequestQueue ID of the job

StringYes

CallBack

RequestCallback address

StringNo

Input has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

ObjectRequest.Input

Media filename

StringYes

Operation has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Required

Segment

Request.Operation

Remuxing parameterContainer

Yes

OutputRequest.Operation

Result output address

Container

Yes

Segment has the following sub-nodes:
Node
Name

Parent NodeDescription

Request.Operation.Segment

Container
formatRequest.Operation.Segment

Remuxing
duration inseconds

Type

RequiredConstraints

Yes

aac, mp3, flac,
mp4, ts, mkv, avi,hls, m3u8

No

The value must be
an integer not lessthan 5.

No

None. Thisparameter takes
effect only when
the container
format is hls .

(Keyword)

FormatDuration

HlsEncrypt

Request.Operation.Segment

HLS
encryption
configuration

StringStringContainer

HlsEncrypt has the following sub-nodes:
Node Name

Parent Node©2013-2022 Tencent Cloud. All rights reserved.

Description

Type

Required

Default

C

Page 1503 of 1869

Cloud Infinite(Keyword)

Value
1.

IsHlsEncrypt

Request.Operation.Segment.HlsEncrypt

Whether toenableHLS
encryption

String

No

false

2.
su
is

UriKeyRequest.Operation.Segment.HlsEncrypt

HLS
encryption
key

String

No

None

T
va

Output has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeDescription

Type

RequiredRegionRequest.Operation.Output

Bucket region

StringYes

BucketRequest.Operation.Output

Result storage bucket

StringYes

StringYes

Output result filename. If Duration is
configured and Format is not HLS or
m3u8, the ${Number} parameter must
ObjectRequest.Operation.Output

be included in the filename and used as
the output sequence number of eachaudio/video segment after custom
remuxing.

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1504 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([Body] => GuzzleHttp\\Psr7\\Stream Object([stream:GuzzleHttp\\Psr7\\Stream:private] => Resource id #88[size:GuzzleHttp\\Psr7\\Stream:private] =>[seekable:GuzzleHttp\\Psr7\\Stream:private] => 1
[readable:GuzzleHttp\\Psr7\\Stream:private] => 1
[writable:GuzzleHttp\\Psr7\\Stream:private] => 1
[uri:GuzzleHttp\\Psr7\\Stream:private] => php://temp[customMetadata:GuzzleHttp\\Psr7\\Stream:private] => Array©2013-2022 Tencent Cloud. All rights reserved.

Page 1505 of 1869

Cloud Infinite())[RequestId] => NjI2YTA2MzZfZAODIJAIODJAIODZF8xNjc2YTA=[ContentType] => application/xml[ContentLength] => 866[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-guangzhou.myqcloud.com/jobs[Response] => Array([JobsDetail] => Array([Code] => Success[CreationTime] => 2022-04-28T11:12:54+0800[EndTime] => [Input] => Array([BucketId] => examplebucket-1250000000[Object] => video01.mp4[Region] => ap-guangzhou)[JobId] => j184996a2c6a111ec954767a8248f19aa[Message] =>[Operation] => Array([Output] => Array([Bucket] => examplebucket-1250000000[Object] => Segment-trans${Number}.mkv[Region] => ap-guangzhou)[Segment] => Array([Duration] => 10[Format] => mkv[HlsEncrypt] => Array([IsHlsEncrypt] => false[UriKey] =>))[UserData] => xxx©2013-2022 Tencent Cloud. All rights reserved.

Page 1506 of 1869

Cloud Infinite[JobLevel] => 0)
[QueueId] => p81e648af2az8x7ca0898s0dasbe086[StartTime] => [State] => Submitted[Tag] => Segment)))©2013-2022 Tencent Cloud. All rights reserved.

Page 1507 of 1869

Cloud Infinite

Template APIs
Template Search API：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for template search.
API

Description

Searching for animated image templates

Searches for animated image templates.

Searching for screenshot templates

Searches for screenshot templates.

Searching for watermark templates

Searches for watermark templates.

Searching for transcoding templates

Searches for transcoding templates.

Searching for splicing templates

Searches for splicing templates.

Searching for top speed codec transcoding templates

Searches for top speed codec transcoding templates.

Searching for video montage templates

Searches for video montage templates.

Searching for voice/sound separation templates

Searches for voice/sound separation templates.

Searching for video enhancement templates

Searches for video enhancement templates.

Searching for image processing templates

Searches for image processing templates.

Searching for super resolution templates

Searches for super resolution templates.

Searching for Template
Feature description
This API is used to search for templates of diverse types, such as Animation, Snapshot, Watermark, Transcode,
Concat, HighSpeedHd, VideoMontage, VoiceSeparate, VideoProcess, PicProcess, and SuperResolution.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1508 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model describeMediaTemplates(array $args = array(

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1509 of 1869

Cloud Infinite<?php
require dirname(__FILE__) . '/../vendor/autoload.php';$secretId = "SECRETID"; // Replace it with your actual `secretId`, which can be vie$secretKey = "SECRETKEY"; // Replace it with your actual `secretKey`, which can be$region = "ap-beijing"; // Replace it with the actual region, which can be viewed i$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol header, which is `http` by default.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1510 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// Query the template list
$result = $cosClient->describeMediaTemplates(array('Bucket' => 'examplebucket-125000000', // Bucket name in the format of `Buc
'Tag' => '', // Template type. Valid values: `Animation`, `Snapshot`, `Wate'Category' => 'Custom','Ids' => '','Name' => '','PageNumber' => '','PageSize' => '',));// The request succeeded.
print_r($result);} catch (\\Exception $e) {// The request failed.
echo($e);}

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description

Type

Required

Tag

None

Template type

StringYes

Category

None

String

No

Ids

None

String

No

Name

None

Template name prefix

StringNo

PageNumber

None

Page number

Integer

No

PageSize

None

Number of entries per page

IntegerNo

Template category: Custom or Official .
Default value: Custom .
Template ID. If you enter multiple IDs, separate themby comma.

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1511 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([RequestId] => NjJhOTRlZDFfNzgwYzdkAOIUDOAIUDTA4ZWE=[ContentType] => application/xml[ContentLength] => 782[TotalCount] => 1
[PageNumber] => 1
[PageSize] => 10[TemplateList] => Array([0] => Array©2013-2022 Tencent Cloud. All rights reserved.

Page 1512 of 1869

Cloud Infinite([TemplateId] => t1456ea89fcbdf45basd7fa98sd97a5[Name] => VoiceSeparate-Name[State] => Normal[Tag] => VoiceSeparate[CreateTime] => 2021-12-27T22:19:15+0800[UpdateTime] => 2021-12-27T22:19:15+0800[BucketId] => examplebucket-125000000[Category] => Custom[VoiceSeparate] => Array([AudioMode] => AudioAndBackground[AudioConfig] => Array([Codec] => mp3[Samplerate] => 44100[Bitrate] => 128[Channels] => 2))))
[Bucket] => examplebucket-125000000[Location] => examplebucket-125000000.ci.ap-guangzhou.myqcloud.com/template)©2013-2022 Tencent Cloud. All rights reserved.

Page 1513 of 1869

Cloud Infinite

File Processing
Multi-File Zipping：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for multi-file zipping.
API

Description

Submitting a multi-file zipping job

The multi-file zipping feature uses a POST request to zip multiple files into
a compressed file such as a ZIP file. You can submit a job to zip multiple
files and asynchronously return the compressed file.

Querying the multi-file zipping
resultThis API is used to query the result of a specified multi-file zipping job.

Submitting a Multi-File Zipping Job
Feature description
The multi-file zipping feature uses a POST request to zip multiple files into a compressed file such as a ZIP file. You
can submit a job to zip multiple files and asynchronously return the compressed file.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1514 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model createFileCompressJobs(array $args = array(

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1515 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; //Replace it with the actual `region`, which can be viewed$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1516 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// https://www.tencentcloud.com/document/product/436/53995: Submitting a Multi$result = $cosClient->createFileCompressJobs(array(//'Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'FileCompress','QueueId' => 'pcc3ae89sa9d807fs89dg789sdg','Operation' => array('UserData' => 'xxx','FileCompressConfig' => array('Flatten' => '0','Format' => 'zip','UrlList' => 'test/index.csv','Prefix' => 'test/','Keys' => array('object1', // File in the bucket to be zipped'object2', // File in the bucket to be zipped////'object3', // File in the bucket to be zipped),),'Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma'Object' => 'output/test.zip',
),
),
//
//
//
//
//
//
//
//

'CallBackFormat' => '','CallBackType' => '','CallBack' => '','CallBackMqConfig' => array('MqRegion' => '','MqMode' => '','MqName' => '',),));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:©2013-2022 Tencent Cloud. All rights reserved.

Page 1517 of 1869

Cloud Infinite

Node Name(Keyword)

Parent
Node

Tag

RequestOperation

RequestQueueId

CallBackFormat

Description

Type

Required

StringYes

File zipping rule.

Container

Yes

RequestID of the queue where the job is in.

StringYes

RequestJob callback format, which can be
JSON or XML (default). It takes

StringNo

StringNo

StringNo

ContainerNo

Job type. It is FileCompress for
multi-file zipping by default.

priority over that of the queue.
Job callback type, which can be Url
CallBackType

Request(default) or TDMQ . It takes priority overthat of the queue.

CallBack

RequestCallBackMqConfig

RequestJob callback address. It takes priority
over that of the queue.
TDMQ configuration for job callback as
described in Structure, which is required
if CallBackType is TDMQ .

Operation has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

FileCompressConfig

Request.Operation

File zipping rule.

Container

Yes

UserData

Request.Operation

The user information passed
through, which is printable
ASCII codes of up to 1,024 inlength.

StringNo

OutputRequest.Operation

Address where the compressed
file is stored.

Container

Yes

FileCompressConfig has the following sub-nodes:
Node
Name

Parent NodeDescription

Type(Keyword)©2013-2022 Tencent Cloud. All rights reserved.

Page 1518 of 1869

Cloud Infinite

FlattenRequest.Operation.FileCompressConfig

Whether to remove the directory structure of
the original file during file zipping. Valid

Stringvalues:0 : No. After file zipping, the original
directory structure is retained.
1 : Yes. After file zipping, the original
directory structure is removed and all files
are at the same level. Assume that theoriginal file URL is
https://domain/source/test.mp4
and the original file directory issource/test.mp4 . If this parameter is
set to 1 , the file directory in the ZIP file istest.mp4 . If this parameter is set to
0 , the file directory in the ZIP file issource/test.mp4 .
FormatRequest.Operation.FileCompressConfig

Zipping type. Valid values: zip , tar ,tar.gz .

StringFiles to be zipped can be sorted into anindex file. The backend zips the files into acompressed file according to the file URL
provided in the index file. The index file mustbe saved in the current bucket, and this fieldmust provide the object address of the index
file, for example, /test/index.csv .
UrlListRequest.Operation.FileCompressConfig

Index file format: Only CSV files in which one
URL occupies one row (only files in theStringbucket are supported) are supported. If
there are multiple columns, the first column
is used as the URL by default. The numberof files cannot exceed 10,000 and the total
size cannot exceed 50 GB. Otherwise, thejob will fail.
Files with a specified prefix in the bucket canbe zipped. To zip files in a specified
directory, add / to the directory. For
Prefix

Request.Operation.FileCompressConfig

example, to zip files in the test directory,
set this parameter to test/ . The number

Stringof files cannot exceed 10,000 and the total
size cannot exceed 50 GB. Otherwise, thejob will fail.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1519 of 1869

Cloud Infinite

Key

Request.Operation.FileCompressConfig

Multiple files in the bucket can be zipped.
The number of files cannot exceed 1,000

Stringarray

and the total size cannot exceed 50 GB.
Otherwise, the job will fail.

Note:
Only one of UrlList, Prefix, and Key can be selected. They cannot all be empty or do not take effect at the same time. If
multiple parameters are specified, the parameter with the highest priority prevails according to the priority UrlList >Prefix > Key.
Output has the following sub-nodes:
Node Name(Keyword)
RegionParent NodeDescription

Type

Required

Request.Operation.Output

Bucket region.

StringYes

StringYes

StringYes

Bucket where the
BucketRequest.Operation.Output

ObjectRequest.Operation.Output

compressed file isstored.
Name of thecompressed file.

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1520 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([RequestId] => NjNkOGM2NmVfZTYxNmY5MSAASJPOJCIANSIDNAI=[ContentType] => application/xml[ContentLength] => 827[JobsDetail] => Array([Progress] => 0
[Code] => Success[Message] =>[JobId] => fcd32dbdaa13b11esa9ds8g0d98gd0h85©2013-2022 Tencent Cloud. All rights reserved.

Page 1521 of 1869

Cloud Infinite[Tag] => FileCompress[State] => Submitted[CreationTime] => 2023-01-31T16:17:21+0800[StartTime] => [EndTime] => [QueueId] => pcc3ae89sa9d807fs89dg789sdg[Operation] => Array([JobLevel] => 0
[UserData] => xxx[Output] => Array([Region] => ap-guangzhou[Bucket] => examplebucket-1250000000[Object] => tmp/test.zip)[FileCompressConfig] => Array([Flatten] => 0
[Format] => zip[UrlList] =>[Prefix] =>[Key] => Array([0] => test1.png[1] => test2.jpeg))))[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-guangzhou.myqcloud.com/file_jobs)

Querying Multi-File Zipping Result
Feature description
This API is used to query the result of a specified multi-file zipping job.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1522 of 1869

Cloud Infinite

Method prototype

public Guzzle\\Service\\Resource\\Model getFileCompressResult(array $args = array()Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1523 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; //Replace it with the actual `region`, which can be viewed$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', //Protocol, which is http by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1524 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// https://www.tencentcloud.com/document/product/436/53996: Querying Multi-File$result = $cosClient->getFileCompressResult(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => '', // jobId));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Parameter

Type

Description

Required

BucketStringBucket name in the format of
BucketName-APPID .

Yes

Key

StringjobId

Yes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1525 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([RequestId] => NjNkOGM2NmVfZTYxNmY5MSAASJPOJCIANSIDNAI=[ContentType] => application/xml[ContentLength] => 1093
[JobsDetail] => Array([Progress] => 100[Code] => Success[Message] => success[JobId] => fcd32dbdaa13b11esa9ds8g0d98gd0h85©2013-2022 Tencent Cloud. All rights reserved.

Page 1526 of 1869

Cloud Infinite[Tag] => FileCompress[State] => Success[CreationTime] => 2023-01-31T16:17:21+0800[StartTime] => 2023-01-31T16:17:21+0800[EndTime] => 2023-01-31T16:17:22+0800[QueueId] => pcc3ae89sa9d807fs89dg789sdg[Operation] => Array([JobLevel] => 0
[UserData] => xxx[Output] => Array([Region] => ap-guangzhou[Bucket] => examplebucket-1250000000[Object] => tmp/test.zip)[FileCompressConfig] => Array([Flatten] => 0
[Format] => zip[UrlList] =>[Prefix] =>[Key] => Array([0] => test1.png[1] => test2.jpeg))[FileCompressResult] => Array([CompressFileCount] => 2
[Region] => ap-guangzhou[Bucket] => examplebucket-1250000000[Object] => tmp/test.zip)))[Key] => fcd32dbdaa13b11esa9ds8g0d98gd0h85[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-guangzhou.myqcloud.com/file_jobs/f)©2013-2022 Tencent Cloud. All rights reserved.

Page 1527 of 1869

Cloud Infinite©2013-2022 Tencent Cloud. All rights reserved.

Page 1528 of 1869

Cloud Infinite

Hash Calculation：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for hash calculation.

API

Description

Submitting a sync request
for hash calculation

Uses a sync GET request to perform hash calculation and return a calculated
hash value in real time.

Submitting a hashcalculation job

Adopts a POST request method. You can submit a job to perform hashcalculation and asynchronously return a calculated hash value.

Querying the hashcalculation result

Queries the result of a specified hash calculation job.

Sync Request for Hash Calculation
Feature description
This API uses a sync GET request to perform hash calculation and return a calculated hash value in real time.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1529 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model FileJobs4Hash(array $args = array());

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1530 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; //Replace it with the actual `region`, which can be viewed$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1531 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// https://www.tencentcloud.com/document/product/436/53990: Sync Request for Ha$result = $cosClient->FileJobs4Hash(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => 'for-test.mp4', // File in the bucket'Type' => 'md5', // Supported hash algorithm. Valid values: `md5`, `sha1`,'AddToHeader' => 'true', // Whether to automatically add the calculated h//));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);/*** Possible exceptions* 1. Error Message: file processing is not active yet, please apply for file p**/

Solution: Activate the file processing service.

}

Parameter description
Request has the following sub-nodes:
Parameter

Type

Description

Required

BucketStringBucket name in the format of BucketName-APPID .

Yes

Key

StringFile in the bucket

Yes

Type

String

AddToHeader

StringSupported hash algorithm. Valid values: md5 , sha1 ,sha256 .
Whether to automatically add the calculated hash value to thecustom header in the file. Format: x-cos-meta-md5/sha1/sha256.
Valid values: true , false . If this parameter is left empty, it

Yes

No

is false by default.

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1532 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([RequestId] => NjNkOGM2NmVfZTYxNmY5MSAASJPOJCIANSIDNAI[ContentType] => application/xml[ContentLength] => 421[FileHashCodeResult] => Array([Etag] => "1f3ede740849eaa2e79e9b269ea3db2a"[LastModified] => 2023-01-29T11:31:02+0000[MD5] => 1f3ede740849eaa2e79e9b269ea3db2a[FileSize] => 42120©2013-2022 Tencent Cloud. All rights reserved.

Page 1533 of 1869

Cloud Infinite)[Input] => Array([Region] => ap-guangzhou[Bucket] => examplebucket-1250000000[Object] => sound01.mp3)[Key] => sound01.mp3[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/sound01.mp)

Submitting a Hash Calculation Job
Feature description
This API adopts a POST request method. You can submit a job to perform hash calculation and asynchronously
return a calculated hash value.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1534 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model createFileHashCodeJobs(array $args = array(

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1535 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; //Replace it with the actual `region`, which can be viewed$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1536 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// https://www.tencentcloud.com/document/product/436/53991: Submitting a Hash C$result = $cosClient->createFileHashCodeJobs(array(//'Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'FileHashCode','QueueId' => 'pcc3ae89sa9d807fs89dg789sdg','Input' => array('Object' => 'test.mp4',),'Operation' => array('UserData' => 'xxx','FileHashCodeConfig' => array('Type' => 'MD5','AddToHeader' => 'true',
),
),

//
//
//
//
//
//
//
//

'CallBackFormat' => '','CallBackType' => '','CallBack' => '','CallBackMqConfig' => array('MqRegion' => '','MqMode' => '','MqName' => '',),));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Node Name

Parent(Keyword)

Node

Tag

Request

Input

RequestDescription
Job type. It is FileHashCode for hashcalculation by default.
Information about the file to be operated.

©2013-2022 Tencent Cloud. All rights reserved.

Type

Required

StringYes

Container

Yes

Page 1537 of 1869

Cloud Infinite

Operation

RequestHash calculation rule.

Container

Yes

QueueId

RequestID of the queue where the job is in.

StringYes

StringNo

StringNo

Job callback format, which can be JSON
CallBackFormat

Requestor XML (default). It takes priority over thatof the queue.
Job callback type, which can be Url

CallBackType

Request(default) or TDMQ . It takes priority overthat of the queue.

CallBack

CallBackMqConfig

RequestJob callback address. It takes priority overthat of the queue.

String

No

Request

TDMQ configuration for job callback as
described in Structure, which is required if
CallBackType is TDMQ .

Container

No

Input has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

ObjectRequest.Input

Filename, which is the full name of thefile in the bucket.

StringYes

Operation has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

FileHashCodeConfig

Request.Operation

Hash calculation rule.

Container

Yes

Request.Operation

The user information passed
through, which is printable ASCII
codes of up to 1,024 in length.

String

No

UserData

FileHashCodeConfig has the following sub-nodes:
Node Name(Keyword)Type

Parent NodeDescription

Type

Required

Request.Operation.FileHashCodeConfig

Hash algorithm. Validvalues: MD5 ,StringYes

SHA1 , SHA256 .

©2013-2022 Tencent Cloud. All rights reserved.

Page 1538 of 1869

Cloud Infinite

AddToHeader

Request.Operation.FileHashCodeConfig

Whether to add thecalculated hash value
to the custom header inthe file. Valid values:

StringNotrue , false(default). The custom
header varies
depending on Type .
For example, if
Type is MD5 , thecustom header is xcos-meta-md5 .

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1539 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([RequestId] => NjNkOGM2NmVfZTYxNmY5MSAASJPOJCIANSIDNAI=[ContentType] => application/xml[ContentLength] => 738[JobsDetail] => Array([Progress] => 0
[Code] => Success[Message] =>[JobId] => fcd32dbdaa13b11esa9ds8g0d98gd0h85©2013-2022 Tencent Cloud. All rights reserved.

Page 1540 of 1869

Cloud Infinite[Tag] => FileHashCode[State] => Submitted[CreationTime] => 2023-01-31T15:49:33+0800[StartTime] => [EndTime] => [QueueId] => pcc3ae89sa9d807fs89dg789sdg[Input] => Array([BucketId] => examplebucket-1250000000[Region] => ap-guangzhou[Object] => sound01.mp3)[Operation] => Array([JobLevel] => 0
[UserData] => xxx[FileHashCodeConfig] => Array([Type] => MD5[AddToHeader] => true)))
[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-guangzhou.myqcloud.com/file_jobs)

Querying Hash Calculation Result
Feature description
This API is used to query the result of a specified hash calculation job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1541 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model getFileHashCodeResult(array $args = array()Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1542 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; //Replace it with the actual `region`, which can be viewed$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', //Protocol, which is http by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1543 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// https://www.tencentcloud.com/document/product/436/53992: Querying Hash Calcu$result = $cosClient->getFileHashCodeResult(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => '', // jobId));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Parameter

Type

Description

Required

BucketStringBucket name in the format of BucketName-APPID .

Yes

Key

StringjobId

Yes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1544 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([RequestId] => NjNkOGM2NmVfZTYxNmY5MSAASJPOJCIANSIDNAI=[ContentType] => application/xml[ContentLength] => 1048
[JobsDetail] => Array([Progress] => 100[Code] => Success[Message] => success[JobId] => fcd32dbdaa13b11esa9ds8g0d98gd0h85©2013-2022 Tencent Cloud. All rights reserved.

Page 1545 of 1869

Cloud Infinite[Tag] => FileHashCode[State] => Success[CreationTime] => 2023-01-31T15:49:33+0800[StartTime] => 2023-01-31T15:49:33+0800[EndTime] => 2023-01-31T15:49:34+0800[QueueId] => pcc3ae89sa9d807fs89dg789sdg[Input] => Array([BucketId] => examplebucket-1250000000[Region] => ap-guangzhou[Object] => sound01.mp3)[Operation] => Array([JobLevel] => 0
[UserData] => xxx[FileHashCodeConfig] => Array([Type] => MD5[AddToHeader] => true)
[FileHashCodeResult] => Array([MD5] => 1f3ede740849eaa2e79e9b269ea3db2a[LastModified] => 2023-01-29T11:31:02+0000[Etag] => "1f3ede740849eaa2e79e9b269ea3db2a"[FileSize] => 42120)))[Key] => fcd32dbdaa13b11esa9ds8g0d98gd0h85[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-guangzhou.myqcloud.com/file_jobs/f)©2013-2022 Tencent Cloud. All rights reserved.

Page 1546 of 1869

Cloud Infinite

File Decompression：

Last updated 2024-03-01 14:43:58

Overview
This document provides an overview of APIs and SDK code samples for file decompression.
API

Description

Submitting a file
decompression job

Adopts a POST request method. You can submit a job to perform file decompression
and asynchronously return decompressed files.

Querying the file
decompression result

Queries the result of a specified file decompression job.

Submitting a File Decompression Job
Feature description
This API adopts a POST request method. You can submit a job to perform file decompression and asynchronously
return decompressed files.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1547 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model createFileUncompressJobs(array $args = arra

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1548 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; //Replace it with the actual `region`, which can be viewed$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', //Protocol, which is http by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1549 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// https://www.tencentcloud.com/document/product/436/53993: Submitting a File D$result = $cosClient->createFileUncompressJobs(array(//'Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Tag' => 'FileUncompress','QueueId' => 'pcc3ae89sa9d807fs89dg789sdg','Input' => array('Object' => 'test.zip',),'Operation' => array('UserData' => 'xxx','FileUncompressConfig' => array('Prefix' => 'prefix','PrefixReplaced' => '1',),
'Output' => array('Region' => $region,'Bucket' => 'examplebucket-1250000000', // Bucket name in the forma
),
),

//
//
//
//
//
//
//
//

'CallBackFormat' => '','CallBackType' => '','CallBack' => '','CallBackMqConfig' => array('MqRegion' => '','MqMode' => '','MqName' => '',),));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description

Type

Required

Tag

RequestJob type. It is FileUncompress for file

StringYes©2013-2022 Tencent Cloud. All rights reserved.

Page 1550 of 1869

Cloud Infinite

decompression by default.
Input

RequestInformation about the file to be operated.

Container

Yes

Operation

RequestFile decompression rule.

Container

Yes

QueueId

RequestID of the queue where the job is in.

StringYes

StringNo

StringNo

Job callback format, which can be JSON
CallBackFormat

Requestor XML (default). It takes priority over thatof the queue.
Job callback type, which can be Url

CallBackType

Request(default) or TDMQ . It takes priority overthat of the queue.

CallBack

CallBackMqConfig

RequestJob callback address. It takes priority overthat of the queue.

String

No

Request

TDMQ configuration for job callback as
described in Structure, which is required if
CallBackType is TDMQ .

Container

No

Input has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

ObjectRequest.Input

Filename, which is the full name of the file inthe bucket.

StringYes

Operation has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

FileUncompressConfig

Request.Operation

File decompression rule.

Container

Yes

UserData

Request.Operation

The user information passed
through, which is printable ASCII
codes of up to 1,024 in length.

StringNo

OutputRequest.Operation

Information about the bucket
where the decompressed file isstored.

Container

Yes©2013-2022 Tencent Cloud. All rights reserved.

Page 1551 of 1869

Cloud Infinite

FileUncompressConfig has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

Required

StringNo

StringNo

Prefix of the input filePrefix

Request.Operation.FileUncompressConfig

PrefixReplaced

Request.Operation.FileUncompressConfig

after decompression.
If this parameter isleft empty, the file isstored in the root
directory of thebucket by default.
Whether to replace
the prefix of thedirectory of thedecompressed file.
Valid values:
0 : No additional
prefix is added. The
decompressed files
are saved in the
directory specified by
Prefix (thename of thecompressed package
is not retained, andthe file in thecompressed package
is saved to thespecified directoryonly).
1 : The name of
the compressedpackage is used as
the prefix. The
decompressed files
are saved in the
directory specified by
Prefix .
2 : The full
directory of thecompressed package
is used as the prefix.
If Prefix is not
specified, the file is©2013-2022 Tencent Cloud. All rights reserved.

Page 1552 of 1869

Cloud Infinite

decompressed to thecurrent directory(including the nameof the compressedpackage) of thecompressedpackage.
Default value: 0 .

Notes:
If the compressed package is named test.zip , contains the image.jpg file, and is stored in the 123
directory in bucket A, the full directory of the compressed package is 123/test.zip .
Decompress the package to bucket A with Prefix set to 456 . The storage directory of the decompressed filevaries depending on the value of PrefixReplaced :0 : The image.jpg file is stored in the 456 directory and its full directory is 456/image.jpg .
1 : The image.jpg file is stored in the 456 directory with prefix test and its full directory is456/test/image.jpg .
2 : The image.jpg file is stored in the 456 directory with prefix 123/test and its full directory is456/123/test/image.jpg .
Output has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

RequiredRegionRequest.Operation.Output

Bucket region.

StringYes

BucketRequest.Operation.Output

Bucket where the decompressed
files are stored.

StringYes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1553 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([RequestId] => NjNkOGM2NmVfZTYxNmY5MSAASJPOJCIANSIDNAI=[ContentType] => application/xml[ContentLength] => 872[JobsDetail] => Array([Progress] => 0
[Code] => Success[Message] =>[JobId] => fcd32dbdaa13b11esa9ds8g0d98gd0h85©2013-2022 Tencent Cloud. All rights reserved.

Page 1554 of 1869

Cloud Infinite[Tag] => FileUncompress[State] => Submitted[CreationTime] => 2023-01-31T16:05:31+0800[StartTime] => [EndTime] => [QueueId] => pcc3ae89sa9d807fs89dg789sdg[Input] => Array([BucketId] => examplebucket-1250000000[Region] => ap-guangzhou[Object] => test.zip)[Operation] => Array([JobLevel] => 0
[UserData] => xxx[Output] => Array([Region] => ap-guangzhou[Bucket] => examplebucket-1250000000)[FileUncompressConfig] => Array([Prefix] => prefix[PrefixReplaced] => 1)))
[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-guangzhou.myqcloud.com/file_jobs)

Querying File Decompression Result
Feature description
This API is used to query the result of a specified file decompression job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1555 of 1869

Cloud Infinite

public Guzzle\\Service\\Resource\\Model getFileUncompressResult(array $args = array

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1556 of 1869

Cloud Infinite<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';$secretId = "SECRETID"; //Replace it with the actual `SecretId`, which can be viewe$secretKey = "SECRETKEY"; //Replace it with the actual `SecretKey`, which can be vi$region = "ap-beijing"; //Replace it with the actual `region`, which can be viewed$cosClient = new Qcloud\\Cos\\Client(array('region' => $region,'schema' => 'https', // Protocol, which is `http` by default©2013-2022 Tencent Cloud. All rights reserved.

Page 1557 of 1869

Cloud Infinite'credentials'=> array('secretId' => $secretId ,'secretKey' => $secretKey)));try {// https://www.tencentcloud.com/document/product/436/53994: Querying File Decom$result = $cosClient->getFileUncompressResult(array('Bucket' => 'examplebucket-1250000000', // Bucket name in the format of `Bu'Key' => '', // jobId));// Request succeeded
print_r($result);} catch (\\Exception $e) {// Request failedecho($e);}

Parameter description
Request has the following sub-nodes:
Parameter

Type

Description

Required

BucketStringBucket name in the format of BucketName-APPID .

Yes

Key

StringjobId

Yes

Sample response©2013-2022 Tencent Cloud. All rights reserved.

Page 1558 of 1869

Cloud Infinite

GuzzleHttp\\Command\\Result Object([RequestId] => NjNkOGM2NmVfZTYxNmY5MSAASJPOJCIANSIDNAI=[ContentType] => application/xml[ContentLength] => 1092
[JobsDetail] => Array([Progress] => 100[Code] => Success[Message] => success[JobId] => fcd32dbdaa13b11esa9ds8g0d98gd0h85©2013-2022 Tencent Cloud. All rights reserved.

Page 1559 of 1869

Cloud Infinite[Tag] => FileUncompress[State] => Success[CreationTime] => 2023-01-31T16:05:31+0800[StartTime] => 2023-01-31T16:05:31+0800[EndTime] => 2023-01-31T16:05:31+0800[QueueId] => pcc3ae89sa9d807fs89dg789sdg[Input] => Array([BucketId] => examplebucket-1250000000[Region] => ap-guangzhou[Object] => test.zip)[Operation] => Array([JobLevel] => 0
[UserData] => xxx[Output] => Array([Region] => ap-guangzhou[Bucket] => examplebucket-1250000000)[FileUncompressConfig] => Array([Prefix] => prefix[PrefixReplaced] => 1)
[FileUncompressResult] => Array([Region] => ap-guangzhou[Bucket] => examplebucket-1250000000[FileCount] => 6)))
[Key] => fcd32dbdaa13b11esa9ds8g0d98gd0h85[Bucket] => examplebucket-1250000000[Location] => examplebucket-1250000000.ci.ap-guangzhou.myqcloud.com/file_jobs/f)©2013-2022 Tencent Cloud. All rights reserved.

Page 1560 of 1869

Cloud Infinite

Python SDK
Getting Started：

Last updated 2024-03-01 14:57:12

Download and Installation
Relevant resources
Download the source code of COS's XML Python SDK.
Download the XML Python SDK.
Download the XML Python Demo.
For the complete sample code, see SDK Sample Code.
For the SDK changelog, see Changelog.
For SDK FAQs, see Python SDK FAQs.
Note
If you encounter errors such as non-existent functions or methods when using the XML version of the SDK, please
update the SDK to the latest version and try again.
Environmental dependencies
Currently, COS’s XML Python SDK supports Python 2.7, Python 3.4, and later.
Note
For the definitions of parameters such as SecretId, SecretKey, Bucket, and Region, see COS’s Glossary.
Installing SDK
You can install the SDK in three ways: installation via pip, manual installation, and offline installation.
Installing via pip (recommended)©2013-2022 Tencent Cloud. All rights reserved.

Page 1561 of 1869

Cloud Infinite

pip install -U cos-python-sdk-v5
Manual installation
Download the source code here and install the SDK manually via setup by running the following command:©2013-2022 Tencent Cloud. All rights reserved.

Page 1562 of 1869

Cloud Infinite

python setup.py install
Offline installation©2013-2022 Tencent Cloud. All rights reserved.

Page 1563 of 1869

Cloud Infinite# Run the following commands on a device that is connected to the Internet
mkdir cos-python-sdk-packages
pip download cos-python-sdk-v5 -d cos-python-sdk-packages
tar -czvf cos-python-sdk-packages.tar.gz cos-python-sdk-packages# Copy the installation package to a device that is not connected to the Internet a# Please make sure that the version of Python on the two computers is the same; othtar -xzvf cos-python-sdk-packages.tar.gz
pip install cos-python-sdk-v5 --no-index -f cos-python-sdk-packages©2013-2022 Tencent Cloud. All rights reserved.

Page 1564 of 1869

Cloud Infinite

Directions
The section below describes how to use the COS SDK for Python to perform basic operations, such as initializing aclient, creating a bucket, querying the bucket list, uploading an object, querying the object list, downloading an object,and deleting an object.

Initialization
Notes
We recommend you use a temporary key as instructed in Generating and Using Temporary Keys to call the SDK for
security purposes. When you apply for a temporary key, follow the Notes on Principle of Least Privilege to avoid
leaking resources besides your buckets and objects.
If you must use a permanent key, we recommend you follow the Notes on Principle of Least Privilege to limit the scopeof permission on the permanent key.
You can initialize the Python SDK Client in the following ways as needed:
Initializing with the COS default domain (default)
If you use the COS default domain to access COS, the SDK will access COS using a domain name formatted as{bucket-appid}.cos.{region}.myqcloud.com.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1565 of 1869

Cloud Infinite# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging# In most cases, set the log level to INFO. If you need to debug, you can set it tologging.basicConfig(level=logging.INFO, stream=sys.stdout)# 1. Set user attributes such as secret_id, secret_key, and region. Appid has been
secret_id = 'SecretId'# Replace it with the actual SecretId, which can be view

©2013-2022 Tencent Cloud. All rights reserved.

Page 1566 of 1869

Cloud Infinite

secret_key = 'SecretKey'
region = 'ap-beijing'
token = None
scheme = 'https'# Replace it with the actual SecretKey, which can be v
# Replace it with the actual region, which can be viewed# For the list of regions supported by COS, see https://# Token is required for temporary keys but not permanent# Specify whether to use HTTP or HTTPS protocol to acces

config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=tclient = CosS3Client(config)
Notes
Usually, you only need to generate one CosS3Client instance for a region, and can upload/download objects
repeatedly. Do not generate a CosS3Client instance for every access. Otherwise, the Python process will occupy too
many connections and threads.
Note
For more information on how to generate and use a temporary key, see Generating and Using Temporary Keys.
Initializing with the COS default domain and proxyConfigure this part when you need to access COS with a proxy. Otherwise, skip this part.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1567 of 1869

Cloud Infinite# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging# In most cases, set the log level to INFO. If you need to debug, you can set it tologging.basicConfig(level=logging.INFO, stream=sys.stdout)# 1. Set user attributes such as secret_id, secret_key, and region. Appid has been
secret_id = 'SecretId'# Replace it with the actual SecretId, which can be view

©2013-2022 Tencent Cloud. All rights reserved.

Page 1568 of 1869

Cloud Infinite

secret_key = 'SecretKey'
region = 'ap-beijing'# Replace it with the actual SecretKey, which can be v
# Replace it with the actual region, which can be viewed# For the list of regions supported by COS, see https://# Token is required for temporary keys but not permanent

token = None
proxies = {'http': '127.0.0.1:80',# Replace it with your HTTP Proxy IP.

'https': '127.0.0.1:443' # Replace it with your HTTPS Proxy IP.
}
config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=tclient = CosS3Client(config)

Initializing with the COS acceleration domain
If you use the COS global acceleration domain to access COS, the SDK will access COS using a domain nameformatted as {bucket-appid}.cos.accelerate.myqcloud.com . region will not appear in the domainname.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1569 of 1869

Cloud Infinite# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging# In most cases, set the log level to INFO. If you need to debug, you can set it tologging.basicConfig(level=logging.INFO, stream=sys.stdout)# 1. Set user attributes such as secret_id, secret_key, and region. Appid has been
secret_id = 'SecretId'# Replace it with the actual SecretId, which can be view

©2013-2022 Tencent Cloud. All rights reserved.

Page 1570 of 1869

Cloud Infinite

secret_key = 'SecretKey'
region = None
token = None
scheme = 'https'# Replace it with the actual SecretKey, which can be v
# "region" does not need to be specified if you initiali# Token is required for temporary keys but not permanent# Specify whether to use HTTP or HTTPS protocol to acces

endpoint = 'cos.accelerate.myqcloud.com' # Replace it with your endpoint or the COS
config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=tclient = CosS3Client(config)

Initializing with a custom domain
If you use a custom domain to access COS, the SDK will directly access COS using the user domain configured.
Neither bucket nor region will appear in the domain name.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1571 of 1869

Cloud Infinite# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging# In most cases, set the log level to INFO. If you need to debug, you can set it tologging.basicConfig(level=logging.INFO, stream=sys.stdout)# 1. Set user attributes such as secret_id, secret_key, and region. Appid has been
secret_id = 'SecretId'# Replace it with the actual SecretId, which can be view

©2013-2022 Tencent Cloud. All rights reserved.

Page 1572 of 1869

Cloud Infinite

secret_key = 'SecretKey'
region = None
token = None
scheme = 'https'# Replace it with the actual SecretKey, which can be v
# "region" does not need to be specified if you initiali# Token is required for temporary keys but not permanent# Specify whether to use HTTP or HTTPS protocol to accesdomain = 'user-define.example.com' # Your custom domain. You need to enable the cus
config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=tclient = CosS3Client(config)

Initializing with the CDN default domain
If you use the CDN default domain to access COS, the SDK will access CDN using a domain formatted as {bucketappid}.file.mycloud.com and then access COS via the CDN origin server.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1573 of 1869

Cloud Infinite# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging# In most cases, set the log level to INFO. If you need to debug, you can set it tologging.basicConfig(level=logging.INFO, stream=sys.stdout)# 1. Set user attributes such as secret_id, secret_key, and region. Appid has been
secret_id = 'SecretId'# Replace it with the actual SecretId, which can be view

©2013-2022 Tencent Cloud. All rights reserved.

Page 1574 of 1869

Cloud Infinite

secret_key = 'SecretKey'
region = None
token = None
scheme = 'https'# Replace it with the actual SecretKey, which can be v
# "region" does not need to be specified if you initiali# Token is required for temporary keys but not permanent# Specify whether to use HTTP or HTTPS protocol to acces

endpoint = 'file.mycloud.com' # Replace it with your default CDN acceleration domai
config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=tclient = CosS3Client(config)

Initializing with a CDN custom domain
If you use a CDN custom domain to access COS, the SDK will directly access CDN using the user domain
configured (neither bucket nor region will appear in the domain name) and then access COS via CDN origin
server.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1575 of 1869

Cloud Infinite# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging# In most cases, set the log level to INFO. If you need to debug, you can set it tologging.basicConfig(level=logging.INFO, stream=sys.stdout)# 1. Set user attributes such as secret_id, secret_key, and region. Appid has been
secret_id = 'SecretId'# Replace it with the actual SecretId, which can be view

©2013-2022 Tencent Cloud. All rights reserved.

Page 1576 of 1869

Cloud Infinite

secret_key = 'SecretKey'
region = None
token = None
scheme = 'https'# Replace it with the actual SecretKey, which can be v
# "region" does not need to be specified if you initiali# Token is required for temporary keys but not permanent# Specify whether to use HTTP or HTTPS protocol to accesdomain = 'user-define.example-cdn.com' # Your CDN custom domain. You need to enableconfig = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=tclient = CosS3Client(config)

Creating a bucket©2013-2022 Tencent Cloud. All rights reserved.

Page 1577 of 1869

Cloud Infinite# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging# In most cases, set the log level to INFO. If you need to debug, you can set it tologging.basicConfig(level=logging.INFO, stream=sys.stdout)# 1. Set user attributes such as secret_id, secret_key, and region. Appid has been
secret_id = 'SecretId'# Replace it with the actual SecretId, which can be view
secret_key = 'SecretKey'# Replace it with the actual SecretKey, which can be v
region = 'ap-beijing'# Replace it with the actual region, which can be viewed# For the list of regions supported by COS, see https://token = None
# Token is required for temporary keys but not permanent
scheme = 'https'# Specify whether to use HTTP or HTTPS protocol to acces
config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=tclient = CosS3Client(config)
response = client.create_bucket(
Bucket='examplebucket-1250000000')

Querying the bucket list

©2013-2022 Tencent Cloud. All rights reserved.

Page 1578 of 1869

Cloud Infinite# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging# In most cases, set the log level to INFO. If you need to debug, you can set it tologging.basicConfig(level=logging.INFO, stream=sys.stdout)# 1. Set user attributes such as secret_id, secret_key, and region. Appid has been
secret_id = 'SecretId'# Replace it with the actual SecretId, which can be view

©2013-2022 Tencent Cloud. All rights reserved.

Page 1579 of 1869

Cloud Infinite

secret_key = 'SecretKey'
region = 'ap-beijing'
token = None
scheme = 'https'# Replace it with the actual SecretKey, which can be v
# Replace it with the actual region, which can be viewed# For the list of regions supported by COS, see https://# Token is required for temporary keys but not permanent# Specify whether to use HTTP or HTTPS protocol to acces

config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=tclient = CosS3Client(config)
response = client.list_buckets()

Uploading an object
Note
Simple upload cannot be used to upload files larger than 5 GB. You can use the advanced upload API to upload large
files. For more information about the related parameters, see Object Operations.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1580 of 1869

Cloud Infinite# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging# In most cases, set the log level to INFO. If you need to debug, you can set it tologging.basicConfig(level=logging.INFO, stream=sys.stdout)# 1. Set user attributes such as secret_id, secret_key, and region. Appid has been
secret_id = 'SecretId'# Replace it with the actual SecretId, which can be view

©2013-2022 Tencent Cloud. All rights reserved.

Page 1581 of 1869

Cloud Infinite

secret_key = 'SecretKey'
region = 'ap-beijing'
token = None
scheme = 'https'# Replace it with the actual SecretKey, which can be v
# Replace it with the actual region, which can be viewed# For the list of regions supported by COS, see https://# Token is required for temporary keys but not permanent# Specify whether to use HTTP or HTTPS protocol to acces

config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=tclient = CosS3Client(config)#### Upload a file stream with simple upload (which cannot be used to upload files# It is strongly recommended to open the file in binary mode; otherwise, an error mwith open('picture.jpg', 'rb') as fp:
response = client.put_object(
Bucket='examplebucket-1250000000',
Body=fp,
Key='picture.jpg',
StorageClass='STANDARD',
EnableMD5=False)
print(response['ETag'])#### Upload a byte stream with simple upload
response = client.put_object(
Bucket='examplebucket-1250000000',
Body=b'bytes',
Key='picture.jpg',
EnableMD5=False)
print(response['ETag'])#### Simple chunk upload
import requests
stream = requests.get('https://cloud.tencent.com/document/product/436/7778')# Online streams will be transferred to COS in the Transfer-Encoding:chunked manner
response = client.put_object(
Bucket='examplebucket-1250000000',
Body=stream,
Key='picture.jpg')
print(response['ETag'])#### Advanced upload API (recommended)# This API can automatically select between simple upload and multipart upload baseresponse = client.upload_file(
Bucket='examplebucket-1250000000',©2013-2022 Tencent Cloud. All rights reserved.

Page 1582 of 1869

Cloud Infinite

LocalFilePath='local.txt',
Key='picture.jpg',
PartSize=1,
MAXThread=10,
EnableMD5=False)
print(response['ETag'])Querying objects©2013-2022 Tencent Cloud. All rights reserved.

Page 1583 of 1869

Cloud Infinite# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging# In most cases, set the log level to INFO. If you need to debug, you can set it tologging.basicConfig(level=logging.INFO, stream=sys.stdout)# 1. Set user attributes such as secret_id, secret_key, and region. Appid has been
secret_id = 'SecretId'# Replace it with the actual SecretId, which can be view
secret_key = 'SecretKey'# Replace it with the actual SecretKey, which can be v
region = 'ap-beijing'# Replace it with the actual region, which can be viewed# For the list of regions supported by COS, see https://token = None
# Token is required for temporary keys but not permanent
scheme = 'https'# Specify whether to use HTTP or HTTPS protocol to acces
config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=tclient = CosS3Client(config)
response = client.list_objects(
Bucket='examplebucket-1250000000',
Prefix='folder1')
A single call to the list_objects API can query up to 1,000 objects. If you want to query all objects, you need tocall it repeatedly.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1584 of 1869

Cloud Infinite# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging# In most cases, set the log level to INFO. If you need to debug, you can set it tologging.basicConfig(level=logging.INFO, stream=sys.stdout)# 1. Set user attributes such as secret_id, secret_key, and region. Appid has been
secret_id = 'SecretId'# Replace it with the actual SecretId, which can be view

©2013-2022 Tencent Cloud. All rights reserved.

Page 1585 of 1869

Cloud Infinite

secret_key = 'SecretKey'
region = 'ap-beijing'
token = None
scheme = 'https'# Replace it with the actual SecretKey, which can be v
# Replace it with the actual region, which can be viewed# For the list of regions supported by COS, see https://# Token is required for temporary keys but not permanent# Specify whether to use HTTP or HTTPS protocol to acces

config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=tclient = CosS3Client(config)
marker = ""while True:
response = client.list_objects(
Bucket='examplebucket-1250000000',
Prefix='folder1',
Marker=marker)
print(response['Contents'])
if response['IsTruncated'] == 'false':
breakmarker = response['NextMarker']

Downloading an object©2013-2022 Tencent Cloud. All rights reserved.

Page 1586 of 1869

Cloud Infinite# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging# In most cases, set the log level to INFO. If you need to debug, you can set it tologging.basicConfig(level=logging.INFO, stream=sys.stdout)# 1. Set user attributes such as secret_id, secret_key, and region. Appid has been
secret_id = 'SecretId'# Replace it with the actual SecretId, which can be view

©2013-2022 Tencent Cloud. All rights reserved.

Page 1587 of 1869

Cloud Infinite

secret_key = 'SecretKey'
region = 'ap-beijing'
token = None
scheme = 'https'# Replace it with the actual SecretKey, which can be v
# Replace it with the actual region, which can be viewed# For the list of regions supported by COS, see https://# Token is required for temporary keys but not permanent# Specify whether to use HTTP or HTTPS protocol to acces

config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=tclient = CosS3Client(config)#### Download an object to the local file system
response = client.get_object(
Bucket='examplebucket-1250000000',
Key='picture.jpg',)
response['Body'].get_stream_to_file('output.txt')#### Download a file stream
response = client.get_object(
Bucket='examplebucket-1250000000',
Key='picture.jpg',)
fp = response['Body'].get_raw_stream()
print(fp.read(2))#### Set the response HTTP headers
response = client.get_object(
Bucket='examplebucket-1250000000',
Key='picture.jpg',
ResponseContentType='text/html; charset=utf-8')
print(response['Content-Type'])
fp = response['Body'].get_raw_stream()
print(fp.read(2))#### Specify the download range
response = client.get_object(
Bucket='examplebucket-1250000000',
Key='picture.jpg',
Range='bytes=0-10')
fp = response['Body'].get_raw_stream()
print(fp.read())

Deleting an object©2013-2022 Tencent Cloud. All rights reserved.

Page 1588 of 1869

Cloud Infinite# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging# In most cases, set the log level to INFO. If you need to debug, you can set it tologging.basicConfig(level=logging.INFO, stream=sys.stdout)# 1. Set user attributes such as secret_id, secret_key, and region. Appid has been
secret_id = 'SecretId'# Replace it with the actual SecretId, which can be view

©2013-2022 Tencent Cloud. All rights reserved.

Page 1589 of 1869

Cloud Infinite

secret_key = 'SecretKey'
region = 'ap-beijing'
token = None
scheme = 'https'# Replace it with the actual SecretKey, which can be v
# Replace it with the actual region, which can be viewed# For the list of regions supported by COS, see https://# Token is required for temporary keys but not permanent# Specify whether to use HTTP or HTTPS protocol to acces

config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=tclient = CosS3Client(config)# Delete an object## deleteObject
response = client.delete_object(
Bucket='examplebucket-1250000000',
Key='exampleobject')# Delete multiple objects## deleteObjects
response = client.delete_objects(
Bucket='examplebucket-1250000000',
Delete={'Object': [{'Key': 'exampleobject1',},{'Key': 'exampleobject2',},],'Quiet': 'true'|'false'})©2013-2022 Tencent Cloud. All rights reserved.

Page 1590 of 1869

Cloud Infinite

Image Processing
Persistent Image Processing：

Last updated 2024-03-01 14:57:12

Overview
This document provides an overview of APIs and SDK code samples related to persistent image processing.
API

Description

Persistent
image
processing

Processes an image during upload, or processes an image stored in COS and saves theprocessing result to COS. Images within 32 MB can be processed.

Processing upon Upload
Feature description
CI allows you to process images during upload. To enable this, add Pic-Operations to the request header andset relevant parameters. You can also save the input images and processing results to COS.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1591 of 1869

Cloud Infinite

ci_put_object(self, Bucket, Body, Key, EnableMD5=False, **kwargs)

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1592 of 1869

Cloud Infinite

with open('local.jpg', 'rb') as fp:
response, data = client.ci_put_object(
Bucket='examplebucket-1250000000',
Body=fp,
Key=ci_file_name,# pic operation json struct
PicOperations='{"is_pic_info":1,"rules":[{"fileid":"format.png","rule":"imaSample request with all parameters©2013-2022 Tencent Cloud. All rights reserved.

Page 1593 of 1869

Cloud Infinite

response = client.ci_put_object(
Bucket='examplebucket-1250000000',
Body=b'bytes'|file,
Key='exampleobject',
EnableMD5=False|True,
ACL='private'|'public-read', # Please note that the maximum number (1000) of AC
GrantFullControl='string',
GrantRead='string',
StorageClass='STANDARD'|'STANDARD_IA'|'ARCHIVE',
Expires='string',
CacheControl='string',©2013-2022 Tencent Cloud. All rights reserved.

Page 1594 of 1869

Cloud Infinite

ContentType='string',
ContentDisposition='string',
ContentEncoding='string',
ContentLanguage='string',
ContentLength='123',
ContentMD5='string',
Metadata={'x-cos-meta-key1': 'value1','x-cos-meta-key2': 'value2'},
TrafficLimit='1048576'
PicOperations='{"is_pic_info":1,"rules":[{"fileid":"format.png","rule":"imageVi)Parameter description
Parameter

Description

Type

Required

BucketBucket name in the format of BucketName-APPID .

StringYes

Body

Content of the uploaded object, which can be a file stream ora byte stream.

file/bytes

Yes

StringYes

String

Yes

Bool

No

StringNo

Key

Object key, which uniquely identifies an object in a bucket.
For example, if an object's access endpoint isexamplebucket-1250000000.cos.apguangzhou.myqcloud.com/doc/pic.jpg , its key is
doc/pic.jpg .

PicOperations

CI image processing parameter. For more information, see
Persistent Image Processing.
Whether the SDK needs to calculate the Content-MD5

EnableMD5

ACLchecksum. It is disabled by default. The upload will takelonger if it is enabled.
Sets the object ACL, such as private or publicread .

GrantFullControl

Grants full permission in the format of id="OwnerUin" .

StringNo

GrantRead

Grants read permission in the format of id="OwnerUin" .

StringNo

String

No

Sets the storage class of the object, such as STANDARD
StorageClass(default), STANDARD_IA , and ARCHIVE . For more
information, see Storage Class Overview.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1595 of 1869

Cloud Infinite

Expires

Sets Expires .

StringNo

CacheControl

Cache policy. Sets Cache-Control .

StringNo

ContentType

Content type. Sets Content-Type .

StringNo

ContentDisposition

Object name. Sets Content-Disposition .

StringNo

ContentEncoding

Encoding format. Sets Content-Encoding .

StringNo

ContentLanguage

Language type. Sets Content-Language .

StringNo

ContentLength

Sets the length of the request content.

StringNo

ContentMD5

Sets the MD5 checksum of the uploaded object forverification.

String

No

Dict

No

String

No

Metadata

TrafficLimit

User-defined object metadata. It must start with x-cosmeta ; otherwise, it will be ignored.
Bandwidth limit for a single request in bit/s. Value range:
819200-838860800, i.e., 100 KB/s–100 MB/s.

PicOperations is a JSON string. Its parameters are as follows:
Parameter

Description

Type

Required

is_pic_info

Whether to return the input image information. Valid values:
0 (no), 1 (yes). Default value: 0 .

Int

No

rules

Processing rules (up to five rules are supported). Each rule
corresponds to one processing result. If this parameter is not
specified, images will not be processed.

Array

No

Parameters of rules (a JSON array) are as follows:
Parameter

Description

Type

RequiredbucketName of the destination bucket to store the results in the format
of BucketName-APPID . If this parameter is not specified,

StringNo

the results will be stored in the current bucket by default.
Path of the processing result file. If the path starts with / , thefileidresult file will be stored in the specified folder; otherwise, it will
be stored in the same directory as the input image file.

StringYes

rule

Processing parameters. For more information, see CI's image

StringYes©2013-2022 Tencent Cloud. All rights reserved.

Page 1596 of 1869

Cloud Infinite

processing API. To process an image by using a specified style,the value must start with style/ , with the style namefollowed. For example, if the style name is test , the value ofrule should be style/test .

Response description
The response contains the original image and processing information in dict format:{'OriginalInfo': {©2013-2022 Tencent Cloud. All rights reserved.

Page 1597 of 1869

Cloud Infinite'Key': 'local.jpg','Location': 'examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/local.j'ETag': '"aff1b996bcc63a0f0259df0de2fa989f38c5ce7e"','ImageInfo': {'Format': 'JPEG','Width': '300','Height': '168','Quality': '74','Ave': '0x1a3451','Orientation': '0''FrameCount': '1'}},'ProcessResults': {'Object': {'Key': 'format.png','Location': 'examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/for'Format': 'png','Width': '300','Height': '168','Size': '77063','Quality': '74','ETag': '"a07dc5bcfa238e7d23d2d5884da4ac328aaaa9c6"''FrameCount': '1'}}}
Parameters in the response body are as follows:
Parameter

Type

Description

UploadResult

Container

Input image information

Content of UploadResult :Parameter

Type

Description

OriginalInfo

Container

Input image information

ProcessResults

Container

Image processing result

Content of OriginalInfo :Node NameType

Description

Key

StringInput image name©2013-2022 Tencent Cloud. All rights reserved.

Page 1598 of 1869

Cloud Infinite

Location

StringImage path

ImageInfo

Container

Input image information

ETag

StringETag of the input image. If the output image overwrites the
input image, the value of ETag will be that of the output image.

Content of ImageInfo :Node NameType

Description

FormatStringFormatWidth

Int

Image width

HeightInt

Image height

QualityInt

Image quality

Ave

StringImage average hue

Orientation

Int

Image rotation angle

FrameCountInt

Number of frames of the image, which is 1 for static images bydefault.

Content of ProcessResults :Node NameType

Description

ObjectContainer

Processing result of each image

Content of Object :Node NameType

Description

Key

StringFile nameLocation

StringImage path

FormatStringImage format

Width

Int

Image width

HeightInt

Image height

Size

Int

Image size

©2013-2022 Tencent Cloud. All rights reserved.

Page 1599 of 1869

Cloud Infinite

QualityInt

Image quality

ETag

StringETag of the processing result image

FrameCountInt

Number of frames of the image, which is 1 for static images bydefault.

Processing In-Cloud Data
Feature description
The persistent image processing API can process an in-cloud image and save the processing result to COS.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1600 of 1869

Cloud Infinite

ci_image_process(self, Bucket, Key, **kwargs)

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1601 of 1869

Cloud Infinite

response, data = client.ci_image_process(Bucket='examplebucket-1250000000',
Key=ci_file_name,# pic operation json struct
PicOperations='{"is_pic_info":1,"rules":[{"fileid":"format.png","rule":"imageVi

Sample request with all parameters©2013-2022 Tencent Cloud. All rights reserved.

Page 1602 of 1869

Cloud Infinite

response, data = client.ci_image_process(Bucket='examplebucket-1250000000',
Key=ci_file_name,# pic operation json struct
PicOperations='{"is_pic_info":1,"rules":[{"fileid":"format.png","rule":"imageViParameter description
Parameter

Description©2013-2022 Tencent Cloud. All rights reserved.

Type

RequiredPage 1603 of 1869

Cloud Infinite

BucketBucket name in the format of BucketName-APPID .

StringYes

StringYes

StringYes

Type

Required

Int

No

Array

No

Object key, which uniquely identifies an object in a bucket. For
example, if an object's access endpoint is examplebucketKey

1250000000.cos.apguangzhou.myqcloud.com/doc/pic.jpg , its key is
doc/pic.jpg .

PicOperations

CI image processing parameters. For more information, see
Persistent Image Processing.

PicOperations is a JSON string. Its parameters are as follows:
Parameter
is_pic_info

rules

Description
Whether to return the input image information. Valid values: 0(no), 1 (yes). Default value: 0 .
Processing rules (up to five rules are supported). Each rule
corresponds to one processing result. If this parameter is not
specified, images will not be processed.

Parameters of rules (a JSON array) are as follows:
Parameter

Description

Type

RequiredbucketName of the destination bucket to store the results in the format of
BucketName-APPID . If this parameter is not specified, theStringNo

StringYes

StringYes

results will be stored in the current bucket by default.
Path of the processing result file. If the path starts with / , thefileidrule

result file will be stored in the specified folder; otherwise, it will be
stored in the same directory as the input image file.
Processing parameters. For more information, see the image
processing API. To process an image by using a specified style, thevalue must start with style/ with the style name followed. For
example, if the style name is test , the value of rule should
be style/test .

Response description
The response contains object metadata in dict format:©2013-2022 Tencent Cloud. All rights reserved.

Page 1604 of 1869

Cloud Infinite{'OriginalInfo': {'Key': 'local.jpg','Location': 'examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/local.j'ETag': '"aff1b996bcc63a0f0259df0de2fa989f38c5ce7e"','ImageInfo': {'Format': 'JPEG','Width': '300','Height': '168','Quality': '74','Ave': '0x1a3451',©2013-2022 Tencent Cloud. All rights reserved.

Page 1605 of 1869

Cloud Infinite'Orientation': '0''FrameCount': '1'}},'ProcessResults': {'Object': {'Key': 'format.png','Location': 'examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/for'Format': 'png','Width': '300','Height': '168','Size': '77063','Quality': '74','ETag': '"a07dc5bcfa238e7d23d2d5884da4ac328aaaa9c6"''FrameCount': '1'}}}
Parameters in the response body are as follows:
Parameter

Type

Description

UploadResult

Container

Input image information

Content of UploadResult :Parameter

Type

Description

OriginalInfo

Container

Input image information

ProcessResults

Container

Image processing result

Content of OriginalInfo :Node NameType

Description

Key

StringInput image nameLocation

StringImage path

ImageInfo

Container

Input image information

ETag

StringETag of the input image. If the output image overwrites the input image,the value of ETag will be that of the output image.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1606 of 1869

Cloud Infinite

Content of ImageInfo :Node NameType

Description

FormatStringFormatWidth

Int

Image width

HeightInt

Image height

QualityInt

Image quality

Ave

StringImage average hue

Orientation

Int

Image rotation angle

FrameCountInt

Number of frames of the image, which is 1 for static images by default.

Content of ProcessResults :Node NameType

Description

ObjectContainer

Processing result of each image

Content of Object :Node NameType

Description

Key

StringFile nameLocation

StringImage path

FormatStringImage format

Width

Int

Image width

HeightInt

Image height

Size

Int

Image size

QualityInt

Image quality

ETag

StringETag of the processing result image

FrameCountInt

Number of frames of the image, which is 1 for static images by default.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1607 of 1869

Cloud Infinite

Image Advanced Compression：

Last updated 2024-03-01 14:57:12

Overview
This document provides an overview of APIs and SDK code samples for image advanced compression.
API

Description

Image advanced compression

Compresses an image in a specified bucket.

Image Advanced Compression
Feature description
CI uses the imageMogr2 API to provide the image advanced compression feature.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1608 of 1869

Cloud Infinite

ci_download_compress_image(self, Bucket, Key, DestImagePath, CompressType, **kwargs

Sample request[//]: #".cssg-snippet-ci-download-compress-image"©2013-2022 Tencent Cloud. All rights reserved.

Page 1609 of 1869

Cloud Infinite# TPG compression
response = client.ci_download_compress_image(Bucket='examplebucket-1250000000',
Key='sample.png',
DestImagePath='sample.tpg',
CompressType='tpg')# HEIF compression
response = client.ci_download_compress_image(Bucket='examplebucket-1250000000',©2013-2022 Tencent Cloud. All rights reserved.

Page 1610 of 1869

Cloud Infinite

Key='sample.png',
DestImagePath='sample.heif',
CompressType='heif')

Parameter description
Parameter

Type

Required

StringYes

Key

Object key. It can contain up to 128 bytes of letters, digits, spaces,
plus signs, minus signs, underscores, equal signs, dots, colons, andslashes.

StringYes

DestImagePath

Local path to save the compressed image

StringYes

CompressType

Compression format, which can be TPG or HEIF.

StringYes

BucketDescription
Bucket name in the format of BucketName-APPID . For more
information, see Bucket Overview.

Response description
This API returns the response header.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1611 of 1869

Cloud Infinite

Blind Watermark：

Last updated 2024-03-01 14:57:12

Overview
This document provides an overview of APIs and SDK code samples for blind watermarking.
API

Description

Blindwatermarking

Adds blind watermark to or extracts blind watermark from local image and uploads it tobucketBlind Watermark
Feature description
Blind watermark is a new type of watermark based on CI.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1612 of 1869

Cloud Infinite

def ci_put_object_from_local_file(self, Bucket, LocalFilePath, Key, EnableMD5=False

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1613 of 1869

Cloud Infinite# Add a blind watermark
watermark_url = 'http://{bucket}.cos.{region}.myqcloud.com/watermark.png'.format(buwatermark_url_base64 = bytes.decode(base64.b64encode(str.encode(watermark_url)))
print(watermark_url_base64)
response, data = client.ci_put_object_from_local_file(
Bucket='examplebucket-1250000000',
LocalFilePath='sample.png',
Key="sample.png",# pic operation json struct
PicOperations='{"is_pic_info":1,"rules":[{"fileid": "format.png","rule": "water
watermark_url_base64 + '" }]}'

©2013-2022 Tencent Cloud. All rights reserved.

Page 1614 of 1869

Cloud Infinite)# Extract a blind watermark
sample_url = 'http://{bucket}.cos.{region}.myqcloud.com/sample.png'.format(bucket='sample_url_base64 = bytes.decode(base64.b64encode(str.encode(sample_url)))
response, data = client.ci_put_object_from_local_file(
Bucket='examplebucket-1250000000',
LocalFilePath='format.png',
Key="format.png",# pic operation json struct
PicOperations='{"is_pic_info":1,"rules":[{"fileid": "watermark.png","rule": "wasample_url_base64 + '" }]}')

Parameter description
Parameter
BucketDescription
Bucket name in the format of BucketName-APPID . For more
information, see Bucket Overview.

Type

Required

StringYes

LocalFilePath

Path of the local image to be processed

StringYes

Key

Object key. It can contain up to 128 bytes of letters, digits, spaces,
plus signs, minus signs, underscores, equal signs, dots, colons, andslashes.

StringYes

EnableMD5

Enables MD5 check for uploaded objects

Bool

No

Response description
This API returns the response header and body.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1615 of 1869

Cloud Infinite

Media Processing
Media Information APIs：

Last updated 2024-03-01 14:57:12

Overview
This document provides an overview of APIs and SDK code samples for media information.
Note:
The COS Python SDK version must be at least v5.1.9.11.
API

Operation

Description

GetMediaInfo

Querying file information

Queries media file information

Note:
Before using this API, make sure that the media processing feature has been enabled in the data processing sectionin the console; otherwise, the error media bucket unbinded, bucket's host is unavailable will bereported. For more information, see Enabling Media Processing.

Querying File Information
Feature description
This API is used to query the information of a media file.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1616 of 1869

Cloud Infinite

def get_media_info(Bucket, Key, **kwargs)

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1617 of 1869

Cloud Infinite

response = client.get_media_info(
Bucket=bucket_name,
Key='demo.mp4')
print(response)

Parameter description
Parameter

Description©2013-2022 Tencent Cloud. All rights reserved.

Required

Type

Page 1618 of 1869

Cloud Infinite

BucketBucket name in the format of BucketName-APPID . For more

Yes

StringYes

Stringinformation, see Bucket Overview.
Key

Object key, which is the unique identifier of the object in the bucket.

Response description{'MediaInfo': [{'Format': {'Bitrate': '16869.432000',©2013-2022 Tencent Cloud. All rights reserved.

Page 1619 of 1869

Cloud Infinite'Duration': '129.200000','FormatLongName': 'QuickTime / MOV','FormatName': 'mov,mp4,m4a,3gp,3g2,mj2','NumProgram': '0',
'NumStream': '2','Size': '272441346','StartTime': '0.000000'},'Stream': {'Audio': {'Bitrate': '125.712000','Channel': '2',
'ChannelLayout': 'stereo','CodecLongName': 'AAC (Advanced Audio Coding)','CodecName': 'aac','CodecTag': '0x6134706d','CodecTagString': 'mp4a','CodecTimeBase': '1/44100','Duration': '129.160998','Index': '0','Language': 'und','SampleFmt': 'fltp','SampleRate': '44100','StartTime': '0.000000','Timebase': '1/44100'},'Subtitle': None,'Video': {'AvgFps': '30/1','Bitrate': '16738.543000','CodecLongName': 'H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10',
'CodecName': 'h264','CodecTag': '0x31637661','CodecTagString': 'avc1','CodecTimeBase': '1/600','Duration': '129.200000','Fps': '30.500000','HasBFrame': '1',
'Height': '1920','Index': '1',
'Language': 'und','Level': '40','NumFrames': '3876','PixFormat': 'yuvj420p','Profile': 'High','RefFrames': '1',
'Rotation': '0.000000',©2013-2022 Tencent Cloud. All rights reserved.

Page 1620 of 1869

Cloud Infinite'StartTime': '0.000000','Timebase': '1/600','Width': '1080'
}
}
}]
}

The nodes are as described below:
MediaInfo has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

StreamMediaInfo

Stream information.

dictFormatMediaInfo

Format information.

dictStream has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Video

MediaInfo.Stream

Video information.

dict

Audio

MediaInfo.Stream

Audio information.

dictSubtitle

MediaInfo.Stream

Subtitles information.

dictFormat has the following sub-nodes (certain nodes may not be returned during video information query):
Node Name(Keyword)

Parent NodeDescription

Type

NumStreamMediaInfo.Format

Number of streams (including videos, audios, andsubtitles).

StringNumProgram

MediaInfo.Format

Number of programs.

StringFormatName

MediaInfo.Format

Container format name.

StringFormatLongName

MediaInfo.Format

Detailed name of the container format.

StringStartTimeMediaInfo.Format

Start time in seconds.

StringDuration

MediaInfo.Format

Duration in seconds.

StringBitrateMediaInfo.Format

Bitrate in Kbps.

String©2013-2022 Tencent Cloud. All rights reserved.

Page 1621 of 1869

Cloud Infinite

SizeMediaInfo.Format

Size in bytes.

StringVideo has the following sub-nodes (certain nodes may not be returned during video information query):
Node Name (Keyword)

Parent NodeDescription

Type

Index

MediaInfo.Stream.Video

Stream number.

StringCodecNameMediaInfo.Stream.Video

Codec format name.

StringCodecLongName

MediaInfo.Stream.Video

Detailed name of the codec format.

StringCodecTimeBase

MediaInfo.Stream.Video

Codec timebase.

StringCodecTagString

MediaInfo.Stream.Video

Codec tag name.

StringCodecTagMediaInfo.Stream.Video

Codec tag.

String

ProfileMediaInfo.Stream.Video

Video codec profile.

StringHeightMediaInfo.Stream.Video

Video height in px.

StringWidthMediaInfo.Stream.Video

Video width in px.

StringHasBFrame

MediaInfo.Stream.Video

Whether B-frames exist. 1: yes; 0: no.

String

RefFrames

MediaInfo.Stream.Video

Number of reference frames for video codec.

StringSar

MediaInfo.Stream.Video

Sample aspect ratio.

StringDar

MediaInfo.Stream.Video

Display aspect ratio.

StringPixFormat

MediaInfo.Stream.Video

Pixel format.

StringFieldOrderMediaInfo.Stream.Video

Field order.

StringLevel

MediaInfo.Stream.Video

Video codec level.

String

Fps

MediaInfo.Stream.Video

Video frame rate.

String

AvgFpsMediaInfo.Stream.Video

Average frame rate.

StringTimebase

MediaInfo.Stream.Video

Timebase.

StringStartTimeMediaInfo.Stream.Video

Video start time in seconds.

StringDuration

MediaInfo.Stream.Video

Video duration in seconds.

StringBitrateMediaInfo.Stream.Video

Bitrate in Kbps.

String©2013-2022 Tencent Cloud. All rights reserved.

Page 1622 of 1869

Cloud Infinite

NumFrames

MediaInfo.Stream.Video

Total number of frames.

StringLanguageMediaInfo.Stream.Video

Language.

StringAudio has the following sub-nodes (certain nodes may not be returned during video information query):
Node Name (Keyword)

Parent NodeDescription

Type

Index

MediaInfo.Stream.Audio

Stream number.

StringCodecNameMediaInfo.Stream.Audio

Codec format name.

StringCodecLongName

MediaInfo.Stream.Audio

Detailed name of the codec format.

StringCodecTimeBase

MediaInfo.Stream.Audio

Codec timebase.

StringCodecTagString

MediaInfo.Stream.Audio

Codec tag name.

StringCodecTagMediaInfo.Stream.Audio

Codec tag.

StringSampleFmt

MediaInfo.Stream.Audio

Sample format.

StringSampleRate

MediaInfo.Stream.Audio

Sample rate.

StringChannelMediaInfo.Stream.Audio

Number of channels.

StringChannelLayout

MediaInfo.Stream.Audio

Channel layout.

StringTimebase

MediaInfo.Stream.Audio

Timebase.

StringStartTimeMediaInfo.Stream.Audio

Audio start time in seconds.

StringDuration

MediaInfo.Stream.Audio

Audio duration in seconds.

StringBitrateMediaInfo.Stream.Audio

Bitrate in Kbps.

StringLanguageMediaInfo.Stream.Audio

Language.

String

Subtitle has the following sub-nodes:
Node Name (Keyword)

Parent NodeDescription

Type

Index

MediaInfo.Stream.Subtitle

Stream number.

StringLanguageMediaInfo.Stream.Subtitle

Language. und indicates no query result.

String©2013-2022 Tencent Cloud. All rights reserved.

Page 1623 of 1869

Cloud Infinite

Media Screenshot APIs：

Last updated 2024-03-01 14:57:12

Overview
This document provides an overview of APIs and SDK code samples for media screenshot.
Note:
The COS Python SDK version must be at least v5.1.9.11.
API

Operation

Description

GetSnapshot

Querying screenshot

Query the screenshot of media file at some time point

Note:
Before using this API, make sure that the media processing feature has been enabled in the data processing sectionin the console; otherwise, the error media bucket unbinded, bucket's host is unavailable will bereported. For more information, see Enabling Media Processing.

Querying Screenshot
Feature description
This API is used to query the screenshot of a media file at some time point.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1624 of 1869

Cloud Infinite

def get_snapshot(Bucket, Key, Time, Width=None, Height=None, Format='jpg', Rotate='

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1625 of 1869

Cloud Infinite

response = client.get_snapshot(
Bucket='examplebucket-1250000000',
Key='demo.mp4',
Time='1.5',
Width='480',
Format='png')
print(response)
response['Body'].get_stream_to_file('snapshot.jpg')©2013-2022 Tencent Cloud. All rights reserved.

Page 1626 of 1869

Cloud Infinite

Parameter description
Parameter
BucketDescription
Bucket name in the format of BucketName-APPID . For more
information, see Bucket Overview.

Required

Type

Yes

StringKey

Object key, which is the unique identifier of the object in the bucket.

Yes

StringTime

Screenshot time point in seconds, which can contain a decimal point.

Yes

StringWidthScreenshot width. Default value: 0.

NoStringNo

StringScreenshot height. Default value: 0. If width and height are
Heightboth 0 , the width and height of the video are used. If one of them is
0 , the other value is used to automatically adapt to the aspect ratioof the video.

FormatScreenshot format. Valid values: jpg, png. Default value: jpg.

No

StringRotateImage rotation method. auto: Rotate automatically according to thevideo rotation information. off: Do not rotate. Default value: auto.

No

StringMode

Frame capturing method. keyframe: Capture the last keyframe before
the specified time point. exactframe: Capture the frame at a specified
time point. Default value: exactframe.

No

String©2013-2022 Tencent Cloud. All rights reserved.

Page 1627 of 1869

Cloud Infinite

Content Moderation
Image Moderation：

Last updated 2024-03-01 14:57:12

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for image moderation.
API

Description

Singleimage
moderation

The existing data scan feature of image moderation leverages CI's persistent processing API toscan existing data stored in COS for pornographic, illegal, and advertising images. Content
moderation requests are `GET` requests.

Batch
image
moderation

The batch image moderation API adopts a sync POST request method. You can use this API to
perform content moderation on multiple image files.

Single Image Moderation
Feature description
This API is used to moderate images in COS, including pornographic, illegal, and advertising images.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1628 of 1869

Cloud Infinite"""Test the CI's API for moderating content in a single image"""from qcloud_cos import CosConfig
from qcloud_cos import CosS3Clientfrom qcloud_cos.cos_comm import CiDetectType# Create a COS client
response = client.get_object_sensitive_content_recognition(
Bucket=test_bucket,
Key=test_object,
DetectUrl='https://examplebucket-1250000000.cos.ap-chongqing.myqcloud.com/t
DetectType=(CiDetectType.PORN | CiDetectType.ADS))©2013-2022 Tencent Cloud. All rights reserved.

Page 1629 of 1869

Cloud Infinite

print(response)

Parameter description
The get_object_sensitive_content_recognition function is called. Specific request parameters are as
follows:
Parameter

Description

Type

RequiredKey

Object name, such as picture.jpg .

StringYes

String

No

enum

No

Int

No

Int

No

String

No

Unique identifier of the moderation policy. You can configure
the scenes you want to moderate on the moderation policy

BizType

page in the console, such as pornographic, adverting, andillegal information. For configuration guidelines, see Setting
Public Moderation Policy. You can get BizType in the
console. If BizType is specified, the moderation request
will perform moderation based on the scenes configured in
the moderation policy. If BizType is not specified, thedefault moderation policy will be used automatically.
Moderation type. Valid values: CiDetectType.PORN(pornography), CiDetectType.ADS (advertising). You

DetectTypecan select multiple types. For example,
CiDetectType.PORN | CiDetectType.ADS
indicates to moderate the image for pornographic andadvertising information. If you need more moderation scenes,
use the BizType parameter.

Interval

Frame capturing frequency, which takes effect for GIF/long
images only. The default value is 0 , indicating to detect
only the first frame of the GIF/long image.

MaxFrames

The maximum number of frames to be captured, which takes
effect for GIF/long images only. The default value is 1 ,indicating to capture only the first frame of the GIF image formoderation, or that the long image will not be split.
You can enter a detect-url value to moderate an image
accessible over the public network. If detect-url is not
specified, the backend will moderate by ObjectKey by

DetectUrl

default. If detect-url is specified, the backend will
moderate by detect-url , and there is no need to enter
ObjectKey . Sample detect-url :http://www.example.com/abc.jpg©2013-2022 Tencent Cloud. All rights reserved.

Page 1630 of 1869

Cloud Infinite

LargeImageDetect

Whether to compress the image that exceeds the size limit
before moderation. Valid values: 0 (no), 1 (yes). Default

Int

No

StringNovalue: 0 . Note: Images up to 32 MB in size can becompressed, and compression fees will be charged.
dataidImage ID. This field will return the original content in the
result, which can contain up to 512 bytes.

Response parameters
Calling the get_object_sensitive_content_recognition function will convert the XML returned in the
API into a dict value. For specific response parameters, see Single Image Moderation.

Batch Image Moderation
Feature description
This API is used to moderate multiple images in COS, including pornographic, illegal, and advertising images.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1631 of 1869

Cloud Infinite"""Test the CI's API for batch moderating content in images"""from qcloud_cos import CosConfig
from qcloud_cos import CosS3Clientfrom qcloud_cos.cos_comm import CiDetectType# Create a COS client
response = client.ci_auditing_image_batch(
Bucket=bucket_name,
DetectType=CiDetectType.PORN,
Input=[{'Url':'https://examplebucket-1250000000.cos.ap-chongqing.myqcloud.com/p'DataId': 'testdataid-111111',©2013-2022 Tencent Cloud. All rights reserved.

Page 1632 of 1869

Cloud Infinite'UserInfo':{'TokenId': 'token','Nickname': 'test','DeviceId': 'DeviceId-test','AppId': 'AppId-test','Room': 'Room-test','IP': 'IP-test','Type': 'Type-test',},},{'Object':'test-0.jpg','LargeImageDetect' :1,},{'Url':'https://examplebucket-1250000000.cos.ap-chongqing.myqcloud.com/p}])
print(response)

Parameter description
The ci_auditing_image_batch function is called. Specific request parameters are as follows:
Parameter

Description

Type

Required

BucketBucket name.

StringYes

BizType

Unique identifier of the moderation policy. It is automatically generated
by the backend and corresponds to the Biztype value in theString

No

enum

No

Array

No

console.
Moderation type. Valid values: CiDetectType.PORN(pornography), CiDetectType.ADS (advertising). You can selectDetectType

multiple types. For example, CiDetectType.PORN |CiDetectType.ADS indicates to moderate the image forpornographic and advertising information. If you need more moderation
scenes, use the BizType parameter.

Input

Information of the image to be moderated. Each array element is of thedict type. The following parameters are supported:
Object: Name of the image file stored in the COS bucket. For
example, if the file is image.jpg in the test directory, the filename is test/image.jpg . Either Object or Url can beselected at a time.
Url : URL of the image file, for example, http://a1250000.cos.ap-shanghai.tencentcos.cn/image.jpg .
Either Object or Url can be selected at a time.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1633 of 1869

Cloud Infinite

Interval : Frame capturing frequency, which takes effect for GIF
images only. The default value is 5 , indicating to capture a frame
every five frames starting from the first frame (included).
MaxFrames : The maximum number of frames to be captured,
which takes effect for GIF images only. The default value is 5 ,indicating to capture only five frames of the GIF image for moderation.
The parameter value must be greater than 0.
DataId : Image identifier. This field will return the original content in
the result, which can contain up to 512 bytes.
LargeImageDetect : Whether to compress the image thatexceeds the size limit before moderation. Valid values: 0 (no), 1(yes). Default value: 0 . Note: Images up to 32 MB in size can becompressed, and compression fees will be charged.
UserInfo : Business field.

Response parameters
Calling the ci_auditing_image_batch function will convert the XML returned in the API into a dict value.
For specific response parameters, see Batch Image Moderation.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1634 of 1869

Cloud Infinite

Video Moderation：

Last updated 2024-03-01 14:57:12

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for video moderation.
Note:
COS Python SDK v5.1.9.10 or later is required. Earlier versions may contain bugs and need to be upgraded to thelatest version when being used.
API

Description

Submitting video moderation job

Submits a video moderation job.

Querying video moderation job result

Queries the result of a specified video moderation job.

Submitting a Video Moderation Job
Feature description
This API is used to submit a video moderation job. The video moderation feature is async. You can submit a job tomoderate your video files, and then use the API for querying video moderation job result to query the moderation
results.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1635 of 1869

Cloud Infinite"""Test the CI's API for moderating video file content"""# Create a COS client# Recognize a video in COS
response = client.ci_auditing_video_submit(
Bucket='bucket',
DetectType=CiDetectType.PORN | CiDetectType.ADS,
Key='test.mp4')
print response©2013-2022 Tencent Cloud. All rights reserved.

Page 1636 of 1869

Cloud Infinite

Parameter description
The ci_auditing_video_submit function is called. Specific request parameters are as follows:
Parameter

Description

Type

Required

BucketBucket name.

StringYes

Key

Object name, such as picture.jpg .

StringYes

BizType

Unique identifier of the moderation policy. You can configure
the scenes you want to moderate on the moderation policy
page in the console, such as pornographic, adverting, andillegal information. For configuration guidelines, see Setting
Public Moderation Policy. You can get BizType in theString

No

enum

No

StringNo

StringNo

StringNo

StringNo

console. If BizType is specified, the moderation request
will perform moderation based on the scenes configured in themoderation policy. If BizType is not specified, the default
moderation policy will be used automatically.
Moderation type. Valid values: CiDetectType.PORN(pornography), CiDetectType.ADS (advertising). You
DetectTypecan select multiple types. For example,
CiDetectType.PORN | CiDetectType.ADS indicatesto moderate the video for pornographic and advertisinginformation. If you need more moderation scenes, use the
BizType parameter.

Url

Callback

A video URL that is not in COS can be directly used formoderation.
Callback address, which must start with http:// or
https:// .
Structure of the callback content. Valid values: Simple (theCallbackVersionModecallback content contains basic information), Detail (thecallback content contains detailed information). Default value:
Simple .
Frame capturing mode. Valid values: Interval (intervalmode), Average (average mode), Fps (fixed frame ratemode).
Interval mode: The TimeInterval and Countparameters take effect. If Count is set but
TimeInterval is not, all frames will be captured togenerate a total of Count images.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1637 of 1869

Cloud Infinite

Average mode: The Count parameter takes effect,indicating to capture a total of Count images at an averageinterval in the entire video.
Fps mode: TimeInterval indicates how many frames
to capture per second, and Count indicates how many
frames to capture in total.
Count

Number of captured frames. Value range: (0, 10000].

StringNo

TimeIntervalVideo frame capturing frequency. Value range: (0, 60]
seconds. The value supports the float format, accurate to themillisecond.

String

No

Dict

No

StringNo

UserInfo

Business field. For details on parameters that can be passed
in, see the UserInfo field in Submitting Video Moderation
Job.

DataIdThis field will return the original content in the moderation
result, which can contain up to 512 bytes. You can use thisfield to uniquely identify the data to be moderated in yourbusiness.

Response parameters
Calling the ci_auditing_video_submit function will convert the XML returned in the API into a dict value.
For specific response parameters, see Submitting Video Moderation Job.

Querying Video Moderation Job Result
Feature description
This API is used to query the result of a specified video moderation job. The video moderation feature is async. You
can submit a job to moderate your video files, and then use the API for querying video moderation job result to query
the moderation results.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1638 of 1869

Cloud Infinite"""Test the CI's API for querying moderation job result"""# Create a COS client# Query the moderation result
response = client.ci_auditing_video_query(
Bucket='bucket',
JobID='v11122zxxxazzz')
print response

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 1639 of 1869

Cloud Infinite

The ci_auditing_video_query function is called. Specific request parameters are as follows:
Parameter

Description

Type

Required

BucketBucket name.

StringYes

JobID

Moderation job ID.

StringYes

Response parameters
Calling the ci_auditing_video_query function will convert the XML returned in the API into a dict value.
For specific response parameters, see Querying Video Moderation Job Result.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1640 of 1869

Cloud Infinite

Audio Moderation：

Last updated 2024-03-01 14:57:12

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for audio moderation.
Note:
COS Python SDK v5.1.9.10 or later is required. Earlier versions may contain bugs and need to be upgraded to thelatest version when being used.
API

Description

Submitting audio moderation job

Submits an audio moderation job.

Querying audio moderation job result

Queries the result of a specified audio moderation job.

Submitting an Audio Moderation Job
Feature description
This API is used to submit an audio moderation job. The audio moderation feature is async. You can submit a job tomoderate your audio files, and then use the API for querying audio moderation job result to query the moderation
results.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1641 of 1869

Cloud Infinite"""Test the CI's API for moderating audio file content"""# Create a COS client# Recognize an audio in COS
response= client.ci_auditing_audio_submit(
Bucket='bucket',
DetectType=CiDetectType.PORN | CiDetectType.ADS,
Key='test.mp3')
print response©2013-2022 Tencent Cloud. All rights reserved.

Page 1642 of 1869

Cloud Infinite

Parameter description
The ci_auditing_audio_submit function is called. Specific request parameters are as follows:
Parameter

Description

Type

Required

BucketBucket name.

StringYes

Key

Object name, such as picture.jpg .

StringYes

BizType

Unique identifier of the moderation policy. You can configure thescenes you want to moderate on the moderation policy page inthe console, such as pornographic, adverting, and illegal
information. For configuration guidelines, see Setting Public
Moderation Policy. You can get BizType in the console. If

String

No

enum

No

StringNo

StringNo

String

No

Dict

No

String

No

BizType is specified, the moderation request will perform
moderation based on the scenes configured in the moderation
policy. If BizType is not specified, the default moderation
policy will be used automatically.
Moderation type. Valid values: CiDetectType.PORN(pornography), CiDetectType.ADS (advertising). You can
DetectType

select multiple types. For example, CiDetectType.PORN |CiDetectType.ADS indicates to moderate the audio forpornographic and advertising information. If you need more
moderation scenes, use the BizType parameter.

Url

Callback

An audio URL that is not in COS can be directly used formoderation.
Callback address, which must start with http:// or
https:// .
Structure of the callback content. Valid values: Simple (theCallbackVersion

UserInfo

DataIdcallback content contains basic information), Detail (thecallback content contains detailed information). Default value:
Simple .
Business field. For details on parameters that can be passed in,see the UserInfo field in Submitting Audio Moderation Job.
This field will return the original content in the moderation result,which can contain up to 512 bytes. You can use this field touniquely identify the data to be moderated in your business.

Response parameters©2013-2022 Tencent Cloud. All rights reserved.

Page 1643 of 1869

Cloud Infinite

Calling the ci_auditing_audio_submit function will convert the XML returned in the API into a dict value.
For specific response parameters, see Submitting Audio Moderation Job.

Querying Audio Moderation Job Result
Feature description
This API is used to query the result of a specified audio moderation job. The audio moderation feature is async. You
can submit a job to moderate your audio files, and then use the API for querying audio moderation job result to query
the moderation results.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1644 of 1869

Cloud Infinite"""Test the CI's API for querying moderation job result"""# Create a COS client# Query the moderation result
response = client.ci_auditing_audio_query(
Bucket='bucket',
JobID='v11122zxxxazzz')
print response

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 1645 of 1869

Cloud Infinite

The ci_auditing_audio_query function is called. Specific request parameters are as follows:
Parameter

Description

Type

Required

BucketBucket name.

StringYes

JobID

Moderation job ID.

StringYes

Response parameters
Calling the ci_auditing_audio_query function will convert the XML returned in the API into a dict value.
For specific response parameters, see Querying Audio Moderation Job Result.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1646 of 1869

Cloud Infinite

Text Moderation：

Last updated 2024-03-01 14:57:12

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for text moderation.
Note:
COS Python SDK v5.1.9.10 or later is required. Earlier versions may contain bugs and need to be upgraded to thelatest version when being used.
API

Description

Submitting text moderation job

Submits a text moderation job.

Querying text moderation job result

Queries the result of a specified text moderation job.

Submitting a Text Moderation Job
Feature description
This API is used to submit a text moderation job. The text moderation feature is async. You can submit a job tomoderate your text files, and then use the API for querying text moderation job result to query the moderation results.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1647 of 1869

Cloud Infinite"""Test the CI's API for moderating text file content"""# Create a COS client# Recognize a text in COS
response= client.ci_auditing_text_submit(
Bucket='bucket',
DetectType=CiDetectType.PORN | CiDetectType.ADS,
Key='test.txt')
print response©2013-2022 Tencent Cloud. All rights reserved.

Page 1648 of 1869

Cloud Infinite

Parameter description
The ci_auditing_text_submit function is called. Specific request parameters are as follows:
Parameter

Description

Type

Required

BucketBucket name.

StringYes

Key

Object name, such as picture.jpg .

StringNo

String

No

enum

No

StringNo

String

No

Dict

No

String

No

Unique identifier of the moderation policy. You can configure
the scenes you want to moderate on the moderation policy
page in the console, such as pornographic, adverting, andillegal information. For configuration guidelines, see Setting
BizTypePublic Moderation Policy. You can get BizType in the
console. If BizType is specified, the moderation request
will perform moderation based on the scenes configured in themoderation policy. If BizType is not specified, the default
moderation policy will be used automatically.
Moderation type. Valid values: CiDetectType.PORN(pornography), CiDetectType.ADS (advertising). You

DetectTypecan select multiple types. For example,
CiDetectType.PORN | CiDetectType.ADS indicatesto moderate the text for pornographic and advertisinginformation. If you need more moderation scenes, use the
BizType parameter.

Content

Callback

UserInfo

When the input content is plain text, the length of the originaltext cannot exceed 10,000 UTF-8 characters. If the length limit
is exceeded, the API will report an error.
Callback address, which must start with http:// or
https:// .
Business field. For details on parameters that can be passed
in, see the UserInfo field in Submitting Text Moderation
Job.
This field will return the original content in the moderation

DataIdresult, which can contain up to 512 bytes. You can use thisfield to uniquely identify the data to be moderated in yourbusiness.

Response parameters©2013-2022 Tencent Cloud. All rights reserved.

Page 1649 of 1869

Cloud Infinite

Calling the ci_auditing_text_submit function will convert the XML returned in the API into a dict value.
For specific response parameters, see Submitting Text Moderation Job.

Querying Text Moderation Job Result
Feature description
This API is used to query the result of a specified text moderation job. The text moderation feature is async. You can
submit a job to moderate your text files, and then use the API for querying text moderation job result to query themoderation results.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1650 of 1869

Cloud Infinite"""Test the CI's API for querying moderation job result"""# Create a COS client# Query the moderation result
response = client.ci_auditing_text_query(
Bucket='bucket',
JobID='v11122zxxxazzz')
print response

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 1651 of 1869

Cloud Infinite

The ci_auditing_text_query function is called. Specific request parameters are as follows:
Parameter

Description

Type

Required

BucketBucket name.

StringYes

JobID

Moderation job ID.

StringYes

Response parameters
Calling the ci_auditing_text_query function will convert the XML returned in the API into a dict value.
For specific response parameters, see Querying Text Moderation Job Result.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1652 of 1869

Cloud Infinite

File Moderation：

Last updated 2024-03-01 14:57:12

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for file moderation.
Note:
COS Python SDK v5.1.9.10 or later is required. Earlier versions may contain bugs and need to be upgraded to thelatest version when being used.
API

Description

Submitting file moderation job

Submits a file moderation job.

Querying file moderation job result

Queries the result of a specified file moderation job.

Submitting a File Moderation Job
Feature description
This API is used to submit a file moderation job. The file moderation feature is async. You can submit a job tomoderate your files, and then use the API for querying file moderation job result to query the moderation results.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1653 of 1869

Cloud Infinite"""Test the CI's API for moderating file content"""# Create a COS client# Recognize a file in COS
response = client.ci_auditing_document_submit(
Bucket=bucket_name,
DetectType=CiDetectType.PORN | CiDetectType.ADS,
Url='https://www.test.com/sss.docx',
Type='docx',)
print response©2013-2022 Tencent Cloud. All rights reserved.

Page 1654 of 1869

Cloud Infinite

Parameter description
The ci_auditing_document_submit function is called. Specific request parameters are as follows:
Parameter

Description

Type

Required

BucketBucket name.

StringYes

Key

Object name, such as picture.jpg .

String

No

enum

Yes

Moderation type. Valid values: CiDetectType.PORN (pornography),
CiDetectType.ADS (advertising). You can select multiple types.
DetectType

For example, CiDetectType.PORN | CiDetectType.ADS
indicates to moderate the file for pornographic and advertisinginformation. If you need more moderation scenes, use the BizTypeparameter.

Url

A file URL that is not in COS can be directly used for moderation.

StringNo

Type

File type. If this parameter is not specified, the file extension will be usedas the type by default, such as DOC, DOCX, PPT, and PPTX. If the file
has no extension, this field must be specified; otherwise, moderation will
fail.

StringNo

Callback

Callback address, which must start with http:// or https:// .

StringNo

String

No

Unique identifier of the moderation policy. You can configure the scenes
you want to moderate on the moderation policy page in the console, such

BizTypeas pornographic, adverting, and illegal information. For configuration
guidelines, see Setting Public Moderation Policy. You can get
BizType in the console. If BizType is specified, the moderation
request will perform moderation based on the scenes configured in themoderation policy. If BizType is not specified, the default moderation
policy will be used automatically.

UserInfo

Business field. For details on parameters that can be passed in, see the
UserInfo field in Submitting File Moderation Job.

Dict

No

DataIdThis field will return the original content in the moderation result, which
can contain up to 512 bytes. You can use this field to uniquely identify
the data to be moderated in your business.

StringNo

Response parameters
Calling the ci_auditing_document_submit function will convert the XML returned in the API into a dictvalue. For specific response parameters, see Submitting File Moderation Job.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1655 of 1869

Cloud Infinite

Querying File Moderation Job Result
Feature description
This API is used to query the result of a specified file moderation job. The file moderation feature is async. You can
submit a job to moderate your files, and then use the API for querying file moderation job result to query themoderation results.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1656 of 1869

Cloud Infinite"""Test the CI's API for querying moderation job result"""# Create a COS client# Query the moderation result
response = client.ci_auditing_document_query(
Bucket='bucket',
JobID='v11122zxxxazzz')
print response

Parameter description
The ci_auditing_document_query function is called. Specific request parameters are as follows:
Parameter

Description

Type

Required

BucketBucket name.

StringYes

JobID

Moderation job ID.

StringYes

Response parameters
Calling the ci_auditing_document_query function will convert the XML returned in the API into a dictvalue. For specific response parameters, see Querying File Moderation Job Result.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1657 of 1869

Cloud Infinite

Webpage Moderation：

Last updated 2024-03-01 14:57:12

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note:
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for webpage moderation.
Note:
COS Python SDK v5.1.9.18 or later is required. Earlier versions may contain bugs and need to be upgraded to thelatest version when being used.
API

Description

Submitting webpage moderation job

Submits a webpage moderation job.

Querying webpage moderation job result

Queries the result of a specified webpage moderation job.

Submitting a Webpage Moderation Job
Feature description
This API is used to submit a webpage moderation job. The webpage moderation feature is async. You can submit a
job to moderate your webpage files, and then use the API for querying webpage moderation job result to query themoderation results.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1658 of 1869

Cloud Infinite"""Test the CI's API for moderating webpage file content"""# Create a COS client# Recognize a webpage in COS
response= client.ci_auditing_html_submit(
Bucket='bucket',
DetectType=CiDetectType.PORN | CiDetectType.ADS,
Url='http://example.com')
print response©2013-2022 Tencent Cloud. All rights reserved.

Page 1659 of 1869

Cloud Infinite

Parameter description
The ci_auditing_html_submit function is called. Specific request parameters are as follows:
Parameter

Description

Type

Required

BucketBucket name.

StringYes

Url

Webpage URL.

StringYes

String

No

enum

No

StringNo

String

No

Bool

No

Dict

No

String

No

Unique identifier of the moderation policy. You can configure

BizTypethe scenes you want to moderate on the moderation policy
page in the console, such as pornographic, adverting, andillegal information. For configuration guidelines, see Setting
Public Moderation Policy. You can get BizType in the
console. If BizType is specified, the moderation request
will perform moderation based on the scenes configured in
the moderation policy. If BizType is not specified, thedefault moderation policy will be used automatically.
Moderation type. Valid values: CiDetectType.PORN(pornography), CiDetectType.ADS (advertising). You

DetectTypecan select multiple types. For example,
CiDetectType.PORN | CiDetectType.ADS
indicates to moderate the webpage for pornographic andadvertising information. If you need more moderation
scenes, use the BizType parameter.

Url

Callback

A webpage URL that is not in COS can be directly used formoderation.
Callback address, which must start with http:// or
https:// .
This parameter specifies whether to highlight the noncompliant text on the webpage. When the result is queried

ReturnHighlightHtml

or called back, this parameter decides whether to return thehighlighted HTML content. Valid values: true ,false . Default value: false .

UserInfo

Business field. For details on parameters that can bepassed in, see the UserInfo field in Submitting
Webpage Moderation Job.

DataIdThis field will return the original content in the moderation
result, which can contain up to 512 bytes. You can use this©2013-2022 Tencent Cloud. All rights reserved.

Page 1660 of 1869

Cloud Infinite

field to uniquely identify the data to be moderated in yourbusiness.

Response parameters
Calling the ci_auditing_html_submit function will convert the XML returned in the API into a dict value.
For specific response parameters, see Submitting Webpage Moderation Job.

Querying Webpage Moderation Job Result
Feature description
This API is used to query the result of a specified webpage moderation job. The webpage moderation feature is async.
You can submit a job to moderate your webpage files, and then use the API for querying webpage moderation job
result to query the moderation results.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1661 of 1869

Cloud Infinite"""Test the CI's API for querying moderation job result"""# Create a COS client# Query the moderation result
response = client.ci_auditing_html_query(
Bucket='bucket',
JobID='v11122zxxxazzz')
print response

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 1662 of 1869

Cloud Infinite

The ci_auditing_html_query function is called. Specific request parameters are as follows:
Parameter

Description

Type

Required

BucketBucket name.

StringYes

JobID

Moderation job ID.

StringYes

Response parameters
Calling the ci_auditing_html_query function will convert the XML returned in the API into a dict value.
For specific response parameters, see Querying Webpage Moderation Job Result.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1663 of 1869

Cloud Infinite

Content Recognition
Speech Recognition
Job APIs：

Last updated 2024-03-01 14:57:12

Overview
This document provides an overview of APIs and SDK code samples for speech recognition jobs.
API

Operation

Description

Submitting a speech
recognition job

Submits a speech recognition
job

Submiting a speech recognition job.

Querying the specified speech
recognition job

Queries the specified speech
recognition job

Querying the specified speech recognition
job.

Pulling eligible speech

Pulls eligible speech

Pulling speech recognition jobs that meet

recognition jobs

recognition jobs

specified conditions.

Submitting Speech Recognition Job
Feature description
This API ( ci_create_asr_job ) is used to submit a speech recognition job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1664 of 1869

Cloud Infinite

def ci_create_asr_job(self, Bucket, QueueId, InputObject, OutputBucket, OutputRegio
SpeechRecognition=None, CallBack=None, CallBackFormat=None, C

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1665 of 1869

Cloud Infinite

def ci_create_asr_jobs():# Create an async speech recognition job (with a template)
response = client.ci_create_asr_job(
Bucket=bucket_name,
QueueId='s0980xxxxxxxxxxxxxxxxff12',
TemplateId='t1ada6f282d29742dxxxxxxxxxxxxx',
InputObject='normal.mp4',
OutputBucket=bucket_name,OutputRegion='ap-chongqing',
OutputObject='result.txt',)©2013-2022 Tencent Cloud. All rights reserved.

Page 1666 of 1869

Cloud Infinite

print(response)
return response
def ci_create_asr_jobs():# Create an async speech recognition job (with parameters)
body = {'EngineModelType': '16k_zh','ChannelNum': '1',
'ResTextFormat': '1',}
response = client.ci_create_asr_job(
Bucket=bucket_name,
QueueId='s0980xxxxxxxxxxxxxxxxff12',
InputObject='normal.mp4',
OutputBucket=bucket_name,OutputRegion='ap-chongqing',
OutputObject='result.txt',
SpeechRecognition=body)print(response)
return response

Parameter description
Parameter

Description

Type

BucketBucket of the object

StringQueueId

ID of the queue which the job is in

StringInputObject

The object to be processed

Container

OutputRegion

Bucket region

StringOutputBucket

Result storage bucket

StringOutputObject

Output file path

StringTemplateId

Template ID

StringSpeechRecognition

Speech recognition parameter. For more information, see
SpeechRecognition in Submitting Speech Recognition Job.

dict

CallBack

Job callback address, which has a higher priority than that of the queue. If
it is set to no , no callbacks will be generated at the callback address ofstringthe queue.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1667 of 1869

Cloud Infinite

CallBackFormat

Job callback format, which can be JSON or XML (default). It has astringhigher priority than that of the queue.
CallBackType

CallBackMqConfig

Job callback type, which can be Url (default) or TDMQ . It has ahigher priority than that of the queue.
TDMQ configuration for job callback as described in Structure, which is
required if CallBackType is TDMQ .

stringdict

Response description©2013-2022 Tencent Cloud. All rights reserved.

Page 1668 of 1869

Cloud Infinite{'JobsDetail': {'Code': 'Success','CreationTime': '2022-09-14T22:31:38+0800','EndTime': '-',
'Input': {'BucketId': 'test-12539xxxxx', 'Object': 'normal.mp4', 'Region':'JobId': 'sf1398ed0343911eda6d733209028ff12','Message': None,'Operation': {'JobLevel': '0',
'Output': {'Bucket': 'test-12539xxxxx', 'Object': 'result.txt', 'Region'TemplateId': 't1ada6f282d29742db83244e085exxxxxx','TemplateName': 'name'},'QueueId': 'p7369ebcf8f93414c8250c966xxxxxxxx','StartTime': '-',
'State': 'Submitted','Tag': 'SpeechRecognition'}}

Parameter

Description

Type

JobsDetailJob details

Container

CodeError code, which will be returned only if State is Failed .

StringMessage

Error message, which will be returned only if State is Failed .

String

JobId

Job ID

StringTag

Job tag: DocProcess

StringState

Job status. Valid values: Submitted , Running , Success ,Failed , Pause , Cancel .

StringCreationTime

Job creation time

StringQueueId

ID of the queue which the job is in

String

Input

Input file path of the job

Container

Operation

Operation ruleContainer

Querying Speech Recognition Job©2013-2022 Tencent Cloud. All rights reserved.

Page 1669 of 1869

Cloud Infinite

Feature description
This API ( ci_get_asr_job ) is used to query a specified speech recognition job.
Method prototype

def ci_get_asr_job(self, Bucket, JobID, **kwargs):

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1670 of 1869

Cloud Infinite

def ci_get_asr_jobs():# Get the information of a speech recognition job
response = client.ci_get_asr_job(
Bucket=bucket_name,
JobID='s18a9xxxxxxxxxxxxxxxxxxxxff1aa',)
print(response)
return response

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 1671 of 1869

Cloud Infinite

Parameter

Description

Type

BucketBucket of the object

StringJobID

Speech recognition job ID

StringResponse description{'JobsDetail': [{©2013-2022 Tencent Cloud. All rights reserved.

Page 1672 of 1869

Cloud Infinite'Code': 'Success','CreationTime': '2022-09-14T22:36:51+0800','EndTime': '2022-09-14T22:37:01+0800','Input': {'BucketId': 'testpic-1253960454', 'Object': 'gaobai.mp4', 'Region'JobId': 'sabfb88d6343a11ed8c375fe3d77ef1d7','Message': None,'Operation': {'JobLevel': '0',
'Output': {'Bucket': 'testpic-1253960454', 'Object': 'result.txt', 'Reg
'SpeechRecognitionResult': {'AudioTime': '215.637','ObjectName': 'result.txt','Result': '[0:0.160,1:0.640] Test test\\n', 'ResultDetail': None},
'TemplateId': 't1ada6f282d29742db83244e085e920b08','TemplateName': 'name'},'QueueId': 'p7369ebcf8f93414c8250c9663e1dff5a','StartTime': '2022-09-14T22:36:53+0800','State': 'Success','Tag': 'SpeechRecognition'}]}
Parameter
JobsDetail

NonExistJobIds

Description

Type

Job details, which is the same as Response.JobsDetail in theContainer

CreateSpeechRecognitionJobs API.
List of non-existing job IDs queried. If all jobs exist, this node will not be
returned.

StringPulling Eligible Speech Recognition Jobs
Feature description
The API ( ci_list_doc_jobs ) is used to pull speech recognition jobs that meet specified conditions.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1673 of 1869

Cloud Infinite

def ci_list_asr_jobs(self, Bucket, QueueId, StartCreationTime=None, EndCreationTime

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1674 of 1869

Cloud Infinite

def ci_list_asr_jobs():# Get the list of speech recognition jobs
response = client.ci_list_asr_jobs(
Bucket=bucket_name,
QueueId='p4bdxxxxxxxxxxxxxxxxxxxx57f1',
Size=10,)print(response)
return response©2013-2022 Tencent Cloud. All rights reserved.

Page 1675 of 1869

Cloud Infinite

Parameter description
Parameter

Description

Type

BucketBucket of the job

StringQueueId

ID of the queue from which jobs are pulled

StringOrderByTime

Desc (default) or Asc

StringNextToken

Context token for pagination

StringSize

StatesMaximum number of jobs that can be pulled. The default value is 10 . The
maximum value is 100 .
Status of the jobs to pull. If you enter multiple job statuses, separate them bycomma. Valid values: All (default), Submitted , Running ,Int

StringSuccess , Failed , Pause , Cancel .
StartCreationTime

EndCreationTime

Start time of the time range for job pulling in the format of %Y-%m%dT%H:%m:%S%z .
End time of the time range for job pulling in the format of %Y-%m%dT%H:%m:%S%z .

StringStringResponse description©2013-2022 Tencent Cloud. All rights reserved.

Page 1676 of 1869

Cloud Infinite{'JobsDetail': [{'Code': 'Success','CreationTime': '2022-09-14T22:36:51+0800','EndTime': '2022-09-14T22:37:01+0800','Input': {'BucketId': 'test-125396xxxx', 'Object': 'gaobai.mp4', 'Region':'JobId': 'sabfb88d6343a11ed8c375fe3dxxxxxxx','Message': None,'Operation': {'JobLevel': '0',
'Output': {'Bucket': 'test-125396xxxx', 'Object': 'result.txt', 'Region©2013-2022 Tencent Cloud. All rights reserved.

Page 1677 of 1869

Cloud Infinite'SpeechRecognitionResult': {'AudioTime': '215.637','ObjectName': 'result.txt','Result': '[0:0.160,1:0.640]'ResultDetail': None},

Test test.\\n','TemplateId': 't1ada6f282d29742db83244e085xxxxxx','TemplateName': 'name'},'QueueId': 'p7369ebcf8f93414c8250c966xxxxxxx','StartTime': '2022-09-14T22:36:53+0800','State': 'Success','Tag': 'SpeechRecognition'}],'NextToken': '15966'}

Parameter
JobsDetail
NextToken

Description
Job details, which is the same as Response.JobsDetail in theCreateSpeechRecognitionJobs API.
Context token for pagination©2013-2022 Tencent Cloud. All rights reserved.

Type
Container
StringPage 1678 of 1869

Cloud Infinite

Speech Recognition Bucket APIs：

Last updated 2024-03-01 14:57:12

Overview
This document provides an overview of APIs and SDK code samples for querying the enablement status of speech
recognition.
API

Description

Querying the enablement status of speech
recognition

Queries whether the speech recognition feature has beenenabled for a bucket.

Querying the Enablement Status of Speech Recognition
Feature description
This API ( ci_get_asr_bucket ) is used to query whether the speech recognition feature has been enabled for abucket.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1679 of 1869

Cloud Infinite

def ci_get_asr_bucket(self, Regions='', BucketName='', BucketNames='', PageNumber='

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1680 of 1869

Cloud Infinite

def ci_get_asr_bucket():# Query the enablement status of speech recognition
response = client.ci_get_asr_bucket(
Regions=region,# BucketName='demo',
BucketNames=bucket_name,PageSize=1,
PageNumber=1)
print(response)
return response©2013-2022 Tencent Cloud. All rights reserved.

Page 1681 of 1869

Cloud Infinite

Parameter description
Parameter

Description

Type

Region information, such as ap-shanghai and ap-beijing . To specify
Regions

multiple regions, separate them by comma. For more information, see Regions andstring

Domain Names.
BucketNames

Bucket name. Separate multiple bucket names by comma. Exact search is
supported.

stringBucketName

Bucket name prefix. Prefix search is supported.

stringPageNumber

Page number.

int

pageSize

Number of entries per page.

int

Response description©2013-2022 Tencent Cloud. All rights reserved.

Page 1682 of 1869

Cloud Infinite{'TotalCount': '1',
'RequestId': 'NjMyMWE2ZjZfZWM0YTYyNjRxxxxxxxxxxxx','PageNumber': '1',
'PageSize': '1',
'AsrBucketList': [{'Name': 'test-125xxxxxxx','CreateTime': '2022-08-11T00:00:00+0800','Region': 'ap-chongqing','AliasBucketId': None,'BucketId': 'test-125xxxxxxxx'©2013-2022 Tencent Cloud. All rights reserved.

Page 1683 of 1869

Cloud Infinite}]}
Parameter

Description

Type

RequestId

Unique ID of the request

stringTotalCount

Total number of buckets with speech recognition enabled

int

PageNumber

Current page number, which is the same as pageNumber in the request.

int

PageSize

Number of entries per page, which is the same as pageSize in the request.

int

AsrBucketList

List of buckets with speech recognition enabled

Container

BucketId

Bucket ID

stringName

Bucket name, which is the same as BucketId .

stringRegionRegionstringCreateTime

Creation time

stringAliasBucketId

Bucket alias

string©2013-2022 Tencent Cloud. All rights reserved.

Page 1684 of 1869

Cloud Infinite

Queue APIs：

Last updated 2024-03-01 14:57:12

Overview
This document provides an overview of APIs and SDK code samples for speech recognition queues.
API

Operation

Description

Querying a speech recognition
queue

Queries a speech recognition
queue

Querying a speech recognition
queue

Updating a speech recognition
queue

Updates a speech recognition
queue

Updating a speech recognition
queue

Querying Speech Recognition Queue
Feature description
This API ( ci_get_asr_queue ) is used to query a speech recognition queue.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1685 of 1869

Cloud Infinite

def ci_get_asr_queue(self, Bucket, State='All', QueueIds='', PageNumber='', PageSiz

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1686 of 1869

Cloud Infinite

def ci_get_asr_queue():# Query a speech recognition queue
response = client.ci_get_asr_queue(
Bucket=bucket_name,
PageNumber=1,
PageSize=1,)
print(response)
return response©2013-2022 Tencent Cloud. All rights reserved.

Page 1687 of 1869

Cloud Infinite

Parameter description
Parameter

Description

Type

BucketBucket of the queue.

StringQueueIds

Queue ID. If you enter multiple IDs, separate them by comma.

StringState

1. Active: Jobs in the queue will be scheduled and executed by the file preview
service.
2. Paused: The queue is paused, and jobs in it will no longer be scheduled andexecuted. All jobs in the queue will remain in the Paused status, while jobs
being executed will continue without being affected.

StringPageNumber

Page number.

int

PageSize

Number of entries per page.

int

Response description©2013-2022 Tencent Cloud. All rights reserved.

Page 1688 of 1869

Cloud Infinite{'TotalCount': '1',
'RequestId': 'NjMyMWExY2RfMTIwNjxxxxxxxxxxxxxxxxxx','PageNumber': '1',
'PageSize': '1',
'QueueList': [{'QueueId': 'p4bdf22746bxxxxxxxxxxxxxxxxxxxxxx','Name': 'speech-queue','State': 'Active','NotifyConfig': {'Url': 'http://www.demo.callback.com',©2013-2022 Tencent Cloud. All rights reserved.

Page 1689 of 1869

Cloud Infinite'Event': 'TaskFinish','Type': 'Url','State': 'On','ResultFormat': 'JSON','MqMode': None,'MqName': None,'MqRegion': None},
'MaxSize': '10000','MaxConcurrent': '10','CreateTime': '2022-08-11T14:42:01+0800','UpdateTime': '2022-09-14T11:18:08+0800','BucketId': 'test-125xxxxxxxxxx','Category': 'Speeching'}]}Parameter

Description

Type

RequestId

Unique ID of the request

StringTotalCount

Total number of queues

Int

PageNumber

Current page number, which is the same as pageNumber in the request.

Int

PageSize

Number of entries per page, which is the same as pageSize in therequest.

Int

QueueList

Queue array

Container

NonExistPIDs

List of IDs of non-existent queues

String array

QueueId

Queue ID

StringName

Queue name

StringState

Current status: Active or Paused .

StringNotifyConfig

Callback configuration

Container

MaxSize

Maximum length of the queue

Int

MaxConcurrent

Maximum number of concurrent jobs in the current queueInt

UpdateTime

Update time

StringCreateTime

Creation time

String©2013-2022 Tencent Cloud. All rights reserved.

Page 1690 of 1869

Cloud Infinite

Url

Callback address

StringState

Switch status: On or Off .

StringType

Callback type: Url .

String

Event

The event that triggers the callback

StringUpdating Speech Recognition Queue
Feature description
This API ( ci_update_asr_queue ) is used to update a speech recognition queue.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1691 of 1869

Cloud Infinite

def ci_update_asr_queue(self, Bucket, QueueId, Request={}, **kwargs):

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1692 of 1869

Cloud Infinite

def ci_put_asr_queue():# Update a speech recognition queue
body = {'Name': 'speech-queue','QueueID': 'p4bdf22xxxxxxxxxxxxxxxxxxxxxxxxxf1','State': 'Active','NotifyConfig': {'Type': 'Url','Url': 'http://www.demo.callback.com','Event': 'TaskFinish','State': 'On',©2013-2022 Tencent Cloud. All rights reserved.

Page 1693 of 1869

Cloud Infinite'ResultFormat': 'JSON'}}
response = client.ci_update_asr_queue(
Bucket=bucket_name,
QueueId='p4bdf22xxxxxxxxxxxxxxxxxxxxxxxxxf1',
Request=body,ContentType='application/xml')
print(response)
return response

Parameter description
Parameter

Description

Type

BucketBucket name

StringName

Queue name

StringQueueID

Queue ID

StringRequestRequest body of the updated queue configuration

StringResponse description©2013-2022 Tencent Cloud. All rights reserved.

Page 1694 of 1869

Cloud Infinite{'RequestId': 'NjMyMWEzMTFfZWMxxxxxxxxxxxxxxxxxxxx','Queue': [{'QueueId': 'p4bdf22746b0xxxxxxxxxxxxxxxxxx','Name': 'speech-queue','State': 'Active','NotifyConfig': {'Url': 'http://www.demo.callback.com','Event': 'TaskFinish','Type': 'Url','State': 'On',©2013-2022 Tencent Cloud. All rights reserved.

Page 1695 of 1869

Cloud Infinite'ResultFormat':'JSON','MqMode': None,'MqName': None,'MqRegion': None},
'MaxSize': '10000','MaxConcurrent': '10','CreateTime': '2022-08-11T14:42:01+0800','UpdateTime': '2022-09-14T11:18:08+0800','BucketId': 'test-125xxxxxxxxxxx','Category': 'Speeching'}]}Parameter

Description

Type

RequestId

Unique ID of the request

dict

Queue

Queue information. For more information, see QueueList in Querying Speech
Recognition Queue.

©2013-2022 Tencent Cloud. All rights reserved.

dictPage 1696 of 1869

Cloud Infinite

Image QR Code：

Last updated 2024-03-01 14:57:12

Overview
This document provides an overview of APIs and SDK code samples for image QR codes.
API

Description

QR codeRecognizes the location and content of valid QR codes in an image, outputs the text information

recognition(URL or text) contained in the QR codes, and pixelates the recognized QR codes.

QR Code Recognition
The QR code recognition feature recognizes the location and content of valid QR codes in an image, outputs the text
information (URL or text) contained in the QR codes, and pixelates the recognized QR codes.

Recognizing QR code during upload
Feature description
The request for recognizing QR codes during image upload is the same as that used to simply upload a file to COS,
except that you need to add the image processing parameter Pic-Operations to the request header.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1697 of 1869

Cloud Infinite# Create a COS client
example_object = 'example_object.jpg'
with open(example_object, 'rb') as fp:
opts = '{"is_pic_info":1,"rules":[{"fileid":"format.jpg","rule":"QRcode/cov
response,data = client.ci_put_object_from_local_file_and_get_qrcode(
Bucket='example-bucket-123456789',
LocalFilePath=example_object,
Key='example_key',
EnableMD5=False,
PicOperations=opts)©2013-2022 Tencent Cloud. All rights reserved.

Page 1698 of 1869

Cloud Infinite# View the response information and read the specified data as needed
print(response,data)

Parameter description
Parameter

Description

Type

Required

BucketBucket name in the format of BucketName-APPID

StringYes

LocalFilePath

Image path

StringYes

String

Yes

Bool

No

StringYes

Unique identifier of the object in the bucket. For example, if an
object's access endpoint is examplebucketKey

1250000000.cos.apguangzhou.myqcloud.com/doc/pic.jpg , its key is
doc/pic.jpg .
Specifies whether the SDK needs to calculate the Content-

EnableMD5MD5 checksum. It is disabled by default. The upload will takelonger if it is enabled.

PicOperations

CI image processing parameters. For more information, see
QR Code Recognition.

Recognizing QR code in the cloud
Feature description
This feature recognizes QR codes in an image stored in the cloud and returns the recognition result.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1699 of 1869

Cloud Infinite# Create a COS client
response,data = client.ci_get_object_qrcode(
Bucket='example_bucket-123456789',
Key='example_object',
Cover=0)# View the response information and read the specified data as needed
print(response,data)

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 1700 of 1869

Cloud Infinite

Parameter

Description

Type

Required

BucketBucket name in the format of BucketName-APPID

StringYes

String

Yes

Int

Yes

Unique identifier of the object in the bucket. For example, if an
object's access endpoint is examplebucketKey

1250000000.cos.apguangzhou.myqcloud.com/doc/pic.jpg , its key is
doc/pic.jpg .

CoverWhether to pixelate QR codes. For more information, see QR
Code Recognition.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1701 of 1869

Cloud Infinite

File Processing
File Transcoding：

Last updated 2024-03-01 14:57:12

Overview
This document provides an overview of APIs and SDK code samples for file preview.
API

Operation

Description

CreateDocProcessJobs

Submitting file preview job

Submits file preview job.

DescribeDocProcessJob

Querying file preview job

Queries specified file preview job.

DescribeDocProcessJobs

Pulling file preview jobs

Pulls eligible file preview jobs.

Submitting File Preview Job
Feature description
This API ( ci_create_doc_job ) is used to submit a file preview job.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1702 of 1869

Cloud Infinite

response = client.ci_create_doc_job(
Bucket="examplebucket-1250000000",
QueueId='pbbbcc56b344e422da78c984be45*****',
InputObject='normal.pptx',
OutputBucket="examplebucket-1250000000",
OutputRegion='ap-chongqing',
OutputObject='/test_doc/normal/abc_${Number}.jpg',)
print(response)
return response©2013-2022 Tencent Cloud. All rights reserved.

Page 1703 of 1869

Cloud Infinite

Parameter description
To call the ci_create_doc_job function, the specific request parameters are as follows:
Parameter

Description

Type

Required

BucketBucket name.

StringYes

QueueId

Queue ID of the job.

StringYes

InputObject

File URL in COS.

StringYes

OutputBucket

Result storage bucket.

StringYes

OutputRegion

Result storage bucket region.

StringYes

StringYes

StringNo

String

No

Int

No

Output file path. <br/>For non-spreadsheet files, the output filename must include the ${Number} or ${Page}
parameter. If there are multiple output files, ${Number} indicatesthat serial numbers start from 1, and ${Page} indicates that serial
numbers are the same as preview page numbers. <ul style="marginbottom:0px"><li> ${Number} indicates that serial numbers startfrom 1 for multiple output files; for example, if the input parameter is
abc_${Number}.jpg to preview pages 5–6 in the file, thenoutput file names will be abc_1.jpg and abc_2.jpg .</li><li> ${Page} indicates that serial numbers are the same as
OutputObject

preview page numbers for multiple output files; for example, if the
input parameter is abc_${Page}.jpg to preview pages 5–6 in
the file, then the output file names will be abc_5.jpg andabc_6.jpg . <br/>For spreadsheet files, the output file pathmust include the ${SheetID} placeholder, and the output
file name must include the ${Number} parameter.<br>For
example, if the input parameter is/${SheetID}/abc_${Number}.jpg , then the corresponding
number of folders will be generated first according to the number of
Excel sheets to be converted, and then the corresponding number ofimage files will be generated in these folders.</li></ul>

SrcType

TgtType

Source data type. Currently, the file conversion feature determines
the source data type according to the file extension of the COS
object. If the object has no extension, you can set this value.
Type of the output target file. Valid values: png, jpg, pdf. If the input
file format cannot be recognized, the jpg format will be used bydefault. You cannot specify pages for the pdf format.

StartPage

Starts conversion from page X. A spreadsheet file may be split into

©2013-2022 Tencent Cloud. All rights reserved.

Page 1704 of 1869

Cloud Infinite

multiple pages, with multiple images generated, and StartPage
indicates to start the conversion from page X of the specified
SheetId . Default value: 1.

EndPageEnds conversion on page X. A spreadsheet file may be split into
multiple pages, with multiple images generated, and EndPage
indicates to end the conversion on page X of the specified
SheetId . Default value: -1 (converting all pages).

Int

No

SheetId

Sheet parameter, indicating to convert the xth sheet. Default value: 0(converting all sheets).

Int

No

PaperDirection

Paper orientation of the spreadsheet. 0: vertical; other values:
horizontal. Default value: 0.

Int

No

PaperSize

Page (canvas) size. Valid values: 0 (A4), 1 (A2), 2 (A0). Default
value: 0.

Int

NoStringNo

Comments

Whether to hide comments and apply track changes. 0: hidecomments and apply track changes; 1: show comments and trackchanges. Default value: 0.

Int

No

ImageParams

Processing parameters for the output image. All parameters of basic
image processing are supported. To specify multiple parameters,
separate them by pipeline operator. In this way, the image can beprocessed by multiple parameters in sequence in the same request.

String

No

Quality

Quality of the generated preview image. Value range: [1-100]. Default
value: 100. For example, if the value is 100, the quality of thegenerated image will be 100%.

Int

No

Zoom

Scaling parameter of the preview image. Value range: [10-200].
Default value: 100. For example, if the value is 200, the image will bescaled up (enlarged) by 200%.

Int

No

Int

No

Int

No

DocPassword

ImageDpi

Password to open the Office file. If you need to convert a passwordprotected file, set this field.

Renders the image according to the specified DPI. This parameterworks together with Zoom . Value range: 96–600. Default value: 96.
The width of the output image must be less than 65500 px.

PicPagination

Whether to convert to a single long image. When this parameter is set
to 1, up to 20 standard pages can be converted to a single long
image, and more pages will cause an error. The page range can becontrolled by StartPage and EndPage . The default value is 0,©2013-2022 Tencent Cloud. All rights reserved.

Page 1705 of 1869

Cloud Infinite

indicating to output images by page. This parameter will take effectonly if TgtType is png or jpg .

Response parameter description
Calling the ci_create_doc_jobs function will convert the XML returned in the API into a dict value. For
specific response parameters, see Submitting File Preview Job.

Querying Specified File Preview Job
Feature description
This API ( ci_get_doc_job ) is used to query a specified file preview job.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1706 of 1869

Cloud Infinite

response = client.ci_get_doc_job(
Bucket="examplebucket-1250000000",
JobID='d31d414c8c07811ec894cd30d17*****',)
print(response)
return response

Parameter description
To call the ci_get_doc_job function, the specific request parameters are as follows:©2013-2022 Tencent Cloud. All rights reserved.

Page 1707 of 1869

Cloud Infinite

Parameter

Description

Type

Required

BucketBucket name.

StringYes

JobID

Job ID.

StringYes

Response parameter description
Calling the ci_get_doc_job function will convert the XML returned in the API into a dict value. For specificresponse parameters, see Querying File Preview Job.

Querying All File Preview Jobs
Feature description
This API ( ci_list_doc_jobs ) is used to query a specified file preview job.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1708 of 1869

Cloud Infinite

response = client.ci_list_doc_jobs(
Bucket="examplebucket-1250000000",
QueueId='pbbbcc56b344e422da78c984be45*****',)
print(response)
return response

Parameter description
To call the ci_list_doc_jobs function, the specific request parameters are as follows:©2013-2022 Tencent Cloud. All rights reserved.

Page 1709 of 1869

Cloud Infinite

Parameter

Description

Type

Required

BucketBucket name.

StringYes

QueueId

Queue ID of the job.

StringYes

StartCreationTime

Start time.

String

No

EndCreationTime

End time.

StringNo

OrderByTime

Sorting order. Valid values: Desc, Asc. Default value: Desc.

StringNo

StringNo

Status of the jobs to pull. If you enter multiple job statuses,
Statesseparate them by comma. Valid values: All (default), Submitted,
Running, Success, Failed, Pause, Cancel.

Size

Maximum number of jobs that can be pulled. Default value: 10.
Maximum value: 100.

StringNo

NextToken

Context token for pagination.

StringNo

Response parameter description
Calling the ci_list_doc_jobs function will convert the XML returned in the API into a dict value. For
specific response parameters, see Pulling File Preview Job.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1710 of 1869

Cloud Infinite

Sync Request API：

Last updated 2024-03-01 14:57:12

Overview
This document provides an overview of APIs and SDK code samples for sync requests for file preview.
API

Description

Sync request API

Synchronously requests for file preview.

Sync Request API
Feature description
This API is used to synchronously request for file preview.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1711 of 1869

Cloud Infinite

def ci_doc_preview_process(self, Bucket, Key, SrcType=None, Page=None, DstType=
ExcelPaperDirection=0, ExcelRow=0, ExcelCol=0, Excel
ImageParams=None, Quality=100, Scale=100, ImageDpi=9

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1712 of 1869

Cloud Infinite

def ci_doc_preview_process():# Sync file preview API
response = client.ci_doc_preview_process(Bucket=bucket_name,
Key='1.txt',)
print(response)
response['Body'].get_stream_to_file('result.png')

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 1713 of 1869

Cloud Infinite

Parameter

Description

Type

BucketBucket of the object

StringKey

Object name, such as folder/document.pdf .

String

SrcType

Source data type. Currently, the file conversion feature determines
the source data type according to the file extension of the COS
object. If the object has no extension, you can set this value.

StringPage

Number of the page to be converted, which is counted from 1 bydefault. For spreadsheets, page indicates to convert the xth

int

image in the xth sheet.
Type of the output target image file. Valid values: png , jpg ,DstTypepdf . If the input file format cannot be recognized, the jpg

Stringformat will be used by default.
Password

Password to open the Office file. If you need to convert apassword-protected file, set this field.

StringComment

Whether to hide comments and apply track changes. 0: hidecomments and apply track changes; 1: show comments and trackchanges. Default value: 0 .

int

Sheet

Sheet parameter, indicating to convert the xth sheet. Default
value: 1 .

int

ExcelPaperDirection

ExcelRow

ExcelCol

Paper orientation of the spreadsheet. 0 : vertical; other values:
horizontal. Default value: 0 .
The value 1 indicates that all rows will be formatted on one
page. Default value: 0 .
The value 1 indicates that all columns will be formatted on one
page. Default value: 0 .

int

int

int

Page (canvas) size. Valid values: 0 (A4), 1 (A2), 2 (A0).
ExcelPaperSize

Default value: 0 . This parameter needs to be used together

intwith excelRow or excelCol .
TxtPagination

Whether to convert to long text. When this parameter is set totrue , the text in the pages to be exported can be combined

bool

before export, and the pagination range can be controlled byRanges . The default value is false , indicating to generate.txt files by page. This parameter takes effect only if
ExportType is txt .

©2013-2022 Tencent Cloud. All rights reserved.

Page 1714 of 1869

Cloud Infinite

ImageParams

Quality

Processing parameters for the output image. All parameters ofbasic image processing are supported. To specify multiple
parameters, separate them with pipeline operators. In this way,
the image can be processed by multiple parameters in sequencein the same request.
Quality of the generated preview image. Value range: [1-100].
Default value: 100 . For example, if the value is 100 , theStringint

quality of the generated image will be 100%.

Scale

Scaling parameter of the preview image. Value range: [10, 200].
Default value: 100 . For example, if the value is 200 , theintimage will be scaled up (enlarged) by 200%.

ImageDpi

Renders the image according to the specified DPI. This parameterworks together with scale . Value range: 96–600. Default
value: 96 . The width of the output image must be less thanint

65500 px.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1715 of 1869

Cloud Infinite

Async Processing Job APIs：

Last updated 2024-03-01 14:57:12

Overview
This document provides an overview of APIs and SDK code samples for file preview jobs.
API

Operation

Description

CreateDocProcessJobs

Submitting file preview job

Submits file preview job.

DescribeDocProcessJob

Querying file preview job

Queries specified file preview job.

DescribeDocProcessJobs

Pulling file preview jobs

Pulls eligible file preview jobs.

Submitting File Preview Job
Feature description
This API ( ci_create_doc_job ) is used to submit a file preview job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1716 of 1869

Cloud Infinite

def ci_create_doc_job(self, Bucket, QueueId, InputObject, OutputBucket, OutputRegio
StartPage=None, EndPage=-1, SheetId=0, PaperDirection=0,

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1717 of 1869

Cloud Infinite

def ci_create_doc_jobs():# Create an async file preview job
response = client.ci_create_doc_job(
Bucket=bucket_name,
QueueId='p4bdf22xxxxxxxxxxxxxxxxxxxxxxxxxf1',
InputObject='normal.pptx',
OutputBucket=bucket_name,OutputRegion='ap-chongqing',
OutputObject='/test_doc/normal/abc_${Number}.jpg',# DocPassword='123',
Quality=109,©2013-2022 Tencent Cloud. All rights reserved.

Page 1718 of 1869

Cloud Infinite

PageRanges='1,3',)
print(response)
return response

Parameter description
Parameter

Description

Type

BucketBucket of the object

StringQueueId

ID of the queue which the job is in

StringInputObject

The object to be processed

Container

OutputRegion

Bucket region

StringOutputBucket

Result storage bucket

StringOutput file path. For non-spreadsheet files, the output file name must
include the ${Number} or ${Page} parameter. If there are
multiple output files, ${Number} indicates that serial numbers start from1, and ${Page} indicates that serial numbers are the same as preview
page numbers. ${Number} indicates that serial numbers start from 1 for
multiple output files; for example, if the input parameter is
abc_${Number}.jpg to preview pages 5–6 in the file, then output filenames will be abc_1.jpg and abc_2.jpg . ${Page} indicates
OutputObject

that serial numbers are the same as preview page numbers for multiple
output files; for example, if the input parameter is abc_${Page}.jpg toStringpreview pages 5–6 in the file, then the output file names will be
abc_5.jpg and abc_6.jpg . For spreadsheet files, the output
file path must include the ${SheetID} placeholder, and theoutput file name must include the ${Number} parameter. For
example, if the input parameter is/${SheetID}/abc_${Number}.jpg , then the corresponding
number of folders will be generated first based on the number of Excel
sheets to be converted, and then the corresponding number of image files
will be generated in these folders.

SrcType

Source data type. Currently, the file conversion feature determines thesource data type based on the file extension of the COS object. If the object
has no extension, you can set this value.

StringType of the output target image file. Valid values: png , jpg , pdf . If
TgtTypethe input file format cannot be recognized, the jpg format will be used byStringdefault.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1719 of 1869

Cloud Infinite

StartPage

Starts conversion from page X. A spreadsheet file may be split into multiple
pages, with multiple images generated, and StartPage indicates toIntstart the conversion from page X of the specified SheetId . Default
value: 1 .
Ends conversion on page X. A spreadsheet file may be split into multiple
EndPagepages, with multiple images generated, and EndPage indicates to end
the conversion on page X of the specified SheetId . Default value: -1

Int(converting all pages).
SheetId

PaperDirection

PaperSize

DocPassword

Sheet parameter, indicating to convert the xth sheet. Default value: 1 . If
this value is set to 0 , all sheets will be converted.
Paper orientation of the spreadsheet. 0 : Vertical; other values:
Horizontal. Default value: 0 .
Page (canvas) size. Valid values: 0 (A4), 1 (A2), 2 (A0). Default
value: 0 .
Password to open the Office file. If you need to convert a passwordprotected file, set this field.

Int

Int

Int

StringWhether to hide comments and apply track changes. 0: Hide comments
Comments

and apply track changes; 1: Show comments and track changes. Default
value: 0 .

Int

PageRanges

Range of pages to be converted; for example, "1,2-4,7" means to convert
pages 1, 2, 3, 4, and 7 in the file.

StringImageParams

Processing parameters for the output image. All parameters of basic image
processing are supported. To specify multiple parameters, separate themby pipeline operator. In this way, the image can be processed by multiple
parameters in sequence in the same request.

String

Quality

Quality of the generated preview image. Value range: [1-100]. Default
value: 100 . For example, if the value is 100, the quality of the generated

Int

image will be 100%.

Zoom

Zooming parameter of the preview image. Value range: [10-200]. Default
value: 100 . For example, if the value is 200, the image will be zoomed inInt(enlarged) by 200%.

ImageDpi

Renders the image according to the specified DPI. This parameter works
together with Zoom . Value range: 96–600. Default value: 96 . The

Int

width of the output image must be less than 65500 px.
PicPagination

Whether to convert to a single long image. When this parameter is set to©2013-2022 Tencent Cloud. All rights reserved.

Int

Page 1720 of 1869

Cloud Infinite

1 , up to 20 standard pages can be converted to a single long image, andmore pages will cause an error. The page range can be controlled byStartPage and EndPage . The default value is 0 , indicating to
output images by page. This parameter will take effect only if TgtTypeis png or jpg .

Response description{'JobsDetail': {©2013-2022 Tencent Cloud. All rights reserved.

Page 1721 of 1869

Cloud Infinite'Code': 'Success','CreationTime': '2022-09-14T00:00:00+0800','EndTime': '-',
'Input': {'BucketId': 'test-125xxxxxxxxxxx','Object': '1.txt','Region': 'ap-chongqing'},'JobId': 'dcf48xxxxxxxxxxxxxxxxxxxxxxxxxc523','Message': None,'Operation': {'DocProcess': {'Comments': '1',
'DocPassword': None,'EndPage': '-1','ImageDpi': '96','ImageParams': None,'PageRanges': '1,3','PaperDirection': '0','PaperSize': '0',
'PicPagination': '0',
'Quality': '109','SheetId': '0',
'SrcType': None,'StartPage': '0',
'TgtType': None,'Zoom': '100'},'JobLevel': '0',
'Output': {'Bucket': 'test-125xxxxxxxxxxx','Object': '/test_doc/normal/abc_${Number}.jpg','Region': 'ap-chongqing'}},'QueueId': 'p4bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx57f1','StartTime': '-',
'State': 'Submitted','Tag': 'DocProcess'}}Parameter

Description

Type

JobsDetailJob details

Container

CodeError code, which will be returned only if State is Failed .

String©2013-2022 Tencent Cloud. All rights reserved.

Page 1722 of 1869

Cloud Infinite

Message

Error message, which will be returned only if State is Failed .

String

JobId

Job ID

StringTag

Job tag: DocProcess

StringState

Job status. Valid values: Submitted , Running , Success ,Failed , Pause , Cancel .

StringCreationTime

Job creation time

StringQueueId

ID of the queue which the job is in

String

Input

Input file path of the job

Container

Operation

Operation ruleContainer

Querying Specified File Preview Job
Feature description
This API ( ci_get_doc_job ) is used to query a specified file preview job.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1723 of 1869

Cloud Infinite

def ci_get_doc_job(self, Bucket, JobID, **kwargs):

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1724 of 1869

Cloud Infinite

def ci_get_doc_jobs():# Get the information of the specified async file preview job
response = client.ci_get_doc_job(
Bucket=bucket_name,
JobID='d18a9xxxxxxxxxxxxxxxxxxxxff1aa',)
print(response)
return response

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 1725 of 1869

Cloud Infinite

Parameter

Description

Type

BucketBucket of the object

StringJobID

File preview job ID

StringResponse description{'JobsDetail':©2013-2022 Tencent Cloud. All rights reserved.

Page 1726 of 1869

Cloud Infinite[{'Code': 'Success','CreationTime': '2022-09-14T17:15:43+0800','EndTime': '2022-09-14T17:15:45+0800','Input': {'BucketId': 'testpic-1253960454', 'Object': '1.txt', 'Region': 'a'JobId': 'dcf488492340d11edb2a0e3aa2e38c523','Message': None,'Operation': {'DocProcess': {'Comments': '1',
'DocPassword': None,'EndPage': '-1','ImageDpi': '96','ImageParams': None,'PageRanges': '1,3','PaperDirection': '0','PaperSize': '0',
'PicPagination': '0',
'Quality': '109','SheetId': '0',
'SrcType': None,'StartPage': '0',
'TgtType': None,'Zoom': '100'},'DocProcessResult': {'FailPageCount': '0','PageInfo': [{'PageNo': '1', 'TgtUri': '/test_doc/normal/abc_1.jpg''SuccPageCount': '2',
'TaskId': None,'TgtType': None,'TotalPageCount': '7'},'JobLevel': '0',
'Output': {'Bucket': 'testpic-1253960454', 'Object': '/test_doc/normal/},'QueueId': 'p4bdf22746b014a22a5a097b1f1d057f1','StartTime': '2022-09-14T17:15:44+0800','State': 'Success','Tag': 'DocProcess'}]}Parameter

Description

Type

JobsDetailJob details, which is the same as Response.JobsDetail in theContainer

CreateDocProcessJobs API.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1727 of 1869

Cloud Infinite

NonExistJobIds

List of non-existing job IDs queried. If all jobs exist, this node will not be
returned.

StringPulling Eligible File Preview Jobs
Feature description
The API ( ci_list_doc_jobs ) is used to pull file preview jobs that meet specified conditions.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1728 of 1869

Cloud Infinite

def ci_list_doc_jobs(self, Bucket, QueueId, StartCreationTime=None, EndCreationTime

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1729 of 1869

Cloud Infinite

def ci_list_doc_jobs():# Get the list of async file preview jobs
response = client.ci_list_doc_jobs(
Bucket=bucket_name,
QueueId='p4bdxxxxxxxxxxxxxxxxxxxx57f1',
Size=10,)print(response)
return response©2013-2022 Tencent Cloud. All rights reserved.

Page 1730 of 1869

Cloud Infinite

Parameter description
Parameter

Description

Type

BucketBucket of the job

StringQueueId

ID of the queue from which jobs are pulled

StringOrderByTime

Valid values: Desc (default) or Asc .

StringNextToken

Context token for pagination

StringSize

StatesMaximum number of jobs that can be pulled. The default value is 10 . The
maximum value is 100 .
Status of the jobs to pull. If you enter multiple job statuses, separate them bycomma. Valid values: All (default), Submitted , Running ,Int

StringSuccess , Failed , Pause , Cancel .
StartCreationTime

EndCreationTime

Start time of the time range for job pulling in the format of %Y-%m%dT%H:%m:%S%z .
End time of the time range for job pulling in the format of %Y-%m%dT%H:%m:%S%z .

StringStringResponse description©2013-2022 Tencent Cloud. All rights reserved.

Page 1731 of 1869

Cloud Infinite{'JobsDetail': [{'Code': 'Success','CreationTime': '2022-09-14T17:15:43+0800','EndTime': '2022-09-14T17:15:45+0800','Input': {'BucketId': 'testpic-1253960454', 'Object': '1.txt', 'Region': 'a'JobId': 'dcf488492340d11edb2a0e3aa2e38c523','Message': None,'Operation': {'DocProcess': {'Comments': '1',

©2013-2022 Tencent Cloud. All rights reserved.

Page 1732 of 1869

Cloud Infinite'DocPassword': None,'EndPage': '-1','ImageDpi': '96','ImageParams': None,'PageRanges': '1,3','PaperDirection': '0','PaperSize': '0',
'PicPagination': '0',
'Quality': '109','SheetId': '0',
'SrcType': None,'StartPage': '0',
'TgtType': None,'Zoom': '100'},'DocProcessResult': {'FailPageCount': '0','PageInfo': [{'PageNo': '1', 'TgtUri': '/test_doc/normal/abc_1.jpg''SuccPageCount': '2',
'TaskId': None,'TgtType': None,'TotalPageCount': '7'},'JobLevel': '0',
'Output': {'Bucket': 'testpic-1253960454', 'Object': '/test_doc/normal/},'QueueId': 'p4bdf22746b014a22a5a097b1f1d057f1','StartTime': '2022-09-14T17:15:44+0800','State': 'Success','Tag': 'DocProcess'}],'NextToken': '75789'}
Parameter
JobsDetail
NextToken

Description
Job details, which is the same as Response.JobsDetail in theCreateDocProcessJobs API.
Context token for pagination©2013-2022 Tencent Cloud. All rights reserved.

Type
Container
StringPage 1733 of 1869

Cloud Infinite

Async Processing Queue APIs：

Last updated 2024-03-01 14:57:12

Overview
This document provides an overview of APIs and SDK code samples for file preview queues.
API

Operation

Description

DescribeDocProcessQueues

Querying file preview queues

Queries specified file preview queues.

UpdateDocProcessQueue

Updating file preview queue

Updates specified file preview queue.

Querying File Preview Queue
Feature description
This API ( ci_get_doc_queue ) is used to query file preview queues.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1734 of 1869

Cloud Infinite

def ci_get_doc_queue(self, Bucket, State='All', QueueIds='', PageNumber='', PageSiz

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1735 of 1869

Cloud Infinite

def ci_get_doc_queue():# Query a file preview queue
response = client.ci_get_doc_queue(
Bucket=bucket_name,
PageNumber=1,
PageSize=1,)
print(response)
return response©2013-2022 Tencent Cloud. All rights reserved.

Page 1736 of 1869

Cloud Infinite

Parameter description
Parameter

Description

Type

BucketBucket of the queue.

StringQueueIds

Queue ID. If you enter multiple IDs, separate them by comma.

String1. Active : Jobs in the queue will be scheduled and executed by the file preview
State

service. <br>2. Paused : The queue is paused, and jobs in it will no longer bescheduled and executed. All jobs in the queue will remain in the Paused status,

Stringwhile jobs being executed will continue without being affected.
PageNumber

Page number.

int

PageSize

Number of entries per page.

int

Response description©2013-2022 Tencent Cloud. All rights reserved.

Page 1737 of 1869

Cloud Infinite{'TotalCount': '1',
'RequestId': 'NjMyMWExY2RfMTIwNjxxxxxxxxxxxxxxxxxx','PageNumber': '1',
'PageSize': '1',
'QueueList': [{'QueueId': 'p4bdf22746bxxxxxxxxxxxxxxxxxxxxxx','Name': 'doc-queue','State': 'Active','NotifyConfig': {'Url': 'http://www.demo.callback.com',©2013-2022 Tencent Cloud. All rights reserved.

Page 1738 of 1869

Cloud Infinite'Event': 'TaskFinish','Type': 'Url','State': 'On','ResultFormat': 'JSON','MqMode': None,'MqName': None,'MqRegion': None},
'MaxSize': '10000','MaxConcurrent': '10','CreateTime': '2022-08-11T14:42:01+0800','UpdateTime': '2022-09-14T11:18:08+0800','BucketId': 'test-125xxxxxxxxxx','Category': 'DocProcessing'}]}Parameter

Description

Type

RequestId

Unique ID of the request

StringTotalCount

Total number of queues

Int

PageNumber

Current page number, which is the same as pageNumber in the request.

Int

PageSize

Number of entries per page, which is the same as pageSize in therequest.

Int

QueueList

Queue array

Container

NonExistPIDs

List of IDs of non-existent queues

Stringarray

QueueId

Queue ID

StringName

Queue name

StringState

Current status: Active or Paused .

StringNotifyConfig

Callback configuration

Container

MaxSize

Maximum length of the queue

Int

MaxConcurrent

Maximum number of concurrent jobs in the current queueInt

UpdateTime

Update time

String©2013-2022 Tencent Cloud. All rights reserved.

Page 1739 of 1869

Cloud Infinite

CreateTime

Creation time

StringUrl

Callback address

StringState

Switch status: On or Off .

StringType

Callback type: Url .

String

Event

The event that triggers the callback

StringUpdating File Preview Queue
Feature description
This API ( ci_update_doc_queue ) is used to update a file preview queue.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1740 of 1869

Cloud Infinite

def ci_update_doc_queue(self, Bucket, QueueId, Request={}, **kwargs):

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1741 of 1869

Cloud Infinite

def ci_put_doc_queue():# Update a file preview queue
body = {'Name': 'doc-queue','QueueID': 'p4bdf22xxxxxxxxxxxxxxxxxxxxxxxxxf1','State': 'Active','NotifyConfig': {'Type': 'Url','Url': 'http://www.demo.callback.com','Event': 'TaskFinish','State': 'On',©2013-2022 Tencent Cloud. All rights reserved.

Page 1742 of 1869

Cloud Infinite'ResultFormat': 'JSON'}}
response = client.ci_update_doc_queue(
Bucket=bucket_name,
QueueId='p4bdf22xxxxxxxxxxxxxxxxxxxxxxxxxf1',
Request=body,ContentType='application/xml')
print(response)
return response

Parameter description
Parameter

Description

Type

BucketBucket name

StringName

Queue name

StringQueueID

Queue ID

StringRequestRequest body of the updated queue configuration

StringResponse description©2013-2022 Tencent Cloud. All rights reserved.

Page 1743 of 1869

Cloud Infinite{'RequestId': 'NjMyMWEzMTFfZWMxxxxxxxxxxxxxxxxxxxx','Queue': [{'QueueId': 'p4bdf22746b0xxxxxxxxxxxxxxxxxx','Name': 'doc-queue','State': 'Active','NotifyConfig': {'Url': 'http://www.demo.callback.com','Event': 'TaskFinish','Type': 'Url','State': 'On',©2013-2022 Tencent Cloud. All rights reserved.

Page 1744 of 1869

Cloud Infinite'ResultFormat':'JSON','MqMode': None,'MqName': None,'MqRegion': None},
'MaxSize': '10000','MaxConcurrent': '10','CreateTime': '2022-08-11T14:42:01+0800','UpdateTime': '2022-09-14T11:18:08+0800','BucketId': 'test-125xxxxxxxxxxx','Category': 'DocProcessing'}]}Parameter

Description

Type

RequestId

Unique ID of the request

dict

Queue

Queue information. For more information, see QueueList in the response in
Querying File Transcoding Queue.

©2013-2022 Tencent Cloud. All rights reserved.

dictPage 1745 of 1869

Cloud Infinite

File-to-HTML Conversion：

Last updated 2024-03-01 14:57:12

Overview
This document provides an overview of APIs and SDK code samples for sync requests for file preview.
API

Description

File-to-HTMLconversion

The file-to-HTML conversion feature allows you to generate HTML pages for preview
from multiple types of files. It enables easy online file preview on PC, app, and otherterminals. It is widely suitable for diverse business scenarios, such as online
education, enterprise OA, online knowledge base, and online file preview.

File-to-HTML Conversion
Feature description
This API is used to covert files in various formats to HTML for preview.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1746 of 1869

Cloud Infinite

def ci_doc_preview_html_process(self, Bucket, Key, SrcType=None, Copyable='1', DstT
HtmlFront=None, HtmlRotate=None, HtmlHorizontal

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1747 of 1869

Cloud Infinite

def ci_doc_preview_to_html_process():# Sync file preview API (generating HTML)
response = client.ci_doc_preview_html_process(Bucket=bucket_name,
Key='1.txt',)
print(response)
response['Body'].get_stream_to_file('result.html')

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 1748 of 1869

Cloud Infinite

Parameter

Description

Type

Required

BucketBucket of the object

StringYes

Key

Object name

StringYes

SrcType

Source file type as listed in Getting Started.

StringNo

StringNo

StringYes

StringNo

Copyable

DstType

Whether the file content is copyable. Valid values: 1 (yes),
0 (no).
Output target file type, which is fixed at html for HTMLpreview.
Custom configuration parameters in JSON structure, which

HtmlParams

must be URL-safe Base64-encoded as described in FAQs.
Default configuration: { commonOptions: { isShowTopArea:
true, isShowHeader: true } }. For supported configurations, see
Custom Configuration Overview.

HtmlWaterword

Watermark text, which must be URL-safe Base64-encoded as
described in FAQs and is empty by default.

StringNo

HtmlFillStyle

Watermark RGBA (color and transparency), which must be
URL-safe Base64-encoded as described in FAQs and isrgba(192,192,192,0.6) by default.

StringNo

StringNo

HtmlFront

Watermark text style, which must be URL-safe Base64encoded as described in FAQs and is bold 20px Serifby default.

HtmlRotate

Rotation angle of the watermark text in degrees. Value range:
0–360. Default value: 315 .

StringNo

HtmlHorizontal

Horizontal spacing of the watermark text in px. Default value:
50 .

StringNo

HtmlVertical

Vertical spacing of the watermark text in px. Default value:
100 .

StringNo©2013-2022 Tencent Cloud. All rights reserved.

Page 1749 of 1869

Cloud Infinite

Querying File Preview Feature Status：

Last updated 2024-03-01 14:57:12

Overview
This document provides an overview of APIs and SDK code samples for querying the file preview feature status.
API

Description

Querying file preview feature status

Queries whether the file preview feature is enabled for a bucket.

Querying File Preview Feature Status
Feature description
This API ( ci_get_doc_bucket ) is used to query whether the file preview feature is enabled for a bucket.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1750 of 1869

Cloud Infinite

def ci_get_doc_bucket(self, Regions='', BucketName='', BucketNames='', PageNumber='

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1751 of 1869

Cloud Infinite

def ci_get_doc_bucket():# Query the file preview feature status
response = client.ci_get_doc_bucket(
Regions=region,# BucketName='demo',
BucketNames=bucket_name,PageSize=1,
PageNumber=1)
print(response)
return response©2013-2022 Tencent Cloud. All rights reserved.

Page 1752 of 1869

Cloud Infinite

Parameter description
Parameter

Description

Type

Region information, such as ap-shanghai and ap-beijing . To
Regions

BucketNames

specify multiple regions, separate them by comma. For more information, see
Regions and Domain Names.
Bucket name. Separate multiple bucket names by comma. Exact search is
supported.

stringstringBucketName

Bucket name prefix. Prefix search is supported.

stringPageNumber

Page number.

int

pageSize

Number of entries per page.

int

Response description©2013-2022 Tencent Cloud. All rights reserved.

Page 1753 of 1869

Cloud Infinite{'TotalCount': '1',
'RequestId': 'NjMyMWE2ZjZfZWM0YTYyNjRxxxxxxxxxxxx','PageNumber': '1', 'PageSize': '1',
'DocBucketList': [{'Name': 'testpic-125xxxxxxx','CreateTime': '2022-08-11T00:00:00+0800','Region': 'ap-chongqing','AliasBucketId': None,'BucketId': 'test-125xxxxxxxx'}]©2013-2022 Tencent Cloud. All rights reserved.

Page 1754 of 1869

Cloud Infinite}
Parameter

Description

Type

RequestId

Unique ID of the request.

stringTotalCount

Total number of buckets with file preview enabled.

int

PageNumber

Current page number, which is the same as pageNumber in the request.

int

PageSize

Number of entries per page, which is the same as pageSize in therequest.

int

DocBucketList

List of buckets with file preview enabled.

Container

BucketId

Bucket ID.

stringName

Bucket name, which is the same as BucketId .

stringRegionRegion.

stringCreateTime

Creation time.

stringAliasBucketId

Bucket alias.

string©2013-2022 Tencent Cloud. All rights reserved.

Page 1755 of 1869

Cloud Infinite

Template APIs
Speech Recognition：

Last updated 2024-03-01 14:57:12

Overview
This document describes how to use CI's speech recognition template SDK.
API

Operation

Description

Creating automatic speech recognition template

Creates a template

Creating a template

Deleting automatic speech recognition template

Deletes a template

Deleting a template

DescribeTemplates

Queries templates

Querying the list of templates.

Updating automatic speech recognition template

Modifies a template

Modifying a template

Basic Operations
Creating template
Feature description
This API is used to create a template.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1756 of 1869

Cloud Infinite

def ci_create_asr_template(self, Bucket, Name, EngineModelType, ChannelNum,
ResTextFormat, FilterDirty=0, FilterModal=0, ConvertNumM
SpeakerNumber=0, FilterPunc=0, OutputFileType='txt', **kParameter description
Request has the following sub-nodes:

Request has the following sub-nodes:©2013-2022 Tencent Cloud. All rights reserved.

Page 1757 of 1869

Cloud Infinite

Node Name(Keyword)

Description

Type

Required

BucketBucket name

StringYes

Name

Template name, which can contain letters, digits, underscores(_), hyphens (-), and asterisks (*).

StringYes

String

Yes

int

No

int

Yes

int

No

Engine model type, divided into phone call and non-phone callscenarios.
Phone call scenarios:
8k_zh: 8 kHz, for Mandarin in general scenarios (available fordual-channel audio).
8k_zh_s: 8 kHz, for Mandarin with speaker separation(available for mono-channel audio only).
8k_en: 8 kHz, for English.
EngineModelType

Non-phone call scenarios:
16k_zh: 16 kHz, for Mandarin in general scenarios.
16k_zh_video: 16 kHz, for audio/video scenarios.
16k_en: 16 kHz, for English.
16k_ca: 16 kHz, for Cantonese.
16k_ja: 16 kHz, for Japanese.
16k_zh_edu: For Mandarin in education scenarios.
16k_en_edu: For English in education scenarios.
16k_zh_medical: For healthcare scenarios.
16k_th: For Thai.
16k_zh_dialect: Multi-dialect, for up to 23 dialects.
Number of sound channels:

ChannelNum

ResTextFormat

1: Mono. If EngineModelType is not the phone call scenario,
only mono channel is supported.
2: Dual (for the 8k_zh engine only, where the two channels
correspond to the caller and callee respectively).
Format of the returned recognition result.
0: Recognition result text, including the list of segment
timestamps.
1: Detailed word-level recognition result, excluding punctuation
marks but including the speech speed value (the list of wordtimestamps, generally used to generate subtitles).
2: Detailed word-level recognition result, including punctuation
marks and the speech speed value.

FilterDirty

Whether to filter restricted words (for the Mandarin engine
only).
0: Does not filter.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1758 of 1869

Cloud Infinite

1: Filters.
2: Replaces restricted words with *.
Default value: 0.

FilterModal

Whether to filter modal particles (for the Mandarin engine
only).
0: Does not filter.
1: Filters partially.
2: Filters strictly.

int

No

int

No

int

No

int

No

int

No

String

No

Default value: 0.
Whether to intelligently convert Chinese numbers to Arabic

ConvertNumMode

SpeakerDiarization

numerals (for the Mandarin engine only):
0: Directly outputs Chinese numbers.
1: Intelligently converts based on the scenario.
3: Enables mathematic number conversion.
Default value: 0.
Whether to enable speaker separation:
0: No.
1: Yes (for mono-channel audios with the 8k_zh, 16k_zh, or
16k_zh_video engine only).
Default value: 0.
Note: In the 8 kHz phone call scenario, we recommend you
use dual channels to distinguish between the caller and callee
by setting ChannelNum=2, so you don't need to enablespeaker separation.

SpeakerNumber

FilterPunc

Number of speakers to be separated (with speaker separation
enabled). Value range: 0–10.
0: Automatic separation (currently only for six or fewer people
only). 1–10: Specified number of speakers to be separated.
Default value: 0.
Whether to filter punctuation marks (currently for the Mandarin
engine only):
0: Does not filter.
1: Filters the punctuation mark at the end of the sentence.
2: Filters all punctuation marks.
Default value: 0.

OutputFileType

Output file type. Valid values: txt (default), srt.

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1759 of 1869

Cloud Infinite

def ci_create_asr_template():# Create a speech recognition template
response = client.ci_create_asr_template(
Bucket=bucket_name,
Name='templateName',EngineModelType='16k_zh',
ChannelNum=1,
ResTextFormat=2,)
print(response)
return response©2013-2022 Tencent Cloud. All rights reserved.

Page 1760 of 1869

Cloud Infinite

Response description{'RequestId': 'NjMyMjliMWZfZWM0YTYyNjRfNWNmNF8xMDBh','Template': {'TemplateId': 't1c1287c04c147443da0b2cc7b8fbabf32','Name': 'templateName','State': 'Normal','Tag': 'SpeechRecognition','CreateTime': '2022-09-15T11:25:19+0800',©2013-2022 Tencent Cloud. All rights reserved.

Page 1761 of 1869

Cloud Infinite'UpdateTime': '2022-09-15T11:25:19+0800','BucketId': 'testpic-1253960454','Category': 'Custom','SpeechRecognition': {'EngineModelType': '16k_zh','ChannelNum': '1',
'ResTextFormat': '2','FilterDirty': '0','FilterModal': '0',
'ConvertNumMode': '0',
'SpeakerDiarization': '0',
'SpeakerNumber': '0','FilterPunc': '0',
'OutputFileType': 'txt'}}}
For more information on response fields, see the response in Creating Speech Recognition Template.

Deleting template
Feature description
This API is used to delete a template.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1762 of 1869

Cloud Infinite

def ci_delete_asr_template(self, Bucket, TemplateId, **kwargs)

Parameter description
Parameter
BucketTemplateId

Description
Bucket name in the format of BucketName-APPID . For more
information, see Bucket Overview.
ID of the template to be canceled©2013-2022 Tencent Cloud. All rights reserved.

Type

Required

StringYes

StringYes

Page 1763 of 1869

Cloud Infinite

Sample request

def ci_delete_asr_template():# Delete the specified speech recognition template
response = client.ci_delete_asr_template(
Bucket=bucket_name,TemplateId='t1bdxxxxxxxxxxxxxxxxx94a9',)
print(response)
return response©2013-2022 Tencent Cloud. All rights reserved.

Page 1764 of 1869

Cloud Infinite

Response description{'RequestId': 'NjMyMjlkZmRfZWM0YTYyNjRfNWNmNF8xMDBi','TemplateId': 't1c1287c04c147443da0b2cc7b8fbabf32'}
For more information on response fields, see the response in DeleteTemplate.

Querying template list

©2013-2022 Tencent Cloud. All rights reserved.

Page 1765 of 1869

Cloud Infinite

Feature description
This API is used to query the template list.
Method prototype

def ci_get_asr_template(self, Bucket, Category='Custom', Ids='', Name='', PageNumbe

Parameter description
Parameter

Description©2013-2022 Tencent Cloud. All rights reserved.

Type

RequiredPage 1766 of 1869

Cloud Infinite

BucketBucket name in the format of BucketName-APPID . For more

StringYes

StringNo

information, see Bucket Overview.
Category

Template category: Custom or Official . Default value:
Custom .

Ids

Template ID. If you enter multiple IDs, separate them by comma.

StringNo

Name

Template name prefix

StringNo

PageNumber

Page number

Integer

No

PageSize

Number of entries per page

IntegerNo

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1767 of 1869

Cloud Infinite

def ci_get_asr_template():# Get the information of speech recognition templates
response = client.ci_get_asr_template(
Bucket=bucket_name,)print(response)
return response

Response description©2013-2022 Tencent Cloud. All rights reserved.

Page 1768 of 1869

Cloud Infinite{'TotalCount': '1',
'RequestId': 'NjMyMjljNTlfMTIwNjUzMDlfMmUzYV8xMWNh','PageNumber': '1',
'PageSize': '10','TemplateList': [{'TemplateId': 't1c1287c04c147443da0b2cc7b8fbabf32','Name': 'templateName','State': 'Normal','Tag': 'SpeechRecognition',©2013-2022 Tencent Cloud. All rights reserved.

Page 1769 of 1869

Cloud Infinite'CreateTime': '2022-09-15T11:25:19+0800','UpdateTime': '2022-09-15T11:25:19+0800','BucketId': 'testpic-1253960454','Category': 'Custom','SpeechRecognition': {'EngineModelType': '16k_zh','ChannelNum': '1',
'ResTextFormat': '2','FilterDirty': '0','FilterModal': '0',
'ConvertNumMode': '0',
'SpeakerDiarization': '0',
'SpeakerNumber': '0','FilterPunc': '0',
'OutputFileType': 'txt'}}]}
For more information on response fields, see the response in DescribeTemplates.

Modifying template
Feature description
This API is used to modify a template.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1770 of 1869

Cloud Infinite

def ci_update_asr_template(self, Bucket, TemplateId, Name, EngineModelType, Channel
ResTextFormat, FilterDirty=0, FilterModal=0, ConvertNumM
SpeakerNumber=0, FilterPunc=0, OutputFileType='txt', **kParameter description
Node Name(Keyword)

Description

Type

RequiredbucketName

Bucket name in the format of BucketName-APPID . For more

StringYes©2013-2022 Tencent Cloud. All rights reserved.

Page 1771 of 1869

Cloud Infinite

information, see Bucket Overview.
templateId

ID of the template to be modified

StringYes

Note:
Other parameters are the same as those of the template creation API as described in Creating Speech Recognition
Template.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1772 of 1869

Cloud Infinite

def ci_update_asr_template():# Modify a speech recognition template
response = client.ci_update_asr_template(
Bucket=bucket_name,TemplateId='t1bdxxxxxxxxxxxxxxxxx94a9',
Name='QueueId1',
EngineModelType='16k_zh',
ChannelNum=1,
ResTextFormat=1,)
print(response)
return response

Response description©2013-2022 Tencent Cloud. All rights reserved.

Page 1773 of 1869

Cloud Infinite{'RequestId': 'NjMyMjlkNzhfMTIwNjUzMDlfMmUxZF8xMGM4','Template': {'TemplateId': 't1c1287c04c147443da0b2cc7b8fbabf32','Name': 'QueueId1','State': 'Normal','Tag': 'SpeechRecognition','CreateTime': '2022-09-15T11:25:19+0800','UpdateTime': '2022-09-15T11:35:20+0800','BucketId': 'testpic-1253960454','Category': 'Custom',©2013-2022 Tencent Cloud. All rights reserved.

Page 1774 of 1869

Cloud Infinite'SpeechRecognition': {'EngineModelType': '16k_zh','ChannelNum': '1',
'ResTextFormat': '1',
'FilterDirty': '0','FilterModal': '0',
'ConvertNumMode': '0',
'SpeakerDiarization': '0',
'SpeakerNumber': '0','FilterPunc': '0',
'OutputFileType': 'txt'}}}
For more information on response fields, see the response in Updating Speech Recognition Template.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1775 of 1869

Cloud Infinite

File Processing
File Decompression
Querying File Decompression Result：

Last updated 2024-03-01 14:57:12

Overview
This document provides an overview of APIs and SDK code samples for querying the file decompression result.
API

Description

Querying the file decompression result

Queries the file decompression result asynchronously.

Async Request API
Feature description
This API is used to query the file decompression result asynchronously.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1776 of 1869

Cloud Infinite

def ci_get_file_process_jobs(self, Bucket, JobIDs, **kwargs)

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1777 of 1869

Cloud Infinite

def ci_get_file_process_jobs():
response = client.ci_get_file_process_jobs(
Bucket=bucket_name,
JobIDs='fcb9a9f90e57611ed9************',)
print(response)
return response

Parameter description©2013-2022 Tencent Cloud. All rights reserved.

Page 1778 of 1869

Cloud Infinite

Parameter

Description

Type

BucketBucket of the object

String

JobIDsJob ID. To specify multiple job IDs, separate them withcommas (,).

StringResponse description{"Response": {©2013-2022 Tencent Cloud. All rights reserved.

Page 1779 of 1869

Cloud Infinite"JobsDetail": {"Code": "Success","Message": "","JobId": "f93984788066911ed89ed352d4d9d2084","State": "Submitted","CreationTime": "2022-07-18T15:4:43 PM+0800","EndTime": "-","StartTime": "-",
"QueueId": "p2911917386e148639319e13c285cc774","Tag": "FileUncompress","Input": {"BucketId": "test-1234567890","Object": "input/test.zip","Region": "ap-chongqing"},"Operation": {"FileUncompressConfig": {"Prefix": "output/","PrefixReplaced": 1},"Output": {"Region": "ap-chongqing","Bucket": "test-1234567890"},"UserData": "This is my data."}}}}

Parameter

Description

Type

Response

Response details. For more information, see "Response" inQuerying File Decompression Result.

dict©2013-2022 Tencent Cloud. All rights reserved.

Page 1780 of 1869

Cloud Infinite

Submitting File Decompression Job：

Last updated 2024-03-01 14:57:12

Overview
This document provides an overview of APIs and SDK code samples for async file decompression requests.
API

Description

Submitting a file decompression job

Submits a file decompression job asynchronously.

Async Request API
Feature description
This API is used to submit an async file decompression request.
Method prototype©2013-2022 Tencent Cloud. All rights reserved.

Page 1781 of 1869

Cloud Infinite

def ci_create_file_uncompress_job(self, Bucket, InputObject,
FileUncompressConfig, QueueId=None, CallBack=None, CallBackFormat=None,
CallBackType=None, CallBackMqConfig=None, UserData=None, **kwargs)

Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1782 of 1869

Cloud Infinite

def ci_create_file_uncompress_job():
body = {'Prefix': 'output/',}
response = client.ci_create_file_uncompress_job(
Bucket=bucket_name,
InputObject='test.zip',
FileUncompressConfig=body)print(response)
return response©2013-2022 Tencent Cloud. All rights reserved.

Page 1783 of 1869

Cloud Infinite

Parameter description
Parameter

Description

Type

BucketBucket of the object

StringInputObject

Object name, such as folder/document.pdf

StringFileUncompressConfig

File decompression rule. For more information, see"FileUncompressConfig" in Submitting File Decompression Job.

dict

QueueId

ID of the queue where the job is in

StringCallBack

Job callback address, which takes priority over that of the queue. If it is
set to no , no callbacks will be generated at the callback address ofstringthe queue.
CallBackFormat

CallBackType

CallBackMqConfig

Job callback format, which can be JSON or XML (default). It takes
priority over that of the queue.
Job callback type, which can be Url (default) or TDMQ . It takes
priority over that of the queue.
TDMQ configuration for job callback. This parameter is required if
CallBackType is TDMQ . For more information, see

stringstringdict"CallBackMqConfig" in Structure.
UserData

The user information passed through, which is printable ASCII codesof up to 1,024 in length.

StringResponse description©2013-2022 Tencent Cloud. All rights reserved.

Page 1784 of 1869

Cloud Infinite{"Response": {"JobsDetail": {"Code": "Success","Message": "","JobId": "f93984788066911ed89ed352d4d9d2084","State": "Submitted","CreationTime": "2022-07-18T15:4:43 PM+0800","EndTime": "-","StartTime": "-",
"QueueId": "p2911917386e148639319e13c285cc774",©2013-2022 Tencent Cloud. All rights reserved.

Page 1785 of 1869

Cloud Infinite"Tag": "FileUncompress","Input": {"BucketId": "test-1234567890","Object": "input/test.zip","Region": "ap-chongqing"},"Operation": {"FileUncompressConfig": {"Prefix": "output/","PrefixReplaced": 1},"Output": {"Region": "ap-chongqing","Bucket": "test-1234567890"},"UserData": "This is my data."}}}}
Parameter

Description

Type

Response

Response details. For more information, see "Response" inSubmitting File Decompression Job.

dict©2013-2022 Tencent Cloud. All rights reserved.

Page 1786 of 1869

Cloud Infinite

Mini Program SDK
Getting Started：

Last updated 2024-03-01 15:15:09

Download and Installation
Relevant resources
Download COS XML SDK source code for Weixin Mini Programs source code here XML SDK for Weixin Mini
Program.
Download the XML mini program SDK here.
Download the demo here XML SDK for Weixin Mini Program Demo.
For the complete sample code, see SDK Sample Code.
For the SDK changelog, see Changelog.
For SDK FAQs, see Mini Program SDK FAQs.
Note:
If you encounter errors such as non-existent functions or methods when using the SDK, you can update the SDK to
the latest version and try again.
Environmental dependencies
1. This SDK is only applicable to WeChat Mini Programs.
2. Log in to the COS console, create a bucket, and get the bucket name and region information.
3. Log in to the CAM console and get your project's SecretId and SecretKey .
Note:
For the definition of parameters such as SecretId , SecretKey , and Bucket , see COS’s Glossary.
If you are using cross platform framework such as uni-app, and encounter problems when packaging the app (such as
iOS or Android app), use the iOS SDK or Android SDK.
SDKs on versions earlier than v1.2.0 support the XCosSecurityToken field only. For later SDKs, use
SecurityToken instead.
Installing SDK
There are two ways to install the SDK for WeChat Mini Programs: manual installation and installation through npm as
detailed below.
Installing manually©2013-2022 Tencent Cloud. All rights reserved.

Page 1787 of 1869

Cloud Infinite

Copy the cos-wx-sdk-v5.js file in the source code directory to any path in the root directory of your WeChat Mini
Program code and reference it using a relative path:var COS = require('./lib/cos-wx-sdk-v5.js')

Installing through npm
If the code of your WeChat Mini Program is packaged using webpack, install the dependencies via npm:

©2013-2022 Tencent Cloud. All rights reserved.

Page 1788 of 1869

Cloud Infinite

npm install cos-wx-sdk-v5
Here, the program code is referenced by using var COS = require('cos-wx-sdk-v5'); . For more
information, see Support for npm.

Getting Started
Configuring domain name allowlist for Weixin Mini Programs©2013-2022 Tencent Cloud. All rights reserved.

Page 1789 of 1869

Cloud Infinite

To request COS in your WeChat Mini Program, you need to log in to the WeChat Official Accounts Platform andconfigure the domain name allowlist in Development > Development Settings > Server Domain Name. The SDK
uses the following two APIs:
1. For cos.postObject, use the wx.uploadFile API.
2. For other methods, use the wx.request API.
For both methods, you need to configure the COS domain name. There are two forms of domain name allowlists.
1. For standard requests, you can configure the bucket domain name as the allowed domain name, for example:
examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com
2. If multiple buckets are used in your WeChat Mini Program, you can choose to use suffixed COS requests bypassing in ForcePathStyle: true when instantiating the SDK. In this case, you need to configure the region
domain name as the allowed domain name, such as cos.ap-guangzhou.myqcloud.com .

Initialization©2013-2022 Tencent Cloud. All rights reserved.

Page 1790 of 1869

Cloud Infinite

var COS = require('./lib/cos-wx-sdk-v5.js')©2013-2022 Tencent Cloud. All rights reserved.

Page 1791 of 1869

Cloud Infinite

var cos = new COS({// ForcePathStyle: true, // If multiple buckets are used, you can use suffixed
SimpleUploadMethod: 'putObject', // We strongly recommend you use `putObject` w
getAuthorization: function (options, callback) {// It will not be called during initialization and will be entered only whe// Get a temporary key asynchronously.
wx.request({
url: 'https://example.com/server/sts.php',
data: {
bucket: options.Bucket,
region: options.Region,©2013-2022 Tencent Cloud. All rights reserved.

Page 1792 of 1869

Cloud Infinite},
dataType: 'json',
success: function (result) {var data = result.data;
var credentials = data && data.credentials;
if (!data || !credentials) return console.error('credentials invali
callback({
TmpSecretId: credentials.tmpSecretId,
TmpSecretKey: credentials.tmpSecretKey,// For SDKs on versions earlier than v1.2.0, use `XCosSecurityT
SecurityToken: credentials.sessionToken,// We recommend that you use the server time as the signature sStartTime: data.startTime, // Timestamp in seconds, such as 158
ExpiredTime: data.expiredTime, // Timestamp in seconds, such as
});
}
});
}
});
// The COS instance can then be used to call a COS request.
// TODO

Configuration item
Sample code
Create a COS SDK instance in the following methods:
Method 1 (recommended): The backend gets a temporary key and sends it to the frontend for signature calculation.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1793 of 1869

Cloud Infinite

var cos = new COS({
SimpleUploadMethod: 'putObject', // We strongly recommend you use `putObject` w// Required parameter
getAuthorization: function (options, callback) {// Server examples for JS and PHP: https://github.com/tencentyun/cos-js-sdk// For server-side examples for other programming languages, see the COS SD// For the STS documentation, visit https://www.tencentcloud.com/document/p
wx.request({
url: 'https://example.com/server/sts.php',
data: {// The required parameters can be obtained from options.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1794 of 1869

Cloud Infinite},
success: function (result) {var data = result.data;
var credentials = data && data.credentials;
if (!data || !credentials) return console.error('credentials invali
callback({
TmpSecretId: credentials.tmpSecretId,
TmpSecretKey: credentials.tmpSecretKey,// For SDKs on versions earlier than v1.2.0, use `XCosSecurityT
SecurityToken: credentials.sessionToken,// We recommend that you use the server time as the signature sStartTime: data.startTime, // Timestamp in seconds, such as 158
ExpiredTime: data.expiredTime, // Timestamp in seconds, such as
});
}
});
}
});
Note:
For more information about how to generate and use a temporary key, see Generating and Using Temporary Keys.
Method 2 (recommended): Permissions are controlled in a more refined manner. The backend gets a temporary key
and sends it to the frontend. The frontend reuses the key only for the same request, and the backend can granularly
manage permissions through Scope.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1795 of 1869

Cloud Infinite

var cos = new COS({
SimpleUploadMethod: 'putObject', // We strongly recommend you use `putObject` w// Required parameter
getAuthorization: function (options, callback) {// Server example: https://github.com/tencentyun/qcloud-cos-sts-sdk/edit/ma
wx.request({
url: 'https://example.com/server/sts-scope.php',
data: JSON.stringify(options.Scope),
success: function (result) {var data = result.data;
var credentials = data && data.credentials;©2013-2022 Tencent Cloud. All rights reserved.

Page 1796 of 1869

Cloud Infinite

if (!data || !credentials) return console.error('credentials invali
callback({
TmpSecretId: credentials.tmpSecretId,
TmpSecretKey: credentials.tmpSecretKey,// For SDKs on versions earlier than v1.2.0, use `XCosSecurityT
SecurityToken: credentials.sessionToken,// We recommend that you use the server time as the signature sStartTime: data.startTime, // Timestamp in seconds, such as 158
ExpiredTime: data.expiredTime, // Timestamp in seconds, such as
ScopeLimit: true, // Refined permission control needs to be set
});
}
});
}
});
Note:
For more information about how to generate and use a temporary key, see Generating and Using Temporary Keys.
Method 3 (not recommended). The frontend needs to get a signature through getAuthorization before eachrequest, and the backend uses a fixed or temporary key to calculate the signature and returns it to the frontend. Thismethod makes it difficult to control permissions for multipart upload and thus is not recommended.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1797 of 1869

Cloud Infinite

var cos = new COS({
SimpleUploadMethod: 'putObject', // We strongly recommend you use `putObject` w// Required parameter
getAuthorization: function (options, callback) {// The server obtains a signature. For more information, see the COS SDK fo// Note: There may be a security risk associated with this method. The backwx.request({
url: 'https://example.com/server/auth.php',
data: JSON.stringify(options.Scope),
success: function (result) {var data = result.data;©2013-2022 Tencent Cloud. All rights reserved.

Page 1798 of 1869

Cloud Infinite

if (!data || !data.authorization) return console.error('authorizati
callback({
Authorization: data.authorization,// For SDKs on versions earlier than v1.2.0, use `XCosSecurityT// SecurityToken: data.sessionToken, // If a temporary key is u
});
}
});
},
});
Method 4 (not recommended): The frontend uses a permanent key to calculate the signature. This method can beused for frontend debugging. If you use this method, be sure to avoid key disclosure.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1799 of 1869

Cloud Infinite// Log in to https://console.tencentcloud.com/cam/capi to check and manage the Secrvar cos = new COS({
SecretId: 'SECRETID',
SecretKey: 'SECRETKEY',
SimpleUploadMethod: 'putObject', // We strongly recommend you use `putObject` w});

Constructor parameters
Parameter

Description©2013-2022 Tencent Cloud. All rights reserved.

Type

RequiredPage 1800 of 1869

Cloud Infinite

SecretId

User SecretId

StringNo

String

No

User's SecretKey , which we recommend to be
SecretKey

used only for frontend debugging and should not be
disclosed

FileParallelLimit

Number of concurrent file uploads in the same instance.
Default value: 3

NumberNo

ChunkParallelLimit

Number of concurrent part uploads for the same
uploaded file. Default value: 3

Number

No

Number

No

Number of retries upon multipart upload failure. Default
ChunkRetryTimesvalue: 2 (a request will be made 3 times in total,
including the initial one)

ChunkSize

Part size in the multipart upload in bytes. Default value:
1048576 (1 MB)

NumberNo

SliceSize

When files are uploaded in batches using uploadFiles,
if the file size is greater than the value of thisparameter, multipart upload (sliceUploadFile) is used;otherwise, simple upload (putObject) is used. Default
value: 1048576 (1 MB)

NumberNo

CopyChunkParallelLimit

Number of concurrent part uploads for the same
multipart copy operation. Default value: 20

Number

No

Number

No

Number

No

NumberNo

StringNo

CopyChunkSize

Number of bytes in each part during a multipart copy
operation with sliceCopyFile . Default value:
10485760 (10 MB)

CopySliceSize

When a file is copied using sliceCopyFile, if the file size
is greater than the value of this parameter, multipart
copy (sliceCopyFile) is used; otherwise, simple copy
(putObjectCopy) is used. Default value: 10485760(10 MB)

ProgressInterval

Callback frequency of the upload progress callback
method onProgress in milliseconds. Default value:
1000

ProtocolProtocol used when the request is made. Valid values:
https: , http: . By default, http: is used
when the current page is determined to be in http:format; otherwise, https: is used©2013-2022 Tencent Cloud. All rights reserved.

Page 1801 of 1869

Cloud Infinite

ServiceDomain

The request domain name when getService isStringNo

StringNo

UploadQueueSize

The maximum size of the upload queue. Excess tasks
will be cleared if their status is not waiting, checking, or
uploading. Default value: 10000

NumberNo

ForcePathStyle

Forces the use of a suffix when sending requests. The
suffixed bucket will be placed in the pathname after thedomain name, and the bucket will be added to thesignature pathname for calculation. Default value:
false

BooleanNo

UploadCheckContentMd5

Forces the verification of Content-MD5 for file uploads,
which calculates the MD5 checksum of the file request
body and places it in the Content-MD5 field of theheader. Default value: false

Boolean

No

FunctionNo

BooleanNo

StringNo

called, such as service.cos.myqcloud.com
The custom request domain name used to call a bucket
or object API. You can use a template, such as "Domain{Bucket}.cos.{Region}.myqcloud.com"
which will use the bucket and region passed in thereplacement parameters when an API is called.

Callback method for getting the signature. If there is no
SecretId or SecretKey , this parameter is
getAuthorization

required.
Note: This callback method is passed in during
instance initialization, and is only executed toobtain the signature when the instance calls APIs.
Whether to enable a global acceleration endpoint.
Default value: false . If you set the value to

UseAcceleratetrue , you need to enable global acceleration for the
bucket. For more information, see Enabling Global
Acceleration.
The name of the method for simply uploading small files

SimpleUploadMethod

during advanced upload and batch upload. Validvalues: postObject , putObject . Default
value: postObject . This parameter is supported
starting from v1.3.0.

getAuthorization Callback function description (Format 1)©2013-2022 Tencent Cloud. All rights reserved.

Page 1802 of 1869

Cloud Infinite

getAuthorization: function(options, callback) { ... }getAuthorization callback parameter descriptions:Parameter

Description

Type

options

Required for getting the signature

Object- Bucket

Bucket name in the format of BucketName-APPID . The bucket name entered
here must be in this format©2013-2022 Tencent Cloud. All rights reserved.

StringPage 1803 of 1869

Cloud Infinite- Region

Bucket region. For the enumerated values, see Regions and Access Endpoints.

Stringcallback

Callback method after the temporary key is obtained

Function

After the temporary key is obtained, the callback returns an object. The attributes of the returned object are as listed
below:
Attribute

Description

Type

Required

TmpSecretId

tmpSecretId of the obtained temporary key

StringYes

TmpSecretKey

tmpSecretKey of the obtained temporary key

StringYes

StringYes

StringNo

StringYessessionToken of the obtained temporary key, which
SecurityToken

corresponds to the x-cos-security-token field in theheader. Use XCosSecurityToken instead of
SecurityToken for SDKs on versions earlier than v1.2.0.

StartTime

ExpiredTime

The timestamp in seconds of when you obtained the key, such as
1580000000 . Passing in this parameter as the signature start
time can avoid signature expiration issues due to time deviation on
the frontend.
expiredTime of the obtained temporary key measured inseconds, i.e., the timeout timestamp, such as 1580000900

getAuthorization Callback function description (Format 2)©2013-2022 Tencent Cloud. All rights reserved.

Page 1804 of 1869

Cloud Infinite

getAuthorization: function(options, callback) { ... }getAuthorization function callback parameter descriptions:Parameter

Description

Type

options

Parameter object for getting the signature

Object- Method

Method of the current request

Object- PathnameRequest path used for signature calculation

String©2013-2022 Tencent Cloud. All rights reserved.

Page 1805 of 1869

Cloud Infinite- Key

An object key (object name), the unique identifier of an object in a bucket.
For more information, see Object Overview.
Note: This parameter is empty if the API that uses the instance is
not an object-operation API.

String- Query

Query parameter in the current request. Format: {key: 'val'}

Object- Headers

Headers in the current request. Format: {key: 'val'}

Objectcallback

Callback after the temporary key is obtained

FunctionOnce the getAuthorization callback function is finished, it returns one of the following:
An Authorization string.
An object whose attributes are listed as follows:
Attribute

Description

Type

Required

Authorization

Calculated signature string

StringYes

StringNosessionToken of the obtained temporary key, which
SecurityToken

corresponds to the x-cos-security-token field in theheader. Use XCosSecurityToken instead of
SecurityToken for SDKs on versions earlier than v1.2.0.

Getting an authentication credential
There are three ways to get the authentication credentials for your instance by passing in different parameters during
instantiation:
1. During instantiation, pass in your SecretId and SecretKey . Each time a signature is required, it will beinternally calculated by the instance.
2. During instantiation, pass in the getAuthorization callback function. Each time a signature is required, it will
be calculated and returned to the instance through this callback.
3. During instantiation, pass in the getSTS callback. Each time a temporary key is required, it will be returned tothe instance for signature calculation within the instance during each request.

Enabling DataInsight
We have introduced the Tencent Beacon into the SDK to track down and optimize the SDK quality for a better user
experience.
Note:
DataInsight only monitors the COS request performance and doesn't report any business data.
To enable this feature, make sure that the SDK version is 1.4.0 or later and specify EnableTracker as true
during initialization.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1806 of 1869

Cloud Infinite

Then, add the following to the valid request domain name allowlist of the mini program:
https://h.trace.qq.com;https://oth.str.beacon.qq.com;https://otheve.beacon.qq.com; .

new COS({
EnableTracker: true,})

How to use
Callback method©2013-2022 Tencent Cloud. All rights reserved.

Page 1807 of 1869

Cloud Infinite

The callback method is used by default in the documentation. Below is the sample code:// The initialization process and upload parameters are omitted here.
var cos = new COS({ ... });cos.uploadFile({ ... }, function(err, data) {if (err) {console.log('Upload failed', err);} else {console.log('Uploaded successfully', data);}});©2013-2022 Tencent Cloud. All rights reserved.

Page 1808 of 1869

Cloud Infinite

PromiseThe SDK also supports calling through the promise method. For example, the code of the callback method above isequivalent to the following code:// The initialization process and upload parameters are omitted here.
var cos = new COS({ ... });cos.uploadFile({ ... }).then(data => {console.log('Uploaded successfully', data);}).catch(err => {console.log('Upload failed', err);});©2013-2022 Tencent Cloud. All rights reserved.

Page 1809 of 1869

Cloud Infinite

Sync method
The sync method is based on JavaScript's async and await. The code of the callback method above is equivalent to
the following code:

async function upload() {// The initialization process and upload parameters are omitted here.
var cos = new COS({ ... });try {var data = await cos.uploadFile({ ... });©2013-2022 Tencent Cloud. All rights reserved.

Page 1810 of 1869

Cloud Infinite

return { err: null, data: data }} catch (err) {return { err: err, data: null };}}// The returned value of the request can be obtained synchronously. Here is only an
var uploadResult = await upload();if (uploadResult.err) {console.log('Upload failed', uploadResult.err);} else {console.log('Uploaded successfully', uploadResult.data);}
Note:cos.getObjectUrl currently only supports the callback method.

Tips
In most cases, you only need to create a COS SDK instance, and use it directly where SDK methods need to becalled.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1811 of 1869

Cloud Infinite

var cos = new COS({....
});/* Self-encapsulated upload method */function myUpload() {// COS SDK instances do not need to be created in each method// var cos = new COS({//...
// });
cos.putObject({©2013-2022 Tencent Cloud. All rights reserved.

Page 1812 of 1869

Cloud Infinite

....
});
}
/* Self-encapsulated deletion method */function myDelete() {// COS SDK instances do not need to be created in each method// var cos = new COS({//...
// });
cos.deleteObject({
....
});
}
Below are some examples of common APIs. For more detailed initialization methods, see the examples in the demo.

Creating a bucket©2013-2022 Tencent Cloud. All rights reserved.

Page 1813 of 1869

Cloud Infinite

cos.putBucket({
Bucket: 'examplebucket-1250000000',
Region: 'ap-beijing',}, function (err, data) {console.log(err || data);
});
Note:
If you need to create a bucket via the Weixin Mini Program, but the bucket name is unknown, you cannot configure
the bucket name as an allowed domain name. Instead, you can use suffixed calls. For more information, see FAQs.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1814 of 1869

Cloud Infinite

Querying the bucket list

cos.getService(function (err, data) {console.log(data && data.Buckets);});

Uploading an object
We strongly recommend you use the advanced upload API uploadFile , which automatically uses simple upload
for small files and multipart upload for large files for a better performance. For more information, see Uploading Object.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1815 of 1869

Cloud Infinite

If you use the temporary key method, you need to grant the permissions of both simple upload and multipart upload as
instructed in Working with COS API Authorization Policies.
For SDK FAQs, see FAQs.

/* Initialize COS */var cos = new COS({// getAuthorization: funciton() {}, // See above for initialization.
SimpleUploadMethod: 'putObject', // We strongly recommend you use `putObject` whe});
function handleFileInUploading(fileName, filePath) {©2013-2022 Tencent Cloud. All rights reserved.

Page 1816 of 1869

Cloud Infinite

cos.uploadFile({
Bucket: 'examplebucket-1250000000', /* Your bucket name. Required. */Region: 'COS_REGION',/* Bucket region. Required */Key: fileName,/* Object key stored in the bucket (required), su
FilePath: filePath, /* Path of the file to be uploaded (required) */SliceSize: 1024 * 1024 * 5,/* Threshold (5 MB in this example) to trigge
onProgress: function(progressData) {console.log(JSON.stringify(progressData));}}, function(err, data) {if (err) {console.log('Upload failed', err);} else {console.log('Uploaded successfully');}});}/* Select a file to get the temporary path (with an image as an example here). For
wx.chooseImage({count: 1, // Default value: `9`
sizeType: ['original'], // You can specify whether to use the original or comprsourceType: ['album', 'camera'], // You can specify whether the source is an al
success: function (res) {var filePath = res.tempFiles[0].path;var fileName = filePath.substr(filePath.lastIndexOf('/') + 1);
handleFileInUploading(fileName, filePath);}});

Querying objects©2013-2022 Tencent Cloud. All rights reserved.

Page 1817 of 1869

Cloud Infinite

cos.getBucket({
Bucket: 'examplebucket-1250000000',
Region: 'ap-beijing',
Prefix: 'exampledir/', // Pass in the file prefixes to be listed here}, function (err, data) {console.log(err || data.Contents);});

Downloading an object©2013-2022 Tencent Cloud. All rights reserved.

Page 1818 of 1869

Cloud Infinite

Note:
This API is used to read object content. To download a file using your browser, you should first get a download URL
through the cos.getObjectUrl method. For more information, see Pre-signed URLs.

cos.getObject({
Bucket: 'examplebucket-1250000000',
Region: 'ap-beijing',
Key: 'exampleobject.txt',}, function (err, data) {console.log(err || data.Body);});©2013-2022 Tencent Cloud. All rights reserved.

Page 1819 of 1869

Cloud Infinite

Deleting an object

cos.deleteObject({
Bucket: 'examplebucket-1250000000',
Region: 'ap-beijing',
Key: 'picture.jpg',}, function (err, data) {console.log(err || data);});©2013-2022 Tencent Cloud. All rights reserved.

Page 1820 of 1869

Cloud Infinite©2013-2022 Tencent Cloud. All rights reserved.

Page 1821 of 1869

Cloud Infinite

Image Processing
Basic Image Processing：

Last updated 2024-03-01 15:15:09

Overview
This document provides an overview of APIs and SDK code samples for basic image processing.
Service

Basic image
processing

FeatureDescription

Scaling

Proportional scaling, scaling image to target width and height

Cropping

Regular cropping, cropping and scaling, cropping to circle,
smart face cropping

Rotation

Adaptive rotation, regular rotation

Format conversion

Format conversion, GIF format optimization, progressive
display

Quality change

Quality change for JPG and WebP images

Gaussian blurring

Image blurring

Sharpening

Image sharpening

Watermarking

Image watermark, text watermark

Image informationacquisition

Basic information, EXIF information, average hue

Metadata removal

Including EXIF information

Quick thumbnail
template

Quick image format conversion, scaling, and cropping for
thumbnail generation

Processing Image During Upload
The following example shows how to automatically process an image when you upload it to COS.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1822 of 1869

Cloud Infinite

When the image is uploaded successfully, COS will save both the original and the processed images. You can later
obtain the processing results by using a general download request.

Sample code<view><button type="primary" bindtap="button">Process an image during upload</button></view>©2013-2022 Tencent Cloud. All rights reserved.

Page 1823 of 1869

Cloud Infinite

Page({
button: function () {wx.chooseMessageFile({
count: 10,
type: 'all',success: function (res) {var file = res.tempFiles[0];wxfs.readFile({
filePath: file.path,
success: function (res) {cos.putObject(©2013-2022 Tencent Cloud. All rights reserved.

Page 1824 of 1869

Cloud Infinite{
Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION',
Key: file.name,Body: res.data,
Headers: {// Use the `imageMogr2` API to scale the image (by specifying the'Pic-Operations':'{"is_pic_info": 1, "rules": [{"fileid": "desample_photo.jpg",},},(err, data) => {console.log(err || data);},);},
fail: (err) => console.error(err),});},
fail: (err) => console.error(err),
});
},
});

Processing In-Cloud Image
The following example shows how to process an image stored in COS and save the processing result to COS.

Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1825 of 1869

Cloud Infinite<view><button type="primary" bindtap="button">Process an in-cloud image</button></view>©2013-2022 Tencent Cloud. All rights reserved.

Page 1826 of 1869

Cloud Infinite

Page({
button: function () {cos.request({
Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION',
Key: 'exampleImage',
Method: 'POST',
Action: 'image_process',
Headers: {// Use the `imageMogr2` API to scale the image (by specifying the width o©2013-2022 Tencent Cloud. All rights reserved.

Page 1827 of 1869

Cloud Infinite'Pic-Operations':'{"is_pic_info": 1, "rules": [{"fileid": "desample_photo.jpg", "rule":},},(err, data) => {console.log(err || data);
},
);
},
});

Processing Image During Download
The following example shows how to process an image during download.

Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1828 of 1869

Cloud Infinite<view><button type="primary" bindtap="button">Process an image during download</button></view>©2013-2022 Tencent Cloud. All rights reserved.

Page 1829 of 1869

Cloud Infinite

Page({
button: function () {cos.getObject({
Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION',
Key: 'exampleImage',
QueryString: `imageMogr2/thumbnail/200x/`,},(err, data) => {console.log(err || data);©2013-2022 Tencent Cloud. All rights reserved.

Page 1830 of 1869

Cloud Infinite

},
);
},
});

Generating Signed URL with Image Processing Parameters
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1831 of 1869

Cloud Infinite<view><button type="primary" bindtap="sign">Generate a signed URL with image processing<button type="primary" bindtap="unsign">Generate an unsigned URL with image proce</view>

Page({
sign: function () {// Generate a signed URL (valid for 30 minutes) with image processing parametercos.getObjectUrl({©2013-2022 Tencent Cloud. All rights reserved.

Page 1832 of 1869

Cloud Infinite

Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION',
Key: 'exampleobject',
Query: {`imageMogr2/thumbnail/200x/`: ''},Expires: 1800,
Sign: true,},(err, data) => {if (data) {console.log(data.URL);
}
},
);
},
unsign: function () {// Generate an unsigned URL with image processing parameters.
cos.getObjectUrl({
Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION',
Key: 'exampleobject',
Query: {`imageMogr2/thumbnail/200x/`: ''},Sign: false,},(err, data) => {if (data) {console.log(data.URL);
}
},
);
},
});

©2013-2022 Tencent Cloud. All rights reserved.

Page 1833 of 1869

Cloud Infinite

Blind Watermark：

Last updated 2024-03-01 15:15:09

Overview
This document provides an overview of APIs and SDK code samples for blind watermarking.
For blind watermark APIs, see Blind Watermark.

Adding Blind Watermark
Feature description
You can add a blind watermark when uploading or downloading an object.
Sample 1: Adding a blind watermark during upload©2013-2022 Tencent Cloud. All rights reserved.

Page 1834 of 1869

Cloud Infinite<view><button type="primary" bindtap="button">Add a blind watermark during upload</butt</view>©2013-2022 Tencent Cloud. All rights reserved.

Page 1835 of 1869

Cloud Infinite

Page({
button: function () {wx.chooseMessageFile({
count: 10,
type: 'all',success: function (res) {var file = res.tempFiles[0];wxfs.readFile({
filePath: file.path,
success: function (res) {cos.putObject(©2013-2022 Tencent Cloud. All rights reserved.

Page 1836 of 1869

Cloud Infinite{
Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION',
Key: file.name,Body: res.data,
Headers: {// CI's persistent processing API during upload'Pic-Operations': '{"is_pic_info": 1, "rules": [{"fileid": "desam},},(err, data) => {console.log(err || data);},);},
fail: (err) => console.error(err),});},
fail: (err) => console.error(err),
});
},
});

Sample 2: Adding a blind watermark during download©2013-2022 Tencent Cloud. All rights reserved.

Page 1837 of 1869

Cloud Infinite<view><button type="primary" bindtap="button">Add a blind watermark during download</bu</view>©2013-2022 Tencent Cloud. All rights reserved.

Page 1838 of 1869

Cloud Infinite

Page({
button: function () {cos.getObject({
Bucket: 'examplebucket-1250000000',
Region: 'COS_REGION',
Key: 'exampleImage',
QueryString: `watermark/3/type/1/image/aHR0cDovL2V4YW1wbGVzLTEyNTEwMDAwMDQu},(err, data) => {console.log(err || data);©2013-2022 Tencent Cloud. All rights reserved.

Page 1839 of 1869

Cloud Infinite

},
);
},
});

©2013-2022 Tencent Cloud. All rights reserved.

Page 1840 of 1869

Cloud Infinite

Media Processing
Media Bucket APIs：

Last updated 2024-03-01 15:15:09

Overview
This document provides an overview of APIs and SDK code samples for media buckets.
API

Operation

Description

DescribeMediaBuckets

Querying media processing activation
statusQueries buckets with media processing
enabledQuerying Media Processing Activation Status
Feature description
This API is used to query buckets with media processing enabled.
Note:
The COS Mini Program SDK version must be at least v1.1.1.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1841 of 1869

Cloud Infinite

var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket (required) */Region: 'COS_REGION', /* Bucket region (required) */};var host = 'ci.' + config.Region + '.myqcloud.com';
var url = 'https://' + host + '/mediabucket';cos.request({
Bucket: config.Bucket,
Region: config.Region,
Method: 'GET',©2013-2022 Tencent Cloud. All rights reserved.

Page 1842 of 1869

Cloud Infinite

Key: 'mediabucket', /** Fixed value (required) */Url: url,
Query: {pageNumber: '1', /** Page number (optional) */pageSize: '10', /** Number of entries per page (optional) */// regions: 'ap-chengdu', /** Region (optional), such as 'ap-beijing'. To s// bucketNames: 'test-1250000000', /** Bucket name (optional), such as 'tes// bucketName: 'test', /** Bucket name prefix for prefix search (optional),}}, function (err, data) {console.log(err || data);});

Parameter description
Parameter

Description

Type

Required

BucketBucket name in the format of BucketName-APPID .

StringYes

RegionBucket region. For the enumerated values, see Regions and AccessEndpoints.

StringYes

Key

Fixed value: mediabucket.

StringYes

PageNumber

Page number.

StringNo

PageSize

Number of entries per page.

StringNo

String

No

Region information, such as ap-shanghai and ap-beijing .
Regions

To specify multiple regions, separate them with commas. For more
information, see Regions and Domain Names.

BucketNames

Bucket name. To specify multiple bucket names, separate them withcommas. Exact search is supported.

StringNo

BucketName

Bucket name prefix for prefix search.

StringNo

Callback function description©2013-2022 Tencent Cloud. All rights reserved.

Page 1843 of 1869

Cloud Infinite

function(err, data) { ... }Parameter

Description

Type

The object returned when an error (network error or service error) occurs. If theerrrequest is successful, this parameter is empty. For more information, see Error
Codes.

Object- statusCode

Returned HTTP status code, such as 200 , 403 , and 404 .

Number- headers

Returned headers.

Object©2013-2022 Tencent Cloud. All rights reserved.

Page 1844 of 1869

Cloud Infinitedata

The object returned when the request is successful. If an error occurs with therequest, this parameter is empty.

Object- statusCode

Returned HTTP status code, such as 200 , 403 , and 404 .

Number- headers

Returned headers.

Object- Response

Response result.

Object- - RequestId

Unique ID of the request.

String- - TotalCount

Total number of media buckets.

String- - PageNumber

Current page number, which is the same as pageNumber in the request.

String- - PageSize

Number of entries per page, which is the same as pageSize in the request.

String-MediaBucketList

Media bucket list.

Object- - - BucketId

Bucket ID.

String- - - Name

Bucket name, which is the same as BucketId .

String- - - Region

Region.

String- - - CreateTime

Creation time.

String©2013-2022 Tencent Cloud. All rights reserved.

Page 1845 of 1869

Cloud Infinite

Media Information APIs：

Last updated 2024-03-01 15:15:09

Overview
This document provides an overview of APIs and SDK code samples for media information.
Note:
The COS Mini Program SDK version must be at least v1.1.1.
API

Operation

Description

GetMediaInfo

Querying file information

Queries media file information

Querying File Information
Feature description
This API is used to query the information of a media file.
Note:
Before using this API, make sure that the media processing feature has been enabled in the data processing sectionin the console; otherwise, the error media bucket unbinded, bucket's host is unavailable will bereported.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1846 of 1869

Cloud Infinite

var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket (required) */Region: 'COS_REGION', /* Bucket region (required) */};cos.request({
Bucket: config.Bucket,
Region: config.Region,
Method: 'GET',
Key: 'test.mp4', /* Media file in bucket (required) */Query: {©2013-2022 Tencent Cloud. All rights reserved.

Page 1847 of 1869

Cloud Infinite'ci-process': 'videoinfo' /** Fixed value (required) */}}, function (err, data) {console.log(err || data);});

Parameter description
Parameter

Description

Type

Required

BucketBucket name in the format of BucketName-APPID .

StringYes

StringYes

RegionBucket region. For the enumerated values, see Regions and AccessEndpoints.

Key

Fixed value: mediabucket.

StringYes

ci-process

Operation type, which is fixed at videoinfo .

StringYes

Callback function description©2013-2022 Tencent Cloud. All rights reserved.

Page 1848 of 1869

Cloud Infinite

function(err, data) { ... }Parameter

Description

Type

The object returned when an error (network error or service error) occurs.
err

If the request is successful, this parameter is empty. For more information,
see Error Codes.

Object- statusCode

Returned HTTP status code, such as 200 , 403 , and 404 .

Number- headers

Returned headers.

Object©2013-2022 Tencent Cloud. All rights reserved.

Page 1849 of 1869

Cloud Infinitedata

The object returned when the request is successful. If an error occurs withthe request, this parameter is empty.

Object- statusCode

Returned HTTP status code, such as 200 , 403 , and 404 .

Number- headers

Returned headers.

Object- RequestId

Unique ID of the request.

String- Response

Response result.

Object- - MediaInfo

Media details.

Object- - - Stream

Stream information.

Object- - - - Video

Video information.

Container- - - - - Index

Stream number.

Number- - - - - CodecName

Codec format name.

String----CodecLongName

Detailed name of the codec format

String----CodecTimeBase

Codec timebase.

String----CodecTagString

Codec tag name.

String- - - - - CodecTag

Codec tag.

String- - - - - Profile

Video codec profile.

String- - - - - Height

Video height in px.

Number- - - - - Width

Video width in px.

Number- - - - - HasBFrame

Whether B-frames exist. 1: yes; 0: no.

Number- - - - - RefFrames

Number of reference frames for video codec.

Number- - - - - Sar

Sample aspect ratio.

String- - - - - Dar

Display aspect ratio.

String- - - - - PixFormat

Pixel format.

String- - - - - FieldOrder

Field order.

String©2013-2022 Tencent Cloud. All rights reserved.

Page 1850 of 1869

Cloud Infinite- - - - - Level

Video codec level.

Number- - - - - Fps

Video frame rate.

Number- - - - - AvgFps

Average frame rate.

String- - - - - Timebase

Timebase.

String- - - - - StartTime

Video start time in seconds.

Number- - - - - Duration

Video duration in seconds.

Number- - - - - Bitrate

Bitrate in Kbps.

Number- - - - - NumFrames

Total number of frames.

Number- - - - - Language

Language.

String- - - - Audio

Audio information.

Container- - - - - Index

Stream number.

Number- - - - - CodecName

Codec format name.

String----CodecLongName

Detailed name of the codec format.

String----CodecTimeBase

Codec timebase.

String----CodecTagString

Codec tag name.

String- - - - - CodecTag

Codec tag.

String- - - - - SampleFmt

Sample format.

String- - - - - SampleRate

Sample rate.

Number- - - - - Channel

Number of channels.

Number----ChannelLayout

Channel layout.

String- - - - - Timebase

Timebase.

String- - - - - StartTime

Audio start time in seconds.

Number- - - - - Duration

Audio duration in seconds.

Number©2013-2022 Tencent Cloud. All rights reserved.

Page 1851 of 1869

Cloud Infinite- - - - - Bitrate

Bitrate in Kbps.

Number- - - - - Language

Language.

String- - - - Subtitle

Subtitles information.

Container- - - - - Index

Stream number.

Number- - - - - Language

Language. und indicates no query result.

String- - - Format

Format information.

Object- - - - NumStream

Number of streams (including videos, audios, and subtitles).

Number- - - - NumProgram

Number of programs.

Number- - - - FormatName

Container format name.

String---FormatLongName

Detailed name of the container format.

String- - - - StartTime

Start time in seconds.

Number- - - - Duration

Duration in seconds.

Number- - - - Bitrate

Bitrate in Kbps.

Number- - - - Size

Size in bytes.

Number©2013-2022 Tencent Cloud. All rights reserved.

Page 1852 of 1869

Cloud Infinite

Media Screenshot APIs：

Last updated 2024-03-01 15:15:09

Overview
This document provides an overview of APIs and SDK code samples for media screenshot.
Note:
The COS Mini Program SDK version must be at least v1.1.1.
API

Operation

Description

GetSnapshot

Querying screenshot

Query the screenshot of media file at some time point

Querying Screenshot
Feature description
This API is used to query the screenshot of a media file at some time point.
Note:
Before using this API, make sure that the media processing feature has been enabled in the data processing sectionin the console; otherwise, the error media bucket unbinded, bucket's host is unavailable will bereported.
Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 1853 of 1869

Cloud Infinite

var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket (required) */Region: 'COS_REGION', /* Bucket region (required) */};cos.request({
Bucket: config.Bucket,
Region: config.Region,
Method: 'GET',
Key: 'test.mp4', /* Media file in bucket (required) */Query: {©2013-2022 Tencent Cloud. All rights reserved.

Page 1854 of 1869

Cloud Infinite'ci-process': 'snapshot', /** Fixed value (required) */time: 1, /** Screenshot time point in seconds (required) */// width: 0, /** Screenshot width (optional) */// height: 0, /** Screenshot height (optional) */// format: 'jpg', /** Screenshot format (optional). Valid values: jpg; png.
// rotate: 'auto', /** Image rotation method (optional). Default value: aut// mode: 'exactframe', /** Frame capturing method (optional). Default value},
RawBody: true,},
function(err, data){
console.log(err || data);});

Parameter description
Parameter

Description

Type

Required

BucketBucket name in the format of BucketName-APPID .

StringYes

StringYes

RegionBucket region. For the enumerated values, see Regions andAccess Endpoints.

Key

Object key (object name), which is the unique identifier of theobject in the bucket. For more information, see Object Overview.

StringYes

ci-process

Operation type, which is fixed at snapshot .

StringYes

time

Screenshot time point in seconds.

NumberYes

width

Screenshot width. Default value: 0.

Number

No

NumberNo

Screenshot height. Default value: 0. If width and heightheightare both 0 , the width and height of the video are used. If one ofthem is 0 , the other value is used to automatically adapt to the
aspect ratio of the video.

formatScreenshot format. Valid values: jpg; png. Default value: jpg.

StringNo

rotateImage rotation method. auto: Rotate automatically according to thevideo rotation information. off: Do not rotate. Default value: auto.

StringNo

mode

Frame capturing method. keyframe: Capture the last keyframe
before the specified time point. exactframe: Capture the frame at a
specified time point. Default value: exactframe.

StringNo©2013-2022 Tencent Cloud. All rights reserved.

Page 1855 of 1869

Cloud Infinite

Callback function descriptionfunction(err, data) { ... }Parameter

Description

Type

The object returned when an error (network error or service error) occurs.
err

If the request is successful, this parameter is empty. For more
information, see Error Codes.

Object- statusCode

Returned HTTP status code, such as 200 , 403 , and 404 .

Number©2013-2022 Tencent Cloud. All rights reserved.

Page 1856 of 1869

Cloud Infinite- headers

Returned headers.

Objectdata

The object returned when the request is successful. If an error occurs
with the request, this parameter is empty.

Object- statusCode

Returned HTTP status code, such as 200 , 403 , and 404 .

Number- headers

Returned headers.

Object- RequestId

Unique ID of the request.

String- BodyReturned file content, which is in string format by default.

String©2013-2022 Tencent Cloud. All rights reserved.

Page 1857 of 1869

Cloud Infinite

Content Moderation
Live Stream Moderation：

Last updated 2024-03-01 15:15:09

Overview
This document describes how to use the content moderation feature provided by Cloud Infinite (CI). CI fully integrates
the processing capabilities with the COS SDK.
Note
To use the content moderation service, you need to have the permission to use CI:
For root accounts, click here for role authorization.
For sub-accounts, see Authorizing Sub-Accounts to Access CI Services.
This document provides an overview of APIs and SDK code samples for live stream moderation.
Note
The COS Mini Program SDK version must be v1.1.1 or later.
API

Description

Submitting a live stream moderation job

Submits a live stream moderation job.

Querying live stream moderation job result

Queries the result of a specified live stream moderation job.

Submitting Live Stream Moderation Job
Feature description
This API is used to submit a live stream moderation job.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1858 of 1869

Cloud Infinite

function postLiveAuditing() {var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket. Required */Region: 'COS_REGION', /* Bucket region. Required */};var host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
var url = 'https://' + host + '/video/auditing';
var body = COS.util.json2xml({
Request: {Type: 'live_video',©2013-2022 Tencent Cloud. All rights reserved.

Page 1859 of 1869

Cloud Infinite

Input: {Url: 'rtmp://example.com/live/123', // The URL of the live stream to be mod// DataId: '',// UserInfo: {},},Conf: {
BizType: '766d07a7af937c26216c51db29793ea6', // BizType can be obtained aft// Callback: 'https://callback.com', // Callback address. Optional// CallbackType: 1, // Callback segment type. Optional}}});cos.request({
Bucket: config.Bucket,
Region: config.Region,
Method: 'POST',
Url: url,
Key: '/video/auditing',
ContentType: 'application/xml',
Body: body},function(err, data){
console.log(err || data);});}
postLiveAuditing();Parameter description
Node Name(Keyword)

ParentNode

Description

Type

Required

Request-The configuration items for live stream
moderation.

Container

Yes

Request has the following sub-nodes:
Node Name(Keyword)

ParentNode

Description

Type

RequiredType

RequestModeration job type, which is fixed atlive_video for live stream moderation.

StringYes

Input

RequestThe information of the live stream to be moderated.

Container

Yes

Conf

RequestThe configuration information of the moderation rule.

Container

Yes©2013-2022 Tencent Cloud. All rights reserved.

Page 1860 of 1869

Cloud Infinite

StorageConf

RequestThe configuration information of live stream storage.

Container

No

Input has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeDescription

Type

Required

Url

Request.Input

The URL of the live stream to be moderated, suchas rtmp://example.com/live/123 .

StringYes

DataIdRequest.Input

This field will return the original content in themoderation result, which can contain up to 512
bytes. You can use this field to uniquely identify
the data to be moderated in your business.

StringNo

UserInfo

Request.Input

ContainerNo

Custom field, which can be used to assist in
behavioral data analysis.

UserInfo has the following sub-nodes:
Node Name(Keyword)

Parent NodeDescription

Type

RequiredTokenId

Request.Input.UserInfo

Account information, which can containup to 128 bytes.

StringNo

Nickname

Request.Input.UserInfo

Nickname information, which cancontain up to 128 bytes.

StringNo

DeviceId

Request.Input.UserInfo

StringNo

AppId

Request.Input.UserInfo

Unique app ID, which can contain up to
128 bytes.

StringNo

Room

Request.Input.UserInfo

Room ID information, which can containup to 128 bytes.

StringNo

IP

Request.Input.UserInfo

IP address information, which cancontain up to 128 bytes.

StringNo

Type

Request.Input.UserInfo

Business type, which can contain up to
128 bytes.

String

No

ReceiveTokenId

Request.Input.UserInfo

StringNo©2013-2022 Tencent Cloud. All rights reserved.

Device information, which can containup to 128 bytes.

User account to receive messages,
which can contain up to 128 bytes.

Page 1861 of 1869

Cloud Infinite

GenderRequest.Input.UserInfo

Gender information, which can containup to 128 bytes.

StringNo

Level

Request.Input.UserInfo

Level information, which can contain up
to 128 bytes.

StringNo

Role

Request.Input.UserInfo

Role information, which can contain up
to 128 bytes.

StringNo

Type

Required

StringYes

String

No

IntegerNo

Conf has the following sub-nodes:
Node Name(Keyword)

BizTypeParent NodeRequest.Conf

Description
Unique identifier of the moderation policy. You canconfigure the scenes you want to moderate on themoderation policy page in the console, such as
pornographic, advertising, and illegal information.
For configuration instructions, see Setting
Moderation Policy.
You can get BizType in the console. If
BizType is specified, the moderation request
will perform moderation based on the scenes
configured in the moderation policy.

Callback

Request.Conf

Callback address, which must start with
http:// or https:// .
Callback segment type. Valid values: 1 (calls

CallbackType

Request.Confback all captured frames and audio segments);
2 (calls back only non-compliant captured
frames and audio segments). Default value: 1 .

StorageConf has the following sub-nodes:
Node
Name
(Keyword)

Parent NodeDescription

Type

Required

Path

Request.StorageConf

The path where to dump the live stream. The
TS and M3U8 files of the live stream will be

StringNo

saved in this directory of the bucket.
The M3U8 file will be named
Path/{$JobId}.m3u8 , and the TS file
will be named Path/{$JobId}-©2013-2022 Tencent Cloud. All rights reserved.

Page 1862 of 1869

Cloud Infinite{$Realtime}.ts , where Realtime is
the 17-digit time of year, month, day,hour, minute, second, andmillisecond .

Response description
For more information, see Submitting Live Stream Moderation Job.

Querying Live Stream Moderation Job Result
Feature description
This API is used to query the status and result of a live stream moderation job.
Sample request©2013-2022 Tencent Cloud. All rights reserved.

Page 1863 of 1869

Cloud Infinite

function getLiveAuditingResult() {var config = {// Replace with your own bucket information
Bucket: 'examplebucket-1250000000', /* Bucket. Required */Region: 'COS_REGION', /* Bucket region. Required */};var jobId = 'av0ca69557bd6111ed904c5254009411xx'; // `jobId`, which is returned avar host = config.Bucket + '.ci.' + config.Region + '.myqcloud.com';
var url = 'https://' + host + '/video/auditing/' + jobId;
cos.request({
Bucket: config.Bucket,©2013-2022 Tencent Cloud. All rights reserved.

Page 1864 of 1869

Cloud Infinite

Region: config.Region,
Method: 'GET',
Key: '/video/auditing/' + jobId,
Url: url,},function(err, data){
console.log(err || data);});}
getLiveAuditingResult();

Parameter description
Parameter

Description

Type

RequiredjobId

ID of the job to be queried.

StringYes

Response description
For more information, see Querying Live Stream Moderation Job Result.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1865 of 1869

Cloud Infinite

Personal Information Protection Policy for
SDK
Personal Information Protection Policy for CI
SDK：

Last updated 2024-03-01 15:15:09

Introduction
The CI SDK (the "SDK Product") is developed by Tencent Cloud Computing (Beijing) Co., Ltd. ("we", "us", or "our")with the registered address at 309, 3/F (West), No. 49, Zhichun Road, Haidian District, Beijing, China.
This Personal Information Protection Policy for CI SDK ("Policy") is intended to inform developers and end users of thecollection, use, and processing of end users' personal information by the SDK Product as necessary to implement its
features.
Please read this Policy carefully. If you are a developer, please acknowledge that you fully understand and agree tothis Policy before integrating the SDK Product. If you do not consent to this Policy or agree to fulfill your obligations toprotect end users' personal information in accordance with this Policy, you must immediately stop connecting to andusing the SDK Product. You shall integrate the SDK Product and process end users' personal information only after
obtaining their consent.

Notes
If you are a developer,
1. You shall comply with applicable laws and regulations in connection with your collection, use, andprocessing of end users' personal information, including but not limited to developing and publishing a
privacy policy governing personal information protection.
2. Before integrating the SDK Product, you shall inform end users of the collection, use, and processingof their personal information by the SDK Product and legally obtain their consent.
3. Unless otherwise required by laws and regulations, you shall not collect end users' personal
information before obtaining their consent.
4. You shall provide an easy-to-use, legally compliant mechanism that allows end users to exercise theirrights and explain to them how to query, copy, modify, delete, restrict the processing of, transfer, or get a
copy of their personal information, withdraw their consent, and cancel their account.
5. You shall comply with the requirements specified in this Policy.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1866 of 1869

Cloud Infinite

If you have any questions or comments about the content of this Policy, feel free to contact us through the channels asprovided in Article 7 of this Policy.

1. Information We Collect and How We Use It
1.1 Personal information required to implement the features of the SDK ProductThe implementation of the features of the SDK Product does not require collecting any personal information of end
users.
1.2 Permissions required to implement the features of the SDK ProductTo implement the features of the SDK Product, we will request the required permissions through the application.
OS

Permission

PurposeRequirediOS

Network
permission

To allow the network
accessApplied for by the application and not involved in the
SDK

Note that the permission display and disablement methods may vary by device and system and are subject to theused device and as further described in the operating system developers' instructions. By disabling a permission, end
users deny the permission. In this case, we and developers will no longer collect and use the personal information
corresponding to the permission and thus will not be able to provide the features that can be provided only if end users
enable the permission.
1.3 Exceptions to requiring user consent under laws and regulations
1. As necessary for the conclusion or performance of the contract with end users.
2. As necessary to fulfill our legal obligations.
3. As necessary to cope with public health emergencies or protect the health or property safety of end users in an
emergency.
4. The reasonable processing of end users' personal information for news coverage or public opinion supervision inline with the public interest.
5. The reasonable processing of end users' personal information made public by themselves or otherwise legally
made public in accordance with this Policy.
6. Other circumstances stipulated by laws and regulations.
Note: Any information collected by us that cannot identify end users alone or in combination with otherinformation is not personal information within the meaning of the law.

2. How End Users Manage Their Own Information©2013-2022 Tencent Cloud. All rights reserved.

Page 1867 of 1869

Cloud Infinite

We attach great importance to end users' right to manage their personal information and endeavor to help them do so,
including querying, copying, and deleting their personal information, canceling their account, and configuring theprivacy feature, to safeguard their rights. If you are a developer, you must provide methods for end users to query,
copy, modify, and delete their personal information, withdraw their consent, and cancel their account.
End users have the right to withdraw their consent to the processing of their personal information based on suchconsent. We offer developers the capabilities to disable the SDK Product as instructed in Getting Started for Android
or Getting Started for iOS. As we cannot interact directly with end users through UIs, end users can directly contact
developers and request them to stop using the SDK Product, or contact us through the channels as provided in Article
7 of this Policy. If you are an end user, you understand that specific business features or services can be implemented
only if you provide the information required by such features or services. If you withdraw your consent, we will be
unable to continue providing the corresponding features or services, nor will we further process your relevant personal
information. Your decision to withdraw your consent does not affect our processing of your personal information
previously collected based on such consent.

3. Information Storage
3.1 Information storage location
We will store personal information collected and generated in the territory of China in the territory of China inaccordance with laws and regulations.
3.2 Information retention period
Generally, we retain end users' personal information only for the minimum period of time necessary to achieve thepurposes as described in this Policy, except:
To comply with applicable laws and regulations.
To comply with court decisions, judgments, or other legal proceedings.
To comply with the law enforcement requirements of applicable government authorities.

4. Information Security
We implement appropriate safeguards to protect end users' personal information from loss, improper use, or
unauthorized access or disclosure.
We protect end users' personal information in strict accordance with laws and regulations.
We use various safeguards within a reasonable level of security to protect the security of information.
For example, we use encryption, anonymization, and other means to protect end users' personal information.
We have a rigorous management policy, process, and organization in place to guarantee the information security.
For example, we strictly limit the access to information to specific people, request them to comply with their©2013-2022 Tencent Cloud. All rights reserved.

Page 1868 of 1869

Cloud Infinite

confidentiality obligations, and review their compliance.
In the event of a security incident such as personal information leakage, we will launch the contingency plan to preventthe expansion of the incident and notify developers through such means as push notification and notice.

5. Minor Protection
The SDK Product is oriented to adults.
If you are a developer, and end users are minors under the age of 14 ("minors"), you must inform the minors' parents
or legal guardians of this Policy and may not process the minors' personal information unless you have obtained theconsent of their parents or legal guardians. If we find that you have provided the personal information of minors to us
without the consent of their guardians, we will take action to delete such personal information as soon as possible.
If you are the guardian of a minor and have any questions or claims regarding the protection of the minor's personal
information, you can contact developers or contact us through the channels as provided in Article 7 of this Policy.

6. Changes
We may revise this Policy from time to time.
If any revisions to this Policy will lead to the substantial derogation of end users' rights under this Policy, we will
announce such revisions through website notices or other means before such revisions take effect. If you are adeveloper, and the updated Policy specifies changes in the processing of end users' personal information, you must
update your privacy policy in due course, notify end users in the form of a pop-up window, and obtain their consent. If
end users do not agree to this Policy, you must stop integrating the SDK Product.

7. Contact Us
We have set up a personal information protection team and a personal information protection officer. If you have any
questions, complaints, or comments about this Policy or personal information protection, you can:Contact us through Tencent Customer Service.
Email your questions to Dataprivacy@tencent.com .
Mail to Data Privacy Protection Department, Tencent Binhai Building, No. 33, Haitian 2nd Road, Nanshan District,
Shenzhen, Guangdong, China, 518054.
We will review such questions, complaints, or comments and respond within 15 business days or such other period
as may be specified by laws and regulations.

©2013-2022 Tencent Cloud. All rights reserved.

Page 1869 of 1869