虽然,这不是什么牛逼的技术,但为了以后方便查阅,还是有必要写一篇记录下来。
Java处理图片的场景,属实不多,工作到现在总共遇到过两次,都是关于证书颁发相关的,也就是把姓名,证书编号等合成到图片上。
public static byte[] textWatermark(String pressText) throws IOException {
ClassPathResource classPathResource = new ClassPathResource("image/moke.jpg");
InputStream inputStream = classPathResource.getInputStream();
Image src = ImageIO.read(inputStream);
int width = src.getWidth(null);
int height = src.getHeight(null);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();
graphics.drawImage(src, 0, 0, width, height, null);
graphics.setColor(Color.BLACK); //添加抗锯齿处理,否则生成出来的图片会模糊
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
graphics.setFont(new Font(Font.SERIF, Font.BOLD, 30));
// 在指定坐标绘制水印文字
graphics.drawString(pressText, 30, 30);
graphics.dispose();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", outputStream);
byte[] bytes = outputStream.toByteArray();
outputStream.close();
return bytes;
}
代码很简单,就是利用Graphics2D将文字合成到图片, 再利用ImageIO将图导出到ByteArrayOutputStream,内存中的字节数组可以直接上传至存储桶中,当然也可以生成base64保存到数据库。
需要注意的就是不要忘了添加抗锯齿,否则文字会模糊。
高谈阔论