操作PNG图片的MetaData

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

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

 

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