Watermarks

更新时间:
复制 MD 格式

You can add visible watermarks to your videos, such as company logos or TV station icons, to highlight your brand, protect your copyright, and increase product recognition. ApsaraVideo Media Processing supports image watermarks, animated watermarks, and text watermarks. This topic provides Java software development kit (SDK) sample code that shows how to call API operations to add visible watermarks to videos. The sample code covers creating a watermark template, submitting a text watermark job, and submitting an image watermark job.

Prerequisites

Before you begin, initialize the client. For more information, see Initialization.

Create a watermark template

A watermark template contains parameters for the position and size of a watermark. Using a watermark template simplifies development. You can call the AddWaterMarkTemplate operation to create a watermark template.

Note
  • Watermark templates apply only to image watermarks, not text watermarks.

  • Watermark templates include only the position and size properties of a watermark, not the watermark asset itself. You must add the watermark asset when you submit a job.

  • After the template is created, the API returns a watermark template ID. You can also create and obtain watermark templates in the ApsaraVideo Media Processing (MPS) console. For more information, see Watermark templates.

  • The error "The resource 'WatermarkTemplate' quota has been used up" indicates that your template quota is exhausted. To increase your quota, submit a ticket.

/**
     * Add a watermark template.
     * @return
     * @throws Exception
     */
    public static void addWaterMarkTemplate() throws Exception {
        com.aliyun.mts20140618.Client client = WaterMark.createClient();
        // For details about watermark parameters, see https://help.aliyun.com/document_detail/29253.htm?spm=a2c4g.602851.0.0.4ab731bckAeLdq#section-k53-tt4-8b0
        JSONObject waterMarkConfig = new JSONObject();
        waterMarkConfig.put("Dx","10");
        waterMarkConfig.put("Dy","5");
        waterMarkConfig.put("ReferPos","TopRight");

        com.aliyun.mts20140618.models.AddWaterMarkTemplateRequest addWaterMarkTemplateRequest = new com.aliyun.mts20140618.models.AddWaterMarkTemplateRequest()
                // The name of the watermark.
                .setName("Name")
                // The job output configuration.
                .setConfig(waterMarkConfig.toJSONString());

        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // We recommend that you print the return value of the API.
            client.addWaterMarkTemplateWithOptions(addWaterMarkTemplateRequest, runtime);
        } catch (TeaException error) {
            // Handle exceptions with caution in actual business scenarios and do not ignore exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // The URL that is used for troubleshooting.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution in actual business scenarios and do not ignore exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // The URL that is used for troubleshooting.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }

Submit a watermark job

Adding a watermark changes the video content and requires the video to be re-encoded. In ApsaraVideo Media Processing, you can call the SubmitJobs operation to submit a watermark job.

Note
  • When you submit a job using the SDK, the Object parameter must be URL-encoded. Otherwise, the job fails. For more information, see URL encoding.

  • You must specify file names in the required format. Otherwise, the job fails because the file cannot be found. For more information, see Parameter details.

  • Record the JobID when you submit a job. You will need this ID for subsequent operations.

Text watermark

/**
     * Submit a transcoding job with a text watermark.
     * @return
     * @throws Exception
     */
    public static void submitTextWaterMarkJobs() throws Exception {
        com.aliyun.mts20140618.Client client = WaterMark.createClient();
        // Configure the watermark output.
        JSONArray waterMarks = new JSONArray();  // The maximum size of the watermark array is 4. This means a maximum of four watermarks are supported for each output.
        // Text watermark.
        JSONObject textWaterMarks = new JSONObject();
        textWaterMarks.put("WaterMarkTemplateId","<your waterMarkTemplateId>");
        textWaterMarks.put("Type","Text");
        // The content of the text watermark. The content must be Base64-encoded.
        textWaterMarks.put("TextWaterMark","{\"Content\":\"QWxpYmFiYSBDbG91ZCBWaWRlbyBvbiBEZW1hbmQ=\",\"FontName\":\"SimSun\",\"FontSize\":\"16\",\"Top\":2,\"Left\":10}");
        waterMarks.add(textWaterMarks);
        com.aliyun.mts20140618.models.SubmitJobsRequest submitJobsRequest = new com.aliyun.mts20140618.models.SubmitJobsRequest()
                // The job input.
                .setInput("{\"Bucket\":\"exampleBucket\",\"Location\":\"oss-cn-shanghai\",\"Object\":\"example.flv\",\"Referer\": \"The hotlink protection parameters that you configured in the OSS console\"}")
                // The job output configurations.
                .setOutputs("[{\"OutputObject\":\"exampleOutput.mp4\",\"TemplateId\":\"6181666213ab41b9bc21da8ff5ff****\",\"WaterMarks\":" + waterMarks.toJSONString() + ",\"UserData\":\"testid-001\"}]")
                // The OSS bucket where the output file is stored.
                .setOutputBucket("exampleBucket")
                // The region where the OSS bucket is located.
                .setOutputLocation("oss-cn-shanghai")
                // The MPS queue ID.
                .setPipelineId("dd3dae411e704030b921e52698e5****");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // If you copy the code, print the API return value.
            client.submitJobsWithOptions(submitJobsRequest, runtime);
        } catch (TeaException error) {
            // The following code is for demonstration purposes only. Handle exceptions with caution. Do not ignore exceptions in your project.
            // Error message
            System.out.println(error.getMessage());
            // The diagnosis address
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // The following code is for demonstration purposes only. Handle exceptions with caution. Do not ignore exceptions in your project.
            // Error message
            System.out.println(error.getMessage());
            // The diagnosis address
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }

Image watermark

/**
     * Submit a transcoding job with an image watermark.
     * @return
     * @throws Exception
     */
    public static void submitImageWaterMarkJobs() throws Exception {
        com.aliyun.mts20140618.Client client = WaterMark.createClient();
        // Configure the watermark output.
        JSONArray waterMarks = new JSONArray();  // The maximum size of the watermark array is 4. This means a maximum of four watermarks are supported for each output.

        // Image watermark.
        JSONObject imageWaterMarks = new JSONObject();
        imageWaterMarks.put("WaterMarkTemplateId","<your waterMarkTemplateId>");
        imageWaterMarks.put("Type","Image");
        // The width and height of the image or animated watermark.
        imageWaterMarks.put("Width","200");
        imageWaterMarks.put("Height","100");
        // The path of the watermark image.
        JSONObject logoFile = new JSONObject();
        logoFile.put("Bucket","<your bucket name>");
        logoFile.put("Location","oss-cn-shanghai");
        // You can replace the image object with a static PNG image, an animated PNG (APNG) image with the .apng file name extension, a MOV file, or a GIF file. If the asset is not a static image, the file name extension must be in lowercase.
        logoFile.put("Object", URLEncoder.encode("animated_logo.apng", "utf-8"));

        imageWaterMarks.put("InputFile",logoFile.toJSONString());
        waterMarks.add(imageWaterMarks);
        com.aliyun.mts20140618.models.SubmitJobsRequest submitJobsRequest = new com.aliyun.mts20140618.models.SubmitJobsRequest()
                // The job input.
                .setInput("{\"Bucket\":\"exampleBucket\",\"Location\":\"oss-cn-shanghai\",\"Object\":\"example.flv\",\"Referer\": \"The hotlink protection parameters that you configured in the OSS console\"}")
                // The job output configurations.
                .setOutputs("[{\"OutputObject\":\"exampleOutput.mp4\",\"TemplateId\":\"6181666213ab41b9bc21da8ff5ff****\",\"WaterMarks\":" + waterMarks.toJSONString() + ",\"UserData\":\"testid-001\"}]")
                // The OSS bucket where the output file is stored.
                .setOutputBucket("exampleBucket")
                // The region where the OSS bucket is located.
                .setOutputLocation("oss-cn-shanghai")
                // The MPS queue ID.
                .setPipelineId("dd3dae411e704030b921e52698e5****");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // If you copy the code, print the API return value.
            client.submitJobsWithOptions(submitJobsRequest, runtime);
        } catch (TeaException error) {
            // The following code is for demonstration purposes only. Handle exceptions with caution. Do not ignore exceptions in your project.
            // Error message
            System.out.println(error.getMessage());
            // The diagnosis address
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // The following code is for demonstration purposes only. Handle exceptions with caution. Do not ignore exceptions in your project.
            // Error message
            System.out.println(error.getMessage());
            // The diagnosis address
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }

Complete code

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.tea.TeaException;

import java.net.URLEncoder;

public class WaterMark {
    /**
     * description :
     * <p>Use your AccessKey ID and AccessKey secret to initialize the client.</p>
     * @return Client
     *
     * @throws Exception
     */
    public static com.aliyun.mts20140618.Client createClient() throws Exception {

        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        config.endpoint = "mts.cn-shanghai.aliyuncs.com";
        return new com.aliyun.mts20140618.Client(config);
    }

    /**
     * Create a watermark template.
     * @return
     * @throws Exception
     */
    public static void addWaterMarkTemplate() throws Exception {
        com.aliyun.mts20140618.Client client = WaterMark.createClient();
        // For details about the watermark parameters, see https://help.aliyun.com/document_detail/29253.htm?spm=a2c4g.602851.0.0.4ab731bckAeLdq#section-k53-tt4-8b0
        JSONObject waterMarkConfig = new JSONObject();
        waterMarkConfig.put("Dx","10");
        waterMarkConfig.put("Dy","5");
        waterMarkConfig.put("ReferPos","TopRight");

        com.aliyun.mts20140618.models.AddWaterMarkTemplateRequest addWaterMarkTemplateRequest = new com.aliyun.mts20140618.models.AddWaterMarkTemplateRequest()
                // The name of the watermark.
                .setName("Name")
                // The job output configuration.
                .setConfig(waterMarkConfig.toJSONString());

        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // Print the return value of the API.
            client.addWaterMarkTemplateWithOptions(addWaterMarkTemplateRequest, runtime);
        } catch (TeaException error) {
            // Handle exceptions with caution in actual business scenarios and do not ignore exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // The URL for troubleshooting.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution in actual business scenarios and do not ignore exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // The URL for troubleshooting.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }

    /**
     * Submit a text watermark job.
     * @return
     * @throws Exception
     */
    public static void submitTextWaterMarkJobs() throws Exception {
        com.aliyun.mts20140618.Client client = WaterMark.createClient();
        // Configure the output settings of watermarks.
        JSONArray waterMarks = new JSONArray();  // A watermark array consists of up to four watermarks. This means that a stream can contain a maximum of four watermarks.
        // Text watermarks.
        JSONObject textWaterMarks = new JSONObject();
        textWaterMarks.put("WaterMarkTemplateId","<your waterMarkTemplateId>");
        textWaterMarks.put("Type","Text");
        // Specify the text to be used as watermarks for the Content parameter. The specified text must be encoded in Base64.
        textWaterMarks.put("TextWaterMark","{\"Content\":\"5rWL6K+V5paH5a2X5rC05Y2w\",\"FontName\":\"SimSun\",\"FontSize\":\"16\",\"Top\":2,\"Left\":10}");
        waterMarks.add(textWaterMarks);
        com.aliyun.mts20140618.models.SubmitJobsRequest submitJobsRequest = new com.aliyun.mts20140618.models.SubmitJobsRequest()
                // The job input.
                .setInput("{\"Bucket\":\"exampleBucket\",\"Location\":\"oss-cn-shanghai\",\"Object\":\"example.flv\",\"Referer\": \"The parameter that you set in the Object Storage Service (OSS) console to enable the hotlink protection feature\"}")
                // The job output configuration.
                .setOutputs("[{\"OutputObject\":\"exampleOutput.mp4\",\"TemplateId\":\"6181666213ab41b9bc21da8ff5ff****\",\"WaterMarks\":" + waterMarks.toJSONString() + ",\"UserData\":\"testid-001\"}]")
                // The OSS bucket in which the output file is stored.
                .setOutputBucket("exampleBucket")
                // The region in which the OSS bucket resides.
                .setOutputLocation("oss-cn-shanghai")
                // The ID of the pipeline.
                .setPipelineId("dd3dae411e704030b921e52698e5****");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // Print the return value of the API.
            client.submitJobsWithOptions(submitJobsRequest, runtime);
        } catch (TeaException error) {
            // Handle exceptions with caution in actual business scenarios and do not ignore exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // The URL for troubleshooting.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution in actual business scenarios and do not ignore exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // The URL for troubleshooting.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }

    /**
     * Submit an image watermark job.
     * @return
     * @throws Exception
     */
    public static void submitImageWaterMarkJobs() throws Exception {
        com.aliyun.mts20140618.Client client = WaterMark.createClient();
        // Configure the output settings of watermarks.
        JSONArray waterMarks = new JSONArray();  // A watermark array consists of up to four watermarks. This means that a stream can contain a maximum of four watermarks.

        // Image watermarks.
        JSONObject imageWaterMarks = new JSONObject();
        imageWaterMarks.put("WaterMarkTemplateId","<your waterMarkTemplateId>");
        imageWaterMarks.put("Type","Image");
        // The width and height of the image or the animated watermark.
        imageWaterMarks.put("Width","200");
        imageWaterMarks.put("Height","100");
        // The path to the image to be used as watermarks.
        JSONObject logoFile = new JSONObject();
        logoFile.put("Bucket","<your bucket name>");
        logoFile.put("Location","oss-cn-shanghai");
        // You can specify a static PNG image, an animated PNG image, a MOV file, or a GIF file as needed. The file name extension of an animated PNG image must be apng. If the image to be used as the watermark is a non-static image, the file name extension must be in lowercase.
        logoFile.put("Object", URLEncoder.encode("Dynamic logo.apng", "utf-8"));

        imageWaterMarks.put("InputFile",logoFile.toJSONString());
        waterMarks.add(imageWaterMarks);
        com.aliyun.mts20140618.models.SubmitJobsRequest submitJobsRequest = new com.aliyun.mts20140618.models.SubmitJobsRequest()
                // The job input.
                .setInput("{\"Bucket\":\"exampleBucket\",\"Location\":\"oss-cn-shanghai\",\"Object\":\"example.flv\",\"Referer\": \"The parameter that you set in the Object Storage Service (OSS) console to enable the hotlink protection feature\"}")
                // The job output configuration.
                .setOutputs("[{\"OutputObject\":\"exampleOutput.mp4\",\"TemplateId\":\"6181666213ab41b9bc21da8ff5ff****\",\"WaterMarks\":" + waterMarks.toJSONString() + ",\"UserData\":\"testid-001\"}]")
                // The OSS bucket in which the output file is stored.
                .setOutputBucket("exampleBucket")
                // The region in which the OSS bucket resides.
                .setOutputLocation("oss-cn-shanghai")
                // The ID of the pipeline.
                .setPipelineId("dd3dae411e704030b921e52698e5****");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // Print the return value of the API.
            client.submitJobsWithOptions(submitJobsRequest, runtime);
        } catch (TeaException error) {
            // Handle exceptions with caution in actual business scenarios and do not ignore exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // The URL for troubleshooting.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution in actual business scenarios and do not ignore exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // The URL for troubleshooting.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }

    public static void main(String[] args_) throws Exception {
        // Create a watermark template.
        WaterMark.addWaterMarkTemplate();
        // Submit an image watermark job.
        //WaterMark.submitImageWaterMarkJobs();
        // Submit a text watermark job.
        //WaterMark.submitTextWaterMarkJobs();

    }
}

References