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

Convert image to byte arrayThere are some situations where we need to convert an image to a byte array. The following are the java code for converting an image to a byte array, and then convert byte array back to image. I have tested it under Java 1.5, please leave your comment, if there is any problem.

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 works this way. On one side, the image is converted to an array of bytes, and sent to the other side. Then the other side convert 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 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.

You may also like:

  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 .

Leave a comment