Image size getting decreased after converting it into byte[] using BufferedImage and ImageIO

后端 未结 2 1319
日久生厌
日久生厌 2021-01-24 00:23

I am converting an Image into byte[] using following code.

public static byte[] extractBytes (String ImageName) throws IOException {

   ByteArrayOutputStream b         


        
2条回答
  •  臣服心动
    2021-01-24 00:36

    When you call ImageIO.write(img, "jpeg", outputfile); the ImageIO library writes a jpeg image, using its own compression parameters. The output image appears to be more compressed than the input image. You can adjust the level of compression by changing the parameter in the call to jpegParams.setCompressionQuality below. The resulting file may be bigger or smaller than the original depending on the relative compression levels in each.

    public static ImageWriter getImageWriter() throws IOException {
        IIORegistry registry = IIORegistry.getDefaultInstance();
        Iterator services = registry.getServiceProviders(ImageWriterSpi.class, (provider) -> {
            if (provider instanceof ImageWriterSpi) {
                return Arrays.stream(((ImageWriterSpi) provider).getFormatNames()).anyMatch(formatName -> formatName.equalsIgnoreCase("JPEG"));
            }
            return false;
        }, true);
        ImageWriterSpi writerSpi = services.next();
        ImageWriter writer = writerSpi.createWriterInstance();
        return writer;
    }
    
    public static void main(String[] args) throws IOException {
        String filepath = "old.jpg";
        File outp = new File(filepath);
        System.out.println("Size of original image=" + outp.length());
        byte[] data = extractBytes(filepath);
        System.out.println("size of byte[] data=" + data.length);
        BufferedImage img = ImageIO.read(new ByteArrayInputStream(data));
        File outputfile = new File("new.jpg");
        JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(null);
        jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        jpegParams.setCompressionQuality(1f);
        ImageWriter writer = getImageWriter();
        outputfile.delete();
        try (final ImageOutputStream stream = createImageOutputStream(outputfile)) {
            writer.setOutput(stream);
            try {
                writer.write(null, new IIOImage(img, null, null), jpegParams);
            } finally {
                writer.dispose();
                stream.flush();
            }
        }
        System.out.println("size of converted image=" + outputfile.length());
    }
    

    This solution is adapted from the answer by JeanValjean given here Setting jpg compression level with ImageIO in Java

提交回复
热议问题