Java: convert image to byte array, convert byte array to image

Convert image to byte array

If you want to convert an image to a byte array, and then convert the byte array back to image, this is the code.

This program was initially for a centralized file upload and management system, which uses Web Service to do file transfer. Although Web Service is not good for transferring large files, images are normally smaller, and therefore may work this way. On one side, the image is converted to an array of bytes, and sent to the other side. Then the other side converts the byte array back to the image.

If you are interested in transferring images using Web Service, Please read my previous post about this topic. Here is a post about the solution of using Web Service to transfer files.

You can download the code here or copy the code below.

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
 
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
 
public class ConvertImage {
 
    public static void main(String[] args) throws FileNotFoundException, IOException {
    	/*
    	 * In this function the first part shows how to convert an image file to 
    	 * byte array. The second part of the code shows how to change byte array
    	 * back to a image.
    	 */
        File file = new File("C:\\rose.jpg");
        System.out.println(file.exists() + "!!");
 
        FileInputStream fis = new FileInputStream(file);
        //create FileInputStream which obtains input bytes from a file in a file system
        //FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.
 
        //InputStream in = resource.openStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum); 
                //no doubt here is 0
                /*Writes len bytes from the specified byte array starting at offset 
                off to this byte array output stream.*/
                System.out.println("read " + readNum + " bytes,");
            }
        } catch (IOException ex) {
            Logger.getLogger(ConvertImage.class.getName()).log(Level.SEVERE, null, ex);
        }
        byte[] bytes = bos.toByteArray();
        //bytes is the ByteArray we need
 
        /*
         * The second part shows how to convert byte array back to an image file  
         */
 
        //Before is how to change ByteArray back to Image
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg");
        //ImageIO is a class containing static convenience methods for locating ImageReaders
        //and ImageWriters, and performing simple encoding and decoding. 
 
        ImageReader reader = (ImageReader) readers.next();
        Object source = bis; // File or InputStream, it seems file is OK
 
        ImageInputStream iis = ImageIO.createImageInputStream(source);
        //Returns an ImageInputStream that will take its input from the given Object
 
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
 
        Image image = reader.read(0, param);
        //got an image file
 
        BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
        //bufferedImage is the RenderedImage to be written
        Graphics2D g2 = bufferedImage.createGraphics();
        g2.drawImage(image, null, null);
        File imageFile = new File("C:\\newrose2.jpg");
        ImageIO.write(bufferedImage, "jpg", imageFile);
        //"jpg" is the format of the image
        //imageFile is the file to be written to.
 
        System.out.println(imageFile.getPath());
    }
}

Here is a simple version which has exactly the same function. It uses the BufferedImage class, which is a proved more efficient way.

