Adicione marcas d'água visíveis, como logotipos de empresas ou emissoras de TV, aos seus vídeos para aumentar a visibilidade da marca, proteger direitos autorais e impulsionar o reconhecimento do produto. O ApsaraVideo Media Processing (MPS) oferece os seguintes tipos de marcas d'água: image watermark, animated watermark e test watermark. Selecione o tipo conforme as necessidades do seu negócio. Este tópico apresenta exemplos de chamada das operações de API encapsuladas no MPS SDK for Java para gerenciar marcas d'água, incluindo criação de modelos, envio de jobs de texto e envio de jobs de imagem.
Pré-requisitos
Inicialize o cliente do SDK. Para mais informações, consulte Inicializar um cliente.
AddWaterMarkTemplate: Crie um modelo de marca d'água
Um modelo de marca d'água define configurações de vários parâmetros, como tamanho e posição. Use esse modelo para simplificar o gerenciamento. Chame a operação AddWaterMarkTemplate para criar um modelo de marca d'água.
O modelo aplica-se apenas a marcas d'água de imagem, não sendo válido para marcas d'água de texto.
Esse modelo especifica somente atributos da marca d'água, como localização e tamanho, mas não define o conteúdo. Especifique o conteúdo da marca d'água ao enviar um job.
Se a chamada à operação for bem-sucedida, o sistema retornará um ID de modelo de marca d'água. Também é possível criar o modelo e obter seu ID no console do MPS. Para mais detalhes, consulte Gerencie modelos de marca d'água.
Caso receba a mensagem de erro "The resource "WatermarkTemplate" quota has been used up", sua cota de modelos de marca d'água foi esgotada. Nessa situação, envie um ticket para solicitar o aumento da cota.
/**
* Create a watermark template.
* @return
* @throws Exception
*/
public static void addWaterMarkTemplate() throws Exception {
com.aliyun.mts20140618.Client client = WaterMark.createClient();
// For more information about watermark parameters, visit https://www.alibabacloud.com/help/zh/apsaravideo-for-media-processing/latest/parameter-details-a#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 {
// Write your own code to display the response of the API operation if necessary.
client.addWaterMarkTemplateWithOptions(addWaterMarkTemplateRequest, runtime);
} catch (TeaException error) {
// In real-world business scenarios, handle exceptions carefully and avoid ignoring them in your project. The exceptions in this example are for illustrative purposes 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);
// In real-world business scenarios, handle exceptions carefully and avoid ignoring them in your project. The exceptions in this example are for illustrative purposes 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);
}
}
SubmitJobs: Envie um job de marca d'água
Ao adicionar uma marca d'água ao vídeo, as imagens são alteradas e a recodificação se torna necessária. O MPS disponibiliza a operação SubmitJobs para envio de jobs de marca d'água.
Ao chamar a operação para enviar um job, aplique a codificação de URL no caminho do arquivo usado como marca d'água. Caso contrário, o job falhará. Para mais informações, consulte Codificação de URL.
Especifique um nome de arquivo válido para garantir que o sistema o encontre durante a execução do job. Consulte Detalhes dos parâmetros para mais informações.
Registre o ID do job enviado para facilitar operações futuras.
Envie um job de marca d'água de texto
/**
* 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 MPS queue.
.setPipelineId("dd3dae411e704030b921e52698e5****");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// Write your own code to display the response of the API operation if necessary.
client.submitJobsWithOptions(submitJobsRequest, runtime);
} catch (TeaException error) {
// In real-world business scenarios, handle exceptions carefully and avoid ignoring them in your project. The exceptions in this example are for illustrative purposes 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);
// In real-world business scenarios, handle exceptions carefully and avoid ignoring them in your project. The exceptions in this example are for illustrative purposes 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);
}
}
Marca d'água de imagem
/**
* 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 based on your business requirements. 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 MPS queue.
.setPipelineId("dd3dae411e704030b921e52698e5****");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// Write your own code to display the response of the API operation if necessary.
client.submitJobsWithOptions(submitJobsRequest, runtime);
} catch (TeaException error) {
// In real-world business scenarios, handle exceptions carefully and avoid ignoring them in your project. The exceptions in this example are for illustrative purposes 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);
// In real-world business scenarios, handle exceptions carefully and avoid ignoring them in your project. The exceptions in this example are for illustrative purposes 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);
}
}
Código de exemplo
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.tea.TeaException;
import java.net.URLEncoder;
public class WaterMark {
/**
* <b>description</b> :
* <p>Use your AccessKey pair 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.
.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 more information about watermark parameters, visit https://www.alibabacloud.com/help/zh/mps/developer-reference/parameter-details.
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 {
// Write your own code to display the response of the API operation if necessary.
client.addWaterMarkTemplateWithOptions(addWaterMarkTemplateRequest, runtime);
} catch (TeaException error) {
// In real-world business scenarios, handle exceptions carefully and avoid ignoring them in your project. The exceptions in this example are for illustrative purposes 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);
// In real-world business scenarios, handle exceptions carefully and avoid ignoring them in your project. The exceptions in this example are for illustrative purposes 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 MPS queue.
.setPipelineId("dd3dae411e704030b921e52698e5****");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// Write your own code to display the response of the API operation if necessary.
client.submitJobsWithOptions(submitJobsRequest, runtime);
} catch (TeaException error) {
// In real-world business scenarios, handle exceptions carefully and avoid ignoring them in your project. The exceptions in this example are for illustrative purposes 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);
// In real-world business scenarios, handle exceptions carefully and avoid ignoring them in your project. The exceptions in this example are for illustrative purposes 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 based on your business requirements. 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 MPS queue.
.setPipelineId("dd3dae411e704030b921e52698e5****");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// Write your own code to display the response of the API operation if necessary.
client.submitJobsWithOptions(submitJobsRequest, runtime);
} catch (TeaException error) {
// In real-world business scenarios, handle exceptions carefully and avoid ignoring them in your project. The exceptions in this example are for illustrative purposes 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);
// In real-world business scenarios, handle exceptions carefully and avoid ignoring them in your project. The exceptions in this example are for illustrative purposes 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();
}
}