当前位置:   article > 正文

javaImageIo实现图片内容动态修改

javaImageIo实现图片内容动态修改

依赖

        <dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>core</artifactId>
			<version>3.5.3</version>
		</dependency>
		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>javase</artifactId>
			<version>3.5.3</version>
		</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

读取要修改的图片

这里放在工程目录下

ClassPathResource classPathResource = new ClassPathResource("abc.jpeg");
  • 1

转换成Image

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);
  • 1
  • 2
  • 3
  • 4
  • 5

转换成Image

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);
  • 1
  • 2
  • 3
  • 4
  • 5

绘制图像

将上面的图进行渲染

Graphics2D graphics = image.createGraphics();
graphics.drawImage(src, 0, 0, width, height, null);
  • 1
  • 2

在指定坐标绘制水印文字

		graphics.drawString("内容1", 110, 212);
        graphics.drawString("内容2", 150, 255);
        graphics.drawString("内容3", 215, 300);
        graphics.drawString("内容4", 610, 473);
        graphics.drawString("内容5", 273, 1050);

        graphics.setFont(new Font(Font.SERIF, Font.BOLD, 35));
        graphics.drawString("内容6", 392, 473);

        graphics.setFont(new Font(Font.SERIF, Font.BOLD, 30));
        graphics.drawString("内容7", 590, 578);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

结束流程

		graphics.dispose();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        byte[] bytes = outputStream.toByteArray();
        outputStream.close();
        return bytes;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

生成后存放到本地

创建文件夹并放入

 //处理图片结束
 ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
 BufferedImage image = ImageIO.read(bis);
 //创建文件夹
 File folder = new File("/Users/zippo/2024-08-07");
 boolean success = false;
 if (!folder.isDirectory()) {
 		success = folder.mkdir();
 } else {
 		success = true;
 }
 if (success) {
 		// 将BufferedImage保存为文件
 		File outputFile = new File("/Users/zippo/2024-08-07/output2.jpg");
        ImageIO.write(image, "jpg", outputFile);

        System.out.println("图片转换成功,已保存为 output2.jpg");

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

小结

之后便可以在对应的路径下找到修改后的图片了。。。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/973292
推荐阅读
相关标签
  

闽ICP备14008679号