Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert image to byte array in java? [duplicate]

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.

like image 462
userv Avatar asked Jul 09 '10 08:07

userv


2 Answers

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()) 
like image 105
Darryl Avatar answered Oct 06 '22 12:10

Darryl


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.

like image 35
Wajdy Essam Avatar answered Oct 06 '22 10:10

Wajdy Essam