Category >> Real Methods  

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

In this tutorial, I will show you two different ways to convert an image to a byte array and convert a byte array to an image.

First of all, the byte type in Java is an 8-bit signed two's complement integer. Its range is [-128, 127]. A byte array is just an array of bytes. An image is essentially a file. So the task is converting the file to an array so that it can be stored or transferred more easily in different kinds of applications.

1. Method 1

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 {
    	/*
    	 * 1. How to convert an image file to  byte array?
    	 */
 
        File file = new File("C:\\rose.jpg");
 
        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.
 
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                //Writes to this byte array output stream
                bos.write(buf, 0, readNum); 
                System.out.println("read " + readNum + " bytes,");
            }
        } catch (IOException ex) {
            Logger.getLogger(ConvertImage.class.getName()).log(Level.SEVERE, null, ex);
        }
 
        byte[] bytes = bos.toByteArray();
 
        /*
         * 2. How to convert byte array back to an image file?
         */
 
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg");
 
        //ImageIO is a class containing static methods for locating ImageReaders
        //and ImageWriters, and performing simple encoding and decoding. 
 
        ImageReader reader = (ImageReader) readers.next();
        Object source = bis; 
        ImageInputStream iis = ImageIO.createImageInputStream(source); 
        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);
 
        System.out.println(imageFile.getPath());
    }
}

2. Method 2

The following is a simpler version which does the same thing. It uses the BufferedImage class, which is a proved more efficient way.

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
 
 
public class SimpleConvertImage {
	public static void main(String[] args) throws IOException{
		String dirName="C:\\";
		ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
		BufferedImage img=ImageIO.read(new File(dirName,"rose.jpg"));
		ImageIO.write(img, "jpg", baos);
		baos.flush();
 
		String base64String=Base64.encode(baos.toByteArray());
		baos.close();
 
		byte[] bytearray = Base64.decode(base64String);
 
		BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytearray));
		ImageIO.write(imag, "jpg", new File(dirName,"snap.jpg"));
	}
}

3. Download Links

You can download the code of method 1 and method 2.

Category >> Real Methods  
  • http://notoriouszeus.tumblr.com/ NotoriousZeus

    import com.sun.org.apache.xerces.internal.impl.dv.util.Base64

  • http://notoriouszeus.tumblr.com/ Notorious Zeus

    Yes.

  • Namrata

    Can we convert byte array to audio file??

  • Issac

    May i know what is the library for apache base64??

  • Mohammad Imdad Sadi

    hello, i have a project on editing images by first converting them to byte arrary, so if you could help me out with which editor should i be using for this? I ‘ll need to save the image as well as the array to access it later on.

  • Pingback: How does ImageIO determine the dimension of images?CopyQuery CopyQuery | Question & Answer Tool for your Technical Queries,CopyQuery, ejjuit, query, copyquery, copyquery.com, android doubt, ios question, sql query, sqlite query, nodejsquery, dns query

  • JD

    Hi, When i convert a bytearray to jpg, the image is created but with empty contents. the bytes are not written to the image

  • Hema

    If i have a gif animated file means,how can i convert it to byte array and again i have to convert into gif file.

  • 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