用java写一个给上传照片文件添加水印,再上传到minio的代码
时间: 2024-03-21 12:44:35 浏览: 227
好的,以下是一个使用Java编写的为上传到Minio的照片文件添加水印的示例代码:
```java
import io.minio.MinioClient;
import io.minio.errors.MinioException;
import org.apache.commons.io.IOUtils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MinioUploadDemo {
public static void main(String[] args) {
try {
// 初始化MinioClient
MinioClient minioClient = new MinioClient("http://minio-server:9000", "minio-access-key", "minio-secret-key");
// 上传文件
String bucketName = "test-bucket";
String objectName = "example.jpg";
String filePath = "path/to/local/file.jpg";
InputStream inputStream = new FileInputStream(new File(filePath));
String contentType = "image/jpeg";
minioClient.putObject(bucketName, objectName, inputStream, contentType);
// 给上传的图片添加水印
addWatermark(minioClient, bucketName, objectName);
} catch (Exception e) {
System.out.println("Error occurred: " + e);
}
}
private static void addWatermark(MinioClient minioClient, String bucketName, String objectName) throws Exception {
// 下载图片
InputStream inputStream = minioClient.getObject(bucketName, objectName);
// 读取图片
BufferedImage image = ImageIO.read(inputStream);
// 添加水印
Graphics2D graphics = image.createGraphics();
graphics.setColor(Color.RED);
graphics.setFont(new Font("宋体", Font.BOLD, 30));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String watermark = "水印:" + sdf.format(new Date());
graphics.drawString(watermark, 0, image.getHeight() - 30);
graphics.dispose();
// 上传图片
InputStream newInputStream = IOUtils.toInputStream(image.toString(), "UTF-8");
minioClient.putObject(bucketName, objectName, newInputStream, "image/jpeg");
}
}
```
这段代码使用了 `minio-java` 库连接到Minio服务器,并且在上传文件到Minio之后,调用了 `addWatermark()` 方法,该方法会从Minio服务器上下载刚才上传的照片,然后添加水印并再次上传到Minio服务器。添加水印的方法使用了Java2D API来实现。
阅读全文