您的当前位置:首页正文

javaImageIo实现图片内容动态修改

2024-11-20 来源:个人技术集锦

依赖

        <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>

读取要修改的图片

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

转换成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);

转换成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);

绘制图像

将上面的图进行渲染

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

在指定坐标绘制水印文字

		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);

结束流程

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

        byte[] bytes = outputStream.toByteArray();
        outputStream.close();
        return bytes;

生成后存放到本地

创建文件夹并放入

 //处理图片结束
 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");

}

小结

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

显示全文