实现方式
- 采用图片拼接形式
官方地址:
https://www.alibabacloud.com/help/zh/oss/user-guide/add-watermarks
试例:
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
- 采用OSS修改线上图片形式
官方地址:
https://help.aliyun.com/zh/oss/developer-reference/img-2?spm=5176.smartservice_service_robot_chat_new.0.0.3364709a2Fv3VU#section-t3c-el1-0tn
解释:
-
阿里云OSS不支持上传图片时上传水印参数,只能通过修改线上图片的方式实现加水印的操作。
-
这里的FilePath是保存在OSS上面的图片地址
-
文字需要转换为BASE64 并且替换其中的 +与/(重要,不然会报错)
`` java
public void addWatermark(WatermarkReq req) {final ProjectConfiguration.AliyunOssProperties aliyunOssProperties = projectConfiguration.getAliyunOssProperties(); final String bucketName = aliyunOssProperties.getBucketName(); final String endPoint = aliyunOssProperties.getEndPoint(); final OSS client = new OSSClientBuilder().build(endPoint, aliyunOssProperties.getAccessKeyId(), aliyunOssProperties.getAccessKeySecret()); StringBuilder sbStyle = new StringBuilder(); Formatter styleFormatter = new Formatter(sbStyle); String filePath = req.getFilePath(); final LocalDateTime dateTime = req.getDateTime(); final String name = req.getName(); final String address = req.getAddress(); //解析filePath,去掉 "https://xxx.xxx.xxx/" 前缀 filePath = filePath.replace("https://xxx.xxx.xxx/", ""); //将dateTime转换为 HH:SS final String time = dateTime.format(DateTimeFormatter.ofPattern("HH:mm")); //将dataTime转换为 yyyy/MM/dd final String date = dateTime.format(DateTimeFormatter.ofPattern("yyyy/MM/dd")); String styleType = "image" + "/watermark,text_" + textToBase64(time + " | ") + ",g_sw,color_FFFFFF,size_30,y_50" + // 时间水印 "/watermark,text_" + textToBase64(address) + ",g_sw,color_FFFFFF,size_15" + // 地址水印 "/watermark,text_" + textToBase64(date) + ",g_sw,color_FFFFFF,size_15,x_110,y_65" + // 年月日水印 "/watermark,text_" + textToBase64(name) + ",g_sw,color_FFFFFF,size_15,x_110,y_50"; // 业务员水印 styleFormatter.format("%s|sys/saveas,o_%s,b_%s", styleType, BinaryUtil.toBase64String(filePath.getBytes()), BinaryUtil.toBase64String(bucketName.getBytes())); ProcessObjectRequest request = new ProcessObjectRequest(bucketName, filePath, sbStyle.toString()); client.processObject(request);
}
/**
- 文字进行base64编码
- @param text 文本
- @return
*/
private static String textToBase64(String text) {
byte[] textByte = text.getBytes();
String encode = Base64.encode(textByte);
encode = encode.replace(“+”, “-”);
encode = encode.replace(“/”, “_”);
encode = encode.replaceAll(“=”, “”);
return encode;
}```