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  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. MMB on 2010-3-30

    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

  2. tripti on 2010-4-22

    thanks it really helps

  3. OD2 on 2010-5-3

    Thank you sooooo much!

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

  4. hussain on 2010-5-6

    really this s very help to me

    thanks to u..

    keep it up..

  5. jitendra on 2010-6-23

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

  6. vidhya dharan on 2010-6-25

    Really nice tips..

    Keep continue mate.

    Thank you so much.

  7. Rudy on 2010-7-2

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

  8. Suril on 2010-8-9

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

  9. jeeva on 2010-8-18

    than you sir…

  10. ringtones on 2010-8-30

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

  11. cairne on 2010-9-21

    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..

  12. admin on 2010-10-8
  13. abhishek on 2010-10-22

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

  14. Bhanuprasad on 2010-11-2

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

  15. admin on 2010-11-6

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

  16. admin on 2010-11-6

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

  17. Ramya on 2011-2-3

    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”));

  18. rp on 2011-2-4

    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.

  19. ques on 2011-2-26

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

  20. admin on 2011-2-27

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

  21. jenny on 2011-3-1

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

  22. Karthik Thayyil on 2011-8-19

    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

  23. sk8terboi on 2012-1-24

    Thank you…. you’re life saver 😉

  24. Banff holiday on 2012-1-27

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

  25. 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.

  26. same on 2012-2-3

    Thanks for sharing..

  27. Daison on 2012-2-3

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

  28. isravel on 2012-2-16

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

  29. ah on 2012-2-23

    🙂
    😉

  30. benjziegreat on 2012-2-25

    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.

  31. kapil on 2012-3-30

    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

  32. nik on 2012-5-24

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

  33. Admin on 2012-5-24

    What do you mean by “comments parts”?

  34. Ankit on 2012-6-26

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

  35. Diego on 2012-11-26

    why the fuck does it only work with .gif

  36. kartheek on 2012-12-18

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

  37. govind on 2013-1-10

    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…

    [email protected]

  38. raji on 2013-1-29

    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…
    [email protected]

  39. Neetha on 2013-2-10

    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.

  40. Sulekha Sharmila on 2013-3-4

    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…

  41. Hema on 2013-7-10

    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.

  42. JD on 2013-11-6

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

  43. […] entire source code is here, look at “Method […]

  44. Mohammad Imdad Sadi on 2014-2-13

    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.

  45. Issac on 2014-4-17

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

  46. Namrata on 2014-6-5

    Can we convert byte array to audio file??

  47. Notorious Zeus on 2014-7-17

    Yes.

  48. NotoriousZeus on 2014-7-17

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

  49. Harsha Madushan on 2014-9-26

    Wow thanks! I’ve lost more time for finding this you saved me. 😀

  50. Nishanth on 2014-10-17

    Thanks a lot…It helped me pretty much…

  51. mojahid on 2014-12-9

    how i can convert audio file to Byte array

  52. Arun on 2015-1-1

    can you please help me to show a tif byte array to image in html screen using javascript

  53. bilal on 2015-1-16

    String base64String = DatatypeConverter.printBase64Binary(baos.toByteArray());
    baos.close();
    byte[] bytearray = DatatypeConverter.parseBase64Binary(base64String);

  54. […] Java: convert image to byte array, … – package com.teli.Image; /* *kapil katiyar *telibrhama *INDIAN */ import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io … […]

  55. […] Java: convert image to byte array, … – 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 … […]

  56. […] Java: convert image to byte array, … – 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 … […]

  57. […] Java: convert image to byte array, … – 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 … […]

  58. […] Java: convert image to byte array, … – 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 … […]

  59. […] Java: convert image to byte array, … – 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 … […]

  60. […] Java: convert image to byte array, … – 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 … […]

  61. Ashish on 2016-7-22

    hi,we provide online training & video tutorial for soapui

    for free videos refer

    http://soapui-tutorial.com/soapui-tutorial/introduction-to-webservices/

  62. MD Shafikul Islam Sujon on 2016-10-24

    (Thanks)^n where n=1,2,3,………………..
    I have lost huge time for this! Again Thanks!

  63. akshata on 2016-11-30

    if i want to convert image into bmp to .iso how i can convert it??

  64. abdulmalik on 2017-7-29

    your code is a life saver

Leave a comment

*