Java

Convert array of bytes into image in Java SE

First we are going to detect the mimetype from bytes array and then save the bytes into an image file.

 

    /**
     * Save bytes array to image file
     * @param chunk 
     */
    public void Bytes2Image( byte[] chunk, String filename, String folder) {
        if(folder.charAt(folder.length()-1) != '/') folder += "/";
        BufferedImage image;
        String formatName = "jpg";
        try {
            ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(chunk));
            Iterator<ImageReader> iter=ImageIO.getImageReaders(iis);
            if (iter.hasNext()) {
                ImageReader reader = (ImageReader)iter.next();
                reader.setInput(iis);
                formatName = reader.getFormatName();
            }
            image = ImageIO.read( new ByteArrayInputStream( chunk ) );
            ImageIO.write(image, formatName, new File(folder+filename+"."+formatName.toLowerCase()));
        } catch (IOException ex) {
            System.err.println(ex.getMessage());
        }
    }

Example

Bytes2Image(myimagebytes, "my_image_file", "/path/to/images");