Related Articles:

  • Sulekha Sharmila

    sir…im doing final year project on face recognition so i want to convert the image of jpeg form to pgm form in java..so can you please help us sir…If you help us it wil be so useful for us…

  • Neetha

    Hi, I tried this code with Jpg, it works perfectly. But with .bmp this is not working. I need to convert a .bmp image to base64 and vice-versa. Is there a different way to handle to .bmp images…pls reply asap. thanks.

  • raji

    sir.. i want one program for getting the image and convert that pixels values and stored in the array format.. please sent the java program coding to this mail…
    raji17.k@gmail.com

  • govind

    sir. . i want java code for converting any color image to matrix form of image data.
    this matrix will use for applying further matrx operation. . . so please give me the java code foe matrix cinversion from the image. . plz send to my mail…

    govind.satyam@gmail.com

  • kartheek

    can you please tell me the software which is used to
    execute the program while connecting to the arm processor

  • Diego

    why the fuck does it only work with .gif

  • Ankit

    Thank you very much sir.. U have solved my problem by giving this tutorial. I am very much thankful to you..

  • Admin

    What do you mean by “comments parts”?

  • nik

    I want to extract comments parts from the image,
    can u tell me how it is possible?
    Thanx in advance

  • kapil

    package com.teli.Image;

    /*
    *kapil katiyar
    *telibrhama
    *INDIAN
    */

    import java.io.ByteArrayOutputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import javax.microedition.lcdui.Image;

    public class PNGEncoder {
    private static final byte[] SIGNATURE = new byte[]
    {
    (byte) 137, (byte) 80, (byte) 78, (byte) 71,
    (byte) 13, (byte) 10, (byte) 26, (byte) 10
    };

    /**
    * Generate a PNG data stream from a pixel array.

    */
    public static byte[] toPNG(int width, int height, int[] argb, boolean processAlpha) throws IllegalArgumentException {
    ByteArrayOutputStream png;
    try {
    byte[] header = createHeaderChunk(width, height, processAlpha);
    byte[] data = createDataChunk(width, height, argb, processAlpha);
    byte[] trailer = createTrailerChunk();

    png = new ByteArrayOutputStream(SIGNATURE.length + header.length + data.length + trailer.length);
    png.write(SIGNATURE);
    png.write(header);
    png.write(data);
    png.write(trailer);
    } catch (IOException ioe)
    {
    // none of the code should ever throw an IOException
    throw new IllegalStateException(“Unexpected ” + ioe);
    }
    return png.toByteArray();
    }

    /**
    * Generate a PNG data stream from an Image object.
    * @param img source Image
    * @param processAlpha true if you want to keep the alpha channel data
    * @return PNG data in a byte[]
    */
    public static byte[] toPNG(Image img, boolean processAlpha) {
    int width = img.getWidth();
    int height = img.getHeight();
    int[] argb = new int[width * height];
    img.getRGB(argb, 0, width, 0, 0, width, height);
    // allow garbage collection, if this is the only reference
    img = null;
    return toPNG(width, height, argb, processAlpha);
    }

    private static byte[] createHeaderChunk(int width, int height, boolean processAlpha) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream(13);
    DataOutputStream chunk = new DataOutputStream(baos);
    chunk.writeInt(width);
    chunk.writeInt(height);
    chunk.writeByte(8); // Bitdepth
    chunk.writeByte(processAlpha ? 6 : 2); // Colortype ARGB or RGB
    chunk.writeByte(0); // Compression
    chunk.writeByte(0); // Filter
    chunk.writeByte(0); // Interlace
    return toChunk(“IHDR”, baos.toByteArray());
    }

    private static byte[] createDataChunk(int width, int height, int[] argb, boolean processAlpha) throws IOException, IllegalArgumentException {
    if (argb.length != (width * height)) {
    throw new IllegalArgumentException(“array size does not match image dimensions”);
    }
    int source = 0;
    int dest = 0;
    byte[] raw = new byte[(processAlpha ? 4 : 3) * (width * height) + height];
    for (int y = 0; y < height; y++) {
    raw[dest++] = 0; // No filter
    for (int x = 0; x > 16); // red
    raw[dest++] = (byte)(pixel >> 8); // green
    raw[dest++] = (byte)(pixel); // blue
    if (processAlpha) {
    raw[dest++] = (byte)(pixel >> 24); // alpha
    }
    }
    }
    return toChunk(“IDAT”, toZLIB(raw));
    }

    private static byte[] createTrailerChunk() throws IOException {

    return toChunk(“IEND”, new byte[] {});
    }

    private static byte[] toChunk(String id, byte[] raw) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream(raw.length + 12);
    DataOutputStream chunk = new DataOutputStream(baos);

    chunk.writeInt(raw.length);

    byte[] bid = new byte[4];
    for (int i = 0; i < 4; i++) {
    bid[i] = (byte) id.charAt(i);
    }

    chunk.write(bid);

    chunk.write(raw);

    int crc = 0xFFFFFFFF;
    crc = updateCRC(crc, bid);
    crc = updateCRC(crc, raw);
    chunk.writeInt(~crc);

    return baos.toByteArray();
    }

    private static int[] crcTable = null;

    private static void createCRCTable() {
    crcTable = new int[256];

    for (int i = 0; i < 256; i++) {
    int c = i;
    for (int k = 0; k 0) ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
    }
    crcTable[i] = c;
    }
    }

    private static int updateCRC(int crc, byte[] raw) {
    if (crcTable == null) {
    createCRCTable();
    }

    for (int i = 0; i >> 8);
    }

    return crc;
    }

    /*
    * This method is called to encode the image data as a zlib block as
    * required by the PNG specification. This file comes with a minimal ZLIB
    * encoder which uses uncompressed deflate blocks (fast, short, easy, but no
    * compression). If you want compression, call another encoder (such as
    * JZLib?) here.
    */
    private static byte[] toZLIB(byte[] raw) throws IOException {
    return ZLIB.toZLIB(raw);
    }
    }

    class ZLIB {
    private static final int BLOCK_SIZE = 32000;

    public static byte[] toZLIB(byte[] raw) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream(raw.length + 6
    + (raw.length / BLOCK_SIZE) * 5);
    DataOutputStream zlib = new DataOutputStream(baos);

    byte tmp = (byte) 8;
    zlib.writeByte(tmp); // CM = 8, CMINFO = 0
    zlib.writeByte( (31 – ( (tmp < BLOCK_SIZE)
    {
    writeUncompressedDeflateBlock(zlib, false, raw, pos, (char) BLOCK_SIZE);
    pos += BLOCK_SIZE;
    }

    writeUncompressedDeflateBlock(zlib, true, raw, pos, (char) (raw.length – pos));

    // zlib check sum of uncompressed data
    zlib.writeInt(calcADLER32(raw));

    return baos.toByteArray();
    }

    private static void writeUncompressedDeflateBlock(DataOutputStream zlib, boolean last,byte[] raw, int off, char len) throws IOException
    {
    zlib.writeByte((byte) (last ? 1 : 0)); // Final flag, Compression type 0
    zlib.writeByte((byte) (len & 0xFF)); // Length LSB
    zlib.writeByte((byte) ( (len & 0xFF00) >> 8)); // Length MSB
    zlib.writeByte((byte) (~len & 0xFF)); // Length 1st complement LSB
    zlib.writeByte((byte) ( (~len & 0xFF00) >> 8)); // Length 1st complement MSB
    zlib.write(raw, off, len); // Data
    }

    private static int calcADLER32(byte[] raw) {
    int s1 = 1;
    int s2 = 0;
    for (int i = 0; i = 0 ? raw[i] : (raw[i] + 256);
    s1 = (s1 + abs) % 65521;
    s2 = (s2 + s1) % 65521;
    }
    return (s2 << 16) + s1;
    }
    }

    //Use this there is method
    toPNG(Image img, boolean processAlpha);
    it must work

  • benjziegreat

    Thanks for the who made the code of converting images to bytes.As a student it can gives me a great help for my project.

  • http://Zg.hk ah

    :)
    ;)

  • isravel

    How you learnt java like this………………..?

  • Daison

    Thank you sir … I really expected this program for my project .

  • http://none same

    Thanks for sharing..

  • http://recipescookbook.org Salvi Pascual – recipescookbook.com

    Great piece of code! I am doing an scholar project and I am using your solution to transfer my images. Thanks for sharing with the community.

  • http://www.banffinfo.com/destinations/banff/ Banff holiday

    Such a great blog, I am really impressed, I am waiting for more interesting things on this blog

  • sk8terboi

    Thank you…. you’re life saver ;)

  • http://null Karthik Thayyil

    Ausome code!!!! I’m been searching for this since long .THanks a lot…there’s a small bug i ur code..
    in catch statement its genFile nt genJpeg

  • jenny

    thank u sooooo muc.it is really helpful for my projectwork.

  • admin

    What’s the error msg? Maybe the file path is not correct.

  • ques

    Hey I have been trying to use this code and I keep getting the error can’t read file?
    any help?

  • rp

    Hi , any one can tell me that how convet other data file to bmp image such as Word file , excel file etc. its urget pls help me !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    search convert file to image in this site.

  • Ramya

    Your code really helps,
    am trying to convert base64 data to jpg file,
    i have base64 data in database as string, i am passing it to java class as args[0], but this throws arrayindexoutofBoundsException
    here is my code

    String base64String=args[0];

    byte[] bytearray = Base64.decode(base64String);
    //Why use Base64 decode?

    BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytearray));
    ImageIO.write(imag, “jpg”, new File(dirName,”snap.jpg”));

  • admin

    Plug this conversion function to your web server, use its output as your transfer input.

  • admin

    I didn’t try that. but if so, I guess that’s the Java method problem.

  • Bhanuprasad

    hey u r very great developer, plz tell me how to do in webservices i am new to webservice

  • abhishek

    Great stuff,
    But the converted file of SimpleConvertImage is not as clear as that of ConvertImage, Could you please explain?
    Regards…

  • admin
  • cairne

    thanks very much for thhis code…
    But in the same way i’ve a question:
    “how convert byte array to files like pdf,doc,…?”
    tx..

  • http://www.milliontones.com ringtones

    Some days ago we downloaded some real ringtones with the help of the free ringtones company and used to be definitely satisfied.

  • jeeva

    than you sir…

  • Suril

    thnx..it helped me a lot..!!

  • http://puzzlesprint.com Rudy

    Absolutley new to java, althought love to read articles from witch I can learn

  • vidhya dharan

    Really nice tips..

    Keep continue mate.

    Thank you so much.

  • jitendra

    good job ….thanks for your help…
    yes …this world is because of helpful guys like you….

  • hussain

    really this s very help to me

    thanks to u..

    keep it up..

  • OD2

    Thank you sooooo much!

    This helped me decode an image byte array sent from flash. So awesome.

  • tripti

    thanks it really helps

  • MMB

    SA
    Hi Thank you for this declration

    am working on this class from two hour ago but i need to seprate store of image from creation method so i read image and convert it to byte array then decoded by base 64 then insert in file

    then terminate

    then run module to create image which read file then decode string by base 64 then ask for image io to write image i got nullpointer exception