操作图像而不删除其 EXIF 数据 [英] Manipulate an image without deleting its EXIF data

查看:67
本文介绍了操作图像而不删除其 EXIF 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用imageIO,我经常会遇到转换图片文件的问题,覆盖后会丢失所有的EXIF数据.有没有办法不先解压,缓存,再重置就可以保存?

Using imageIO, I usually have the problem of transforming an image file, and after overwriting it, it loses all of its EXIF data. Is there any way to preserve it without first extracting it, caching it, and then resetting it?

推荐答案

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

ImageIO do have this functionality itself, but instead of ImageIO.read you will need to use ImageReader:

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

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

(you may want to also check if such reader exists). Then you need to set the input:

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

现在您可以保存元数据:

Now you may save your metadata:

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:

When you want to save new image, you should use 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); <- This was initially in the code but actually it was only adding image again at the end of the file.

由于这是一个老话题,我想这个答案有点太晚了,但可能会帮助其他人,因为这个话题仍然可以用谷歌搜索.

As it's old topic, I guess this answer is a bit too late, but may help others as this topic is still googlable.

这篇关于操作图像而不删除其 EXIF 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