hiii!! i want to convert an image to byte array and vice versa. here user will enter the name of the image(.jpg) and program will read it from the file and will convert it to byte array. thanks.. bye
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.
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()
BufferedImage image = ImageIO.read(new File("filename.jpg"));
// Process image
ImageIO.write(image, "jpg", new File("output.jpg"));
BufferedImage consists from two main classes (Raster & ColorModel), Raster itself consists from two classes, the one related to image content is DataBufferByte, the other class 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 hide text in lsb for example, or make any processing you want.