编程语言
首页 > 编程语言> > java – 操作图像而不删除其EXIF数据

java – 操作图像而不删除其EXIF数据

作者:互联网

使用imageIO,我经常遇到转换图像文件的问题,在覆盖它之后,它会丢失所有的EXIF数据.有没有办法保留它而不首先提取它,缓存它,然后重置它?

解决方法:

ImageIO本身就具有此功能,但您需要使用ImageReader而不是ImageIO.read:

ImageReader reader = ImageIO.getImageReadersBySuffix("jpg").next();

(您可能还想检查这样的阅读器是否存在).
然后你需要设置输入:

reader.setInput(ImageIO.createImageInputStream(your_imput_stream));

现在您可以保存元数据:

IIOMetadata metadata = reader.getImageMetadata(0); 
                            // As far as I understand you should provide 
                            // index as tiff images could have multiple pages

然后阅读图片:

BufferedImage bi = reader.read(0);

如果要保存新图像,则应使用ImageWriter:

// I'm writing to byte array in memory, but you may use any other stream
ByteArrayOutputStream os = new ByteArrayOutputStream(255);
ImageOutputStream ios = ImageIO.createImageOutputStream(os);

Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = iter.next();
writer.setOutput(ios);

//You may want also to alter jpeg quality
ImageWriteParam iwParam = writer.getDefaultWriteParam();
iwParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwParam.setCompressionQuality(.95f);

//Note: we're using metadata we've already saved.
writer.write(null, new IIOImage(bi, null, metadata), iwParam);
writer.dispose();

ImageIO.write(bi, "jpg", ios);

由于这是一个古老的主题,我想这个答案有点太晚了,但可能会帮助其他人,因为这个话题仍然可以转让.

标签:javax-imageio,java,image-resizing,bitmap,bufferedimage
来源: https://codeday.me/bug/20190930/1835360.html