writing image to byte-array


Ad

Advertisements

J

JScoobyCed

Georg said:
hi

how can i write an image into a byte-array?

best regards

Well... It depends what you mean by byte-array. Do you want the file
loaded in an array of byte ? Do you want the RGB equivalent array ?
For the first one:
<sniplet>
File myImageFile = new File("path_to_image.jpg");
FileInputStream fis = new FileInputStream(myImageFile);
byte[] data = new byte[1024];
byte[] tmp = new byte[0];
byte[] myArrayImage = new byte[0];
int len = 0 ;
int total = 0;
while( (len = fis.read(data)) != -1 ) {
total += len;
tmp = myArrayImage;
myArrayImage = new byte[total];
System.arraycopy(tmp,0,myArrayImage,0,tmp.length);
System.arraycopy(data,0,myArrayImage,tmp.length,len);
}
fis.close();
</sniplet>
Note: this might not be the most efficient way... But that does the job.

For the array of RGB values:
<sniplet>
Image img = getImage();
BufferedImage bu = new BufferedImage(img.width,
img.height,BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bu.createGraphics();
g2.drawImage(img,0,0,this); // this referes to the current
//ImageObserver
g2.dispose();
int[] rgb = bu.getRGB(0, 0, img.width, img.height, null, 1);
</sniplet>

You can have a look at the BufferedImage in the javadoc.
 
Ad

Advertisements

D

Dave Neary

Hi,

how can i write an image into a byte-array?

BufferedImage img = ImageIO.read(inputFile);
ByteArrayOutputStream bas =
new ByteArrayOutputStream();
ImageIO.write(img, "pnm", bas);
byte[] data = bas.toByteArray();

This might not be what you want, though...

Cheers,
Dave.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top