大家好,我是架构君,一个会写代码吟诗的架构师。今天说一说操作PNG图片的Chunks「建议收藏」,希望能够帮助大家进步!!!
在学习如何向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<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架构师必看祝您升职加薪,年年好运。