75

I want to convert an image to byte array and vice versa. Here, the user will enter the name of the image (.jpg) and program will read it from the file and will convert it to a byte array.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
userv
  • 2,527
  • 4
  • 27
  • 36
  • 7
    Likely not a duplicate: The question asker means compressed image file to raster, not how to read compressed bytes. – Alex I Aug 15 '15 at 07:52
  • 7
    Agree, this is *not* a duplicate of the marked question (at least not by referring to the accepted answer). Voting to reopen. – Harald K Aug 29 '15 at 13:35
  • 3
    This is not a duplicate, as `File` is very different from `Image`. – digit plumber Feb 05 '16 at 23:31

9 Answers9

84

If you are using JDK 7 you can use the following code..

import java.nio.file.Files;
import java.io.File;

File fi = new File("myfile.jpg");
byte[] fileContent = Files.readAllBytes(fi.toPath())
Darryl
  • 859
  • 6
  • 4
72

BufferedImage consists of two main classes: Raster & ColorModel. Raster itself consists of two classes, DataBufferByte for image content while the other for pixel color.

if you want the data from DataBufferByte, use:

public byte[] extractBytes (String ImageName) throws IOException {
 // open image
 File imgPath = new File(ImageName);
 BufferedImage bufferedImage = ImageIO.read(imgPath);

 // get DataBufferBytes from Raster
 WritableRaster raster = bufferedImage .getRaster();
 DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();

 return ( data.getData() );
}

now you can process these bytes by hiding text in lsb for example, or process it the way you want.

rb512
  • 6,880
  • 3
  • 36
  • 55
Wajdy Essam
  • 4,280
  • 3
  • 28
  • 33
  • if the image is backen by a short array (which was the case for me and a tif image) it will give you a DataBufferShort resulting in a cast exception – Karussell Jun 21 '14 at 08:55
  • for this classes do i need any extra jars? – praveen Jun 30 '14 at 05:36
  • No, in Eclipse just use Ctrl + Shift + o. – RichardK Feb 03 '15 at 08:54
  • 12
    Sorry, but this answer is nonsense. Getting bytes from an image file is not different from getting bytes from an arbitrary file. You don't need Java 2D API for this at all. This approach is clumsy and would only be necessary when you're **actually interested** in manipulating the image in some way (resizing, cropping, colorizing, etc). Just use `Files#readAllBytes()` or any other sane way you'd usually use on any arbitrary file. – BalusC May 10 '15 at 17:21
  • 5
    the context for image processing. – Wajdy Essam Aug 15 '15 at 15:59
  • How do you convert the bytes back to an image after I have process them ? – mp3por Feb 14 '16 at 13:54
  • @BalusC How to check the content of an arbitrary fils is actually an image? Not mp3? – Jin Kwon Jun 02 '23 at 08:30
34
File fnew=new File("/tmp/rose.jpg");
BufferedImage originalImage=ImageIO.read(fnew);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ImageIO.write(originalImage, "jpg", baos );
byte[] imageInByte=baos.toByteArray();
user717325
  • 359
  • 3
  • 4
7

Try this code snippet

BufferedImage image = ImageIO.read(new File("filename.jpg"));

// Process image

ImageIO.write(image, "jpg", new File("output.jpg"));
Rakesh
  • 4,264
  • 4
  • 32
  • 58
McK
  • 221
  • 2
  • 4
6

Here is a complete version of code for doing this. I have tested it. The BufferedImage and Base64 class do the trick mainly. Also some parameter needs to be set correctly.

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"));
    }
}

Reference link

Ryan
  • 2,825
  • 9
  • 36
  • 58
3

Check out javax.imageio, especially ImageReader and ImageWriter as an abstraction for reading and writing image files.

BufferedImage.getRGB(int x, int y) than allows you to get RGB values on the given pixel, which can be chunked into bytes.

Note: I think you don't want to read the raw bytes, because then you have to deal with all the compression/decompression.

b_erb
  • 20,932
  • 8
  • 55
  • 64
2

Using RandomAccessFile would be simple and handy.

RandomAccessFile f = new RandomAccessFile(filepath, "r");
byte[] bytes = new byte[(int) f.length()];
f.read(bytes);
f.close();
Gowtham
  • 11,853
  • 12
  • 43
  • 64
1

java.io.FileInputStream is what you're looking for :-)

Vanya
  • 3,091
  • 2
  • 18
  • 12
0

I think the best way to do that is to first read the file into a byte array, then convert the array to an image with ImageIO.read()

Maurice Perry
  • 32,610
  • 9
  • 70
  • 97