前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >操作PNG图片的Chunks「建议收藏」

操作PNG图片的Chunks「建议收藏」

作者头像
Java架构师必看
发布2022-10-24 14:09:28
4480
发布2022-10-24 14:09:28
举报
文章被收录于专栏:Java架构师必看

大家好,我是架构君,一个会写代码吟诗的架构师。今天说一说操作PNG图片的Chunks「建议收藏」,希望能够帮助大家进步!!!

在学习如何向png图片中插入metaData 时候,发现了一个工具包,很好用,commons-imaging-1.0, 可以到网上搜索下载jar包。

这里写了一个简短的练习类,来学习, 实现的功能是读取图片的metadata,并插入到新图片中。

代码语言:javascript
复制
public static byte[] imageWriteExample(final File file)
			throws ImageReadException, ImageWriteException, IOException {
		// read image
		final BufferedImage image = Imaging.getBufferedImage(file);

		final ImageFormat format = ImageFormats.PNG;
		ImageInfo imageInfo = Imaging.getImageInfo(file);
		List<String> allComments = imageInfo.getComments();
		List newComments = new ArrayList();
		for (String items : allComments) {
			System.out.println(items);
			String[] item = items.split(":");
			if (item[0].equals("view_nodes")) {
				newComments.add(new PngText.Itxt(item[0], item[1], "utf-8", ""));
			} else {
				newComments.add(new PngText.Text(item[0], item[1]));
			}
		}

		final Map<String, Object> params = new HashMap<>();

		// set optional parameters if you like
		params.put(PngConstants.PARAM_KEY_PNG_TEXT_CHUNKS, newComments);
		params.put(PngConstants.PARAM_KEY_PNG_FORCE_TRUE_COLOR, imageInfo.getColorType());

		final byte[] bytes = Imaging.writeImageToBytes(image, format, params);

		return bytes;
	}

	public static void byte2image(byte[] data, String path) {
		if (data.length < 3 || path.equals(""))
			return;// 判断输入的byte是否为空
		try {
			FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));// 打开输入流
			imageOutput.write(data, 0, data.length);
			imageOutput.close();
			System.out.println("Make Picture success,Please find image in " + path);
		} catch (Exception ex) {
			System.out.println("Exception: " + ex);
			ex.printStackTrace();
		}
	}

	public static void main(String[] args) {
		File file = new File("C:\\test\\t.png");
		try {
			byte[] contentByte = imageWriteExample(file);
			byte2image(contentByte, "C:\\test\\a.png");
		} catch (ImageReadException e) {
			e.printStackTrace();
		} catch (ImageWriteException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

只听到从架构师办公室传来架构君的声音:

泪珠阁定空相觑。有谁来对上联或下联?

今天文章到此就结束了,感谢您的阅读,Java架构师必看祝您升职加薪,年年好运。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-10-112,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档