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.
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();
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.
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"));
}
}
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())
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()
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();
Try this code snippet
BufferedImage image = ImageIO.read(new File("filename.jpg"));
// Process image
ImageIO.write(image, "jpg", new File("output.jpg"));
java.io.FileInputStream is what you're looking for :-)
Source: Stackoverflow.com