Java – can I tell bufferedimage what the original file type is?

In my code, I have a bufferedimage loaded with the imageio class, as shown below:

BufferedImage image = ImageIO.read(new File (filePath);

Later, I want to save it as a byte array, but imageio The write method requires me to choose GIF, PNG or JPG format to write my image (as described in the tutorial here)

I want to choose the same file type as the original image If the image was originally GIF, I don't want the overhead of saving it as PNG But if the image was originally PNG, I don't want to lose translucency and save it as JPG or GIF Is there any way to determine the original file format from bufferedimage?

I know I can simply parse the file path when I load the image to find the extension and save it for future use, but ideally I prefer to do this directly from bufferedimage

Solution

As @ jarrodroberson said, bufferedimage has no "format" (i.e. no file format, it does have one of several pixel formats, or pixel "layout") I don't know Apache Tika, but I think his solution is also feasible

However, if you prefer to use only imageio instead of adding new dependencies to your project, you can write the following:

ImageInputStream input = ImageIO.createImageInputStream(new File(filePath));

try {
    Iterator<ImageReader> readers = ImageIO.getImageReaders(input);

    if (readers.hasNext()) {
        ImageReader reader = readers.next();

        try {
            reader.setInput(input);

            BufferedImage image = reader.read(0);  // Read the same image as ImageIO.read

            // Do stuff with image...

            // When done,either (1):
            String format = reader.getFormatName(); // Get the format name for use later
            if (!ImageIO.write(image,format,outputFileOrStream)) {
                // ...handle not written
            }
            // (case 1 done)

            // ...or (2):
            ImageWriter writer = ImageIO.getImageWriter(reader); // Get best suitable writer

            try {
                ImageOutputStream output = ImageIO.createImageOutputStream(outputFileOrStream);

                try {
                    writer.setOutput(output);
                    writer.write(image);
                }
                finally {
                    output.close();
                }
            }
            finally {
                writer.dispose();
            }
            // (case 2 done)
        }
        finally {
            reader.dispose();
        }
    }
}
finally {
    input.close();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>