You can add watermarks to images or objects that are stored in Object Storage Service (OSS) to help prevent the resources from being replicated or used without your authorization.
Scenarios
Copyright protection: To help prevent your works from being replicated or used without your authorization, you can add watermarks to images to identify the copyright.
Brand promotion: Enterprises or individuals can add watermarks with brand logos or names to images, videos, or documents to promote their brands or logos.
Tamper prevention: Adding watermarks to official documents, certificates, or reports can increase the difficulty of tampering and reduce the risk of document forgery.
Image plagiarism prevention: Images can be easily downloaded and republished by Internet users. You can add watermarks to images to show that they are copyrighted.
Legal compliance requirement: In some cases, you must add watermarks to meet legal compliance requirements when you publish specific content of legal terms or contract terms.
Usage notes
You can use object URLs, OSS SDKs, or API operations to configure IMG parameters that are used to process images. In this example, object URLs are used. You can use object URLs to configure IMG parameters only for public-read images. If you want to configure IMG parameters for private images, use OSS SDKs or API operations. For more information, see IMG implementation modes.
Only images stored in the current bucket can be used as watermarks. To use online or local images as watermarks, you must first upload the images to the current bucket.
Only JPG, PNG, BMP, WebP, and TIFF images can be used as watermarks.
You can add up to three different image watermarks to a single image. An image watermark cannot completely overlap another image watermark.
Traditional Chinese characters cannot be used as text watermarks.
Parameters
Action: watermark
The following tables describe the parameters that you can configure when you add watermarks to images.
Basic parameters
Parameter
Required
Description
Valid value
t
No
The opacity of the watermark.
[0,100]
Default value: 100. The value 100 specifies that the watermark is opaque.
g
No
The position of the watermark on the image.
nw: upper left.
north: upper middle.
ne: upper right.
west: middle left.
center: center.
east: middle right.
sw: lower left.
south: lower middle.
se (default): lower right.
For the precise position that is specified by each value, see the following figure.
x
No
The horizontal margin, which specifies the horizontal distance between the watermark and the image edge. This parameter takes effect only when the watermark is on the upper left, middle left, lower left, upper right, middle right, or lower right of the image.
[0,4096]
Default value: 10.
Unit: pixel.
y
No
The vertical margin, which specifies the vertical distance between the watermark and the image edge. This parameter takes effect only when the watermark is on the upper left, upper middle, upper right, lower left, lower middle, or lower right of the image.
[0,4096]
Default value: 10.
Unit: pixel.
voffset
No
The vertical offset from the middle line. When the watermark is on the middle left, center, or middle right of the image, you can specify the vertical offset of the watermark along the middle line.
[-1000,1000]
Default value: 0.
Unit: pixel.
fill
No
Specifies whether to tile the image watermarks or text watermarks across the image.
NoteIf you want to add tiled watermarks, submit an application at Quota Center.
1: tiles the image watermarks or text watermarks across the image.
0: does not tile the image watermarks or text watermarks across the image. This is the default value.
padx
No
The horizontal spacing between watermarks when the image watermarks or text watermarks are tiled across the image. This parameter is valid only when you set fill to 1.
[0,4096]
Default value: 0.
Unit: pixel.
pady
No
The vertical spacing between watermarks when the image watermarks or text watermarks are tiled across the image. This parameter is valid only when you set fill to 1.
[0,4096]
Default value: 0.
Unit: pixel.
You can use parameters x, y, and voffset to adjust the position of a watermark on an image. You can also use these parameters to adjust the watermark layout when the image contains multiple watermarks.
The following figure shows the positions of watermarks based on coordinates.
Image watermark parameters
Parameter
Required
Description
Valid value
image
Yes
The complete name of the image object that you want to use as a watermark. The object name must be Base64-encoded. For more information, see Encode watermark-related parameters.
For example, if you want to use an image named panda.png in the image directory of the bucket as the watermark, you need to encode image/panda.png. The encoding result is
aW1hZ2UvcGFuZGEucG5n
.NoteOnly objects in the current bucket can be used as watermarks.
Base64-encoded strings.
Parameters for watermark image preprocessing
You can preprocess watermark images by using parameters in image resizing, custom crop, indexed slice, rounded rectangle, and image rotation actions. When you preprocess a watermark image, you can include the P parameter to resize the watermark image.
Parameter
Description
Valid value
P
The percentage of the size of the watermark image relative to the source image. For example, if you set this parameter to 10 for a source image of 100 × 100 pixels, the size of the watermark image is 10 × 10 pixels. If the size of the source image is 200 × 200 pixels, the size of the watermark image is 20 × 20 pixels.
[1,100]
Text watermark parameters
Parameter
Required
Description
Valid value
text
Yes
The content of the text watermark. The text content must be Base64-encoded. For more information, see Encode watermark-related parameters.
A Chinese string before Base64-encoding cannot exceed 64 characters in length.
type
No
The font of the text watermark. The font name must be Base64-encoded.
For more information about the supported fonts and the encoding results of the fonts, see Font types and encoding results.
Default value: wqy-zenhei (encoding result: d3F5LXplbmhlaQ).
color
No
The color of the text watermark. The valid values for this parameter are RGB color values.
For example, 000000 specifies black, and FFFFFF specifies white.
Default value: 000000.
size
No
The size of the text watermark.
(0,1000]
Default value: 40.
Unit: pixel.
shadow
No
The opacity of the shadow for the text watermark.
[0,100]
Default value: 0. The value 0 specifies that no shadows are added to the text.
rotate
No
The degree by which the text is rotated clockwise.
[0,360]
Default value: 0. The value 0 specifies that the text is not rotated.
The following table describes the valid values of the type parameter and the encoding results of these values.
Value
Description
Encoding result
wqy-zenhei
WenQuanYi Zen Hei
d3F5LXplbmhlaQ
wqy-microhei
WenQuanYi Micro Hei
d3F5LW1pY3JvaGVp
fangzhengshusong
Fangzheng Shusong
ZmFuZ3poZW5nc2h1c29uZw
fangzhengkaiti
Fangzheng Kaiti
ZmFuZ3poZW5na2FpdGk
fangzhengheiti
Fangzheng Heiti
ZmFuZ3poZW5naGVpdGk
fangzhengfangsong
Fangzheng Fangsong
ZmFuZ3poZW5nZmFuZ3Nvbmc
droidsansfallback
DroidSansFallback
ZHJvaWRzYW5zZmFsbGJhY2s
Text-and-image watermark parameters
Parameter
Required
Description
Valid value
order
No
The order of the text watermark and image watermark.
0 and 1.
0 (default): The image watermark is on the top of the text watermark.
1: The text watermark is on the top of the image watermark.
align
No
The alignment of the text watermark and image watermark.
0, 1, and 2.
0: Top alignment is applied to the text watermark and the image watermark.
1: Center alignment is applied to the text watermark and the image watermark.
2 (default): Bottom alignment is applied to the text watermark and the image watermark.
interval
No
The spacing between the text watermark and image watermark.
[0,1000]
Default value: 0.
Unit: pixel.
Encode watermark-related parameters
When you add watermarks, you must use Base64 to encode watermark-related parameters, such as the text and font of the text watermark and the name of the watermark image, into URL-safe strings. Encoding requires two steps:
Encode watermark-related parameters by using Base64.
Replace the following characters in the encoding result:
Replace the plus signs (+) in the encoding result with hyphens (-).
Replace the forward slashes (/) in the encoding result with underscores (_).
Omit the equal signs (=) at the end of the encoding result.
We recommend that you use base64url encoder to encode watermark-related parameters.
The encoding results can be used only in specific parameters in watermark operations. Do not use the encoding results in signature strings.
Methods
Add watermarks to public-read or public-read-write images
You can add image processing (IMG) parameters to the URL of a public-read or public-read write image to add watermarks to the image.
Example 1: Add a text watermark to a public-read or public-read write image
This section provides examples on how to add a text watermark to an image named example.jpg in the oss-console-img-demo-cn-hangzhou-3az bucket in the China (Hangzhou) region. The image is hosted at the following URL: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example.jpg.
The following examples show how to add a text watermark to example.jpg:
Add the string "Hello World" to the image as a text watermark
Base64-encode the string "Hello World" into a URL-safe string. For more information, see Encode watermark-related parameters. The encoding result is
SGVsbG8gV29ybGQ
and the URL used to process the image is https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/watermark,text_SGVsbG8gV29ybGQ.Configure multiple IMG parameters when you add a text watermark to the image
In this example, IMG parameters are configured to perform the following operations on the source image and the text watermark "Hello World":
Resize the source image example.jpg to 300 × 300 pixels by using
resize,w_300,h_300
Set the font of the watermark text to WenQuanYi Zen Hei by using
type_d3F5LXplbmhlaQ
. d3F5LXplbmhlaQ is the result of encoding WenQuanYi Zen Hei in Base64.Add the string "Hello World" to the source image as a text watermark by using
text_SGVsbG8gV29ybGQ
.Set the color of the watermark text to white and the size of the text to 30 pixels by using
color_FFFFFF,size_30
.Set the opacity of the shadow of the watermark text to 50% by using
shadow_50
.Set the position of the text watermark to lower right, the horizontal margin to 10 pixels, and the vertical offset from the middle line to 10 pixels by using
g_se,x_10,y_10
.
The following URL is used to process the image based on the preceding parameters: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/resize,w_300,h_300/watermark,type_d3F5LXplbmhlaQ,size_30,text_SGVsbG8gV29ybGQ,color_FFFFFF,shadow_50,t_100,g_se,x_10,y_10.
Example 2: Add an image watermark to a public-read or public-read write image
The following examples show how to add an image watermark to the example.jpg image:
Add an image named panda.png to the source image as an image watermark
Base64-encode the name of the panda.png image into a URL-safe string. The encoding result is
cGFuZGEucG5n
and the URL used to process the image is https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/watermark,image_cGFuZGEucG5n.Configure multiple IMG parameters when you add an image watermark to the source image
In this example, IMG parameters are configured to perform the following operations on the example.jpg image and add the panda.png image to the example.jpg image as an image watermark:
Resize the example.jpg image to 300 × 300 pixels by using
resize,w_300,h_300
.Set the quality of the example.jpg image to 90% by using
quality,q_90
.Add the panda.png image to the source image as an image watermark by using
watermark,image_cGFuZGEucG5n
. cGFuZGEucG5n is the result of encoding panda.png in Base64.Set the opacity of the watermark image to 90% by using
t_90
.Set the position of the image watermark to lower right, the horizontal margin to 10 pixels, and the vertical offset from the middle line to 10 pixels by using
g_se,x_10,y_10
.
The following URL is used to process the image based on the preceding parameters: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/resize,w_300,h_300/quality,q_90/watermark,image_cGFuZGEucG5n,t_90,g_se,x_10,y_10.
Preprocess the image watermark and then configure IMG parameters
In this example, IMG parameters are configured to perform the following operations on the example.jpg image and add the panda.png image to the example.jpg image as an image watermark:
Resize the width of the source image example.jpg to 300 pixels by using
resize,w_300
.Resize the image watermark panda.png to 30% of the size of the source image by using
image_cGFuZGEucG5nP3gtb3NzLXByb2Nlc3M9aW1hZ2UvcmVzaXplLFBfMzA
(cGFuZGEucG5nP3gtb3NzLXByb2Nlc3M9aW1hZ2UvcmVzaXplLFBfMzA
is the Base64-encoding result ofpanda.png?x-oss-process=image/resize,P_30
).Set the opacity of the image watermark to 90%, the position of the image watermark to lower right, the horizontal margin to 10 pixels, and the vertical offset from the middle line to 10 pixels by using
t_90,g_se,x_10,y_10
.
The following URL is used to process the image based on the preceding parameters: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/resize,w_300/watermark,image_cGFuZGEucG5nP3gtb3NzLXByb2Nlc3M9aW1hZ2UvcmVzaXplLFBfMzA,t_90,g_se,x_10,y_10.
Add multiple image watermarks to the source image
In this example, panda.png and Tulips.jpg are added to example.jpg as image watermarks.
Base64-encode the name of the panda.png image into a URL-safe string. The encoding result is
cGFuZGEucG5n
. Add the panda.png image as an image watermark by usingwatermark,image_cGFuZGEucG5n
.Base64-encode the name of the Tulips.jpg image into a URL-safe string. The encoding result is
VHVsaXBzLmpwZw
. Set the position of the image watermark to middle left, the horizontal margin to 10 pixels, and the vertical offset from the middle line to 10 pixels by usingwatermark,image_VHVsaXBzLmpwZw,g_west,x_10,y_10
.
The following URL is used to process the image based on the preceding parameters:
Example 3: Add text and image watermarks to a public-read or public-read write image
The following example shows how to add text and image watermarks to the example.jpg image:
The following URL is used to process the image based on the encoding results of the name of the image that you want to add to the source image as an image watermark and the string that you want to add to the source image as a text watermark: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/watermark,image_cGFuZGEucG5nP3gtb3NzLXByb2Nlc3M9aW1hZ2UvcmVzaXplLFBfMzA,text_SGVsbG8gV29ybGQ.
Add a watermark to a private image
You can use OSS SDKs and API operations to add a watermark to a private image.
Use OSS SDKs
The following sample code provides examples on how to add a watermark to a private image by using OSS SDKs for common programming languages. For more information about how to add a watermark to a private image by using other programming languages, see Overview.
Java
OSS SDK for Java 3.17.4 or later is required.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GetObjectRequest;
import java.io.File;
public class Demo {
public static void main(String[] args) throws Throwable {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region of the endpoint. Example: cn-hangzhou.
String region = "cn-hangzhou";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path.
String objectName = "src.jpg";
// Specify the full path to which you want to save the processed image. Example: D:\\localpath\\example-new.jpg. If a file that has the same name already exists in the path, the processed image overwrites the file. Otherwise, the processed image is saved in the path.
String pathName = "D:\\dest.jpg";
// Create an OSSClient instance.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Add the text watermark "Hello World" to the image.
String image = "image/watermark,text_SGVsbG8gV29ybGQ";
GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
request.setProcess(image);
// Save the processed image as example-new.jpg to your local device.
// If you specify only the name of a local file such as example-new.jpg without specifying the local path of the file, the processed image is saved to the local path of the project to which the sample program belongs.
ossClient.getObject(request, new File("D:\\dest.jpg"));
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
PHP
OSS SDK for PHP 2.7.0 or later is required.
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
$provider = new EnvironmentVariableCredentialsProvider();
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the bucket. Example: examplebucket.
$bucket= "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.jpg. Do not include the bucket name in the full path.
$object = "src.jpg";
// Specify the full path to which you want to save the processed image. Example: D:\\localpath\\example-new.jpg. If a file that has the same name already exists in the path, the processed image overwrites the file. Otherwise, the processed image is saved in the path.
// If you specify only the name of a local file such as example-new.jpg without specifying the local path of the file, the processed image is saved to the local path of the project to which the sample program belongs.
$download_file = "D:\\dest.jpg";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
// Specify the ID of the Alibaba Cloud region in which the bucket is located.
"region" => "cn-hangzhou"
);
$ossClient = new OssClient($config);
// Add the text watermark "Hello World" to the image.
$image = "image/watermark,text_SGVsbG8gV29ybGQ";
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => $image);
// Save the processed image to your local computer.
$ossClient->getObject($bucket, $object, $options);
Python
OSS SDK for Python 2.18.4 or later is required.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
## Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# Specify the ID of the Alibaba Cloud region in which the bucket is located.
region = 'cn-hangzhou'
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)
# Specify the name of the source image. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: example/example.jpg.
key = 'src.jpg'
# Specify the name of the processed image.
new_pic = 'D:\\dest.jpg'
# Add the text watermark "Hello World" to the image.
image = 'image/watermark,text_SGVsbG8gV29ybGQ'
bucket.get_object_to_file(key, new_pic, process=image)
Go
OSS SDK for Go 3.0.2 or later is required.
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func HandleError(err error) {
fmt.Println("Error:", err)
os.Exit(-1)
}
func main() {
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region("cn-hangzhou"))
if err != nil {
HandleError(err)
}
// Specify the name of the bucket in which the source image is stored. Example: examplebucket.
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
HandleError(err)
}
// Specify the name of the source image. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: example/example.jpg.
sourceImageName := "src.jpg"
// Specify the name of the processed image.
targetImageName := "D://dest.jpg"
// Add the text watermark "Hello World" to the image.
image := "image/watermark,text_SGVsbG8gV29ybGQ"
err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(image))
if err != nil {
HandleError(err)
}
}
Use the OSS API
If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see GetObject.
You can process images by adding watermark parameters to the GetObject operation.
GET /oss.jpg?x-oss-process=image/watermark,w_100 HTTP/1.1
Host: oss-example.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: OSS qn6q**************:77Dv****************
FAQ
How do I use online or local images as watermark images?
When IMG is used to add image watermarks to a source image, make sure that the watermark images and the source image are stored in the same bucket. To add online or local images to a source image as image watermarks, you must first upload the images to the bucket in which the source image is stored.
What do I do if the "font content is too large" message appears when I add a text watermark?
When you add a text watermark to an image by using OSS IMG parameters, the maximum allowed length for a text watermark is 64 English characters, with each Chinese character equating to three English characters. When the "font content is too large" message appears, we recommend that you shorten the text watermark. For more information, see Example 1: Add a text watermark to a public-read or public-read-write image.
What do I do if I fail to add an image watermark to a private object?
The URL of a private object must be signed. IMG parameters cannot be directly added to the end of a signed URL. If you want to process a private object, add IMG parameters to the signature. For more information, see Generate a signed object URL that includes IMG parameters.
Can I configure a background color for an image watermark when I add the image watermark?
No. You cannot configure a background color for an image watermark.
How do I use a signed URL to access an image?
The URL of a private object must be signed. IMG parameters cannot be directly added to the end of a signed URL. If you want to process a private object, add IMG parameters to the signature. For more information, see IMG.
Does OSS support the vertical arrangement of watermarks?
Yes, OSS supports the vertical arrangement of watermarks. If you want to arrange watermarks vertically, you can split the watermarking operation into multiple watermark actions and use multiple watermark actions to implement vertical watermark arrangement.
For example, you can use https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/watermark,text_SGVsbG8gV29ybGQ/watermark,text_SGVsbG8gV29ybGQy,y_60.
How many watermarks can I add to an image at the same time?
You can add up to three watermarks to an image at the same time. If you want to add more than three watermarks to an image at the same time, submit a ticket.