gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 05:49:25 25 4
gpt4 key购买 nike

使用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); <- This was initially in the code but actually it was only adding image again at the end of the file.

由于这是旧主题,我想这个答案有点太晚了,但可能对其他人有帮助,因为这个主题仍然可以在谷歌上搜索。

关于java - 操作图像而不删除其 EXIF 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5098509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com