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

发布于 2024-12-28 06:33:49 字数 85 浏览 2 评论 0原文

使用 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

嘿哥们儿 2025-01-04 06:33:49

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.

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

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

And then read the image:

BufferedImage bi = reader.read(0);

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.

冷月断魂刀 2025-01-04 06:33:49

这是我的解决方案,结合使用 ImageIO< /a>、ImgscalrApache commons-imaging。遗憾的是(2016 年 5 月)没有一个库将读取图像与其元数据结合起来,这使得内存使用可能相当过多;欢迎改进。

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import org.apache.commons.imaging.ImageReadException;
import org.apache.commons.imaging.ImageWriteException;
import org.apache.commons.imaging.Imaging;
import org.apache.commons.imaging.common.IImageMetadata;
import org.apache.commons.imaging.formats.jpeg.JpegImageMetadata;
import org.apache.commons.imaging.formats.jpeg.exif.ExifRewriter;
import org.apache.commons.imaging.formats.tiff.TiffImageMetadata;
import org.apache.commons.io.IOUtils;
import org.imgscalr.Scalr;


public class ImageData {

    private byte[] imageData;


    public ImageData(InputStream instream) throws IOException {
        imageData  = IOUtils.toByteArray(instream);
        instream.close();
    }


    public synchronized void resize(int maxDimension) throws IOException, ImageReadException, ImageWriteException {
        // Resize the image if necessary
        BufferedImage image = readImage(imageData);
        if (image.getWidth() > maxDimension || image.getHeight() > maxDimension) {

            // Save existing metadata, if any
            TiffImageMetadata metadata = readExifMetadata(imageData);
            imageData = null; // allow immediate GC

            // resize 
            image = Scalr.resize(image, maxDimension);

            // rewrite resized image as byte[]
            byte[] resizedData = writeJPEG(image);
            image = null; // allow immediate GC 

            // Re-code resizedData + metadata to imageData 
            if (metadata != null) {
                this.imageData = writeExifMetadata(metadata, resizedData);
            } else {
                this.imageData = resizedData;
            }
        }
    }

    private TiffImageMetadata readExifMetadata(byte[] jpegData) throws ImageReadException, IOException {
        IImageMetadata imageMetadata = Imaging.getMetadata(jpegData);
        if (imageMetadata == null) {
            return null;
        }
        JpegImageMetadata jpegMetadata = (JpegImageMetadata)imageMetadata;
        TiffImageMetadata exif = jpegMetadata.getExif();
        if (exif == null) {
            return null;
        }
        return exif;
    }


    private byte[] writeExifMetadata(TiffImageMetadata metadata, byte[] jpegData) 
                                throws ImageReadException, ImageWriteException, IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        new ExifRewriter().updateExifMetadataLossless(jpegData, out, metadata.getOutputSet());
        out.close();
        return out.toByteArray();
    }


    private BufferedImage readImage(byte[] data) throws IOException {
        return ImageIO.read(new ByteArrayInputStream(data));
    }

    private byte[] writeJPEG(BufferedImage image) throws IOException {
        ByteArrayOutputStream jpegOut = new ByteArrayOutputStream();
        ImageIO.write(image, "JPEG", jpegOut);
        jpegOut.close();
        return jpegOut.toByteArray();
    }

    public synchronized void writeJPEG(OutputStream outstream) throws IOException {
        IOUtils.write(imageData,  outstream);

    }

    public synchronized byte[] getJPEGData() {
        return imageData;
    }

}

Here is my solution using a combination of ImageIO, Imgscalr and Apache commons-imaging. It's a pity there's (May 2016) no single library which combines reading the image with its metadata , making this probably rather excessive on memory usage; Improvements welcome.

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import org.apache.commons.imaging.ImageReadException;
import org.apache.commons.imaging.ImageWriteException;
import org.apache.commons.imaging.Imaging;
import org.apache.commons.imaging.common.IImageMetadata;
import org.apache.commons.imaging.formats.jpeg.JpegImageMetadata;
import org.apache.commons.imaging.formats.jpeg.exif.ExifRewriter;
import org.apache.commons.imaging.formats.tiff.TiffImageMetadata;
import org.apache.commons.io.IOUtils;
import org.imgscalr.Scalr;


public class ImageData {

    private byte[] imageData;


    public ImageData(InputStream instream) throws IOException {
        imageData  = IOUtils.toByteArray(instream);
        instream.close();
    }


    public synchronized void resize(int maxDimension) throws IOException, ImageReadException, ImageWriteException {
        // Resize the image if necessary
        BufferedImage image = readImage(imageData);
        if (image.getWidth() > maxDimension || image.getHeight() > maxDimension) {

            // Save existing metadata, if any
            TiffImageMetadata metadata = readExifMetadata(imageData);
            imageData = null; // allow immediate GC

            // resize 
            image = Scalr.resize(image, maxDimension);

            // rewrite resized image as byte[]
            byte[] resizedData = writeJPEG(image);
            image = null; // allow immediate GC 

            // Re-code resizedData + metadata to imageData 
            if (metadata != null) {
                this.imageData = writeExifMetadata(metadata, resizedData);
            } else {
                this.imageData = resizedData;
            }
        }
    }

    private TiffImageMetadata readExifMetadata(byte[] jpegData) throws ImageReadException, IOException {
        IImageMetadata imageMetadata = Imaging.getMetadata(jpegData);
        if (imageMetadata == null) {
            return null;
        }
        JpegImageMetadata jpegMetadata = (JpegImageMetadata)imageMetadata;
        TiffImageMetadata exif = jpegMetadata.getExif();
        if (exif == null) {
            return null;
        }
        return exif;
    }


    private byte[] writeExifMetadata(TiffImageMetadata metadata, byte[] jpegData) 
                                throws ImageReadException, ImageWriteException, IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        new ExifRewriter().updateExifMetadataLossless(jpegData, out, metadata.getOutputSet());
        out.close();
        return out.toByteArray();
    }


    private BufferedImage readImage(byte[] data) throws IOException {
        return ImageIO.read(new ByteArrayInputStream(data));
    }

    private byte[] writeJPEG(BufferedImage image) throws IOException {
        ByteArrayOutputStream jpegOut = new ByteArrayOutputStream();
        ImageIO.write(image, "JPEG", jpegOut);
        jpegOut.close();
        return jpegOut.toByteArray();
    }

    public synchronized void writeJPEG(OutputStream outstream) throws IOException {
        IOUtils.write(imageData,  outstream);

    }

    public synchronized byte[] getJPEGData() {
        return imageData;
    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文