i have one problem when i convert image to byte[] and reverse:
I have 2 function convert image to byte[] as follow
public byte[] extractBytes2 (String ImageName) throws IOException {
File imgPath = new File(ImageName);
BufferedImage bufferedImage = ImageIO.read(imgPath);
WritableRaster raster = bufferedImage .getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
return ( data.getData() );
}
and
public byte[] extractBytes (String ImageName) throws IOException
{
Path path = Paths.get(ImageName);
byte[] data = Files.readAllBytes(path);
return data;
}
I will have byte[] byteArray
byteArray = extractBytes2("image/pikachu.png");
or
byteArray = extractBytes("image/pikachu.png");
when i convert byte[] to Image i use
Graphics g = panelMain.getGraphics();
Graphics2D g2D = (Graphics2D) g;
try {
InputStream in = new ByteArrayInputStream(byteArray);
BufferedImage image = ImageIO.read(in);
g2D.drawImage(image, 0, 0, GiaoDienChinh.this);
g2D.setPaint(Color.BLACK);
panelMain.setOpaque(true);
panelMain.paintComponents(g2D);
}
catch ( Exception e ) {
}
finally {
}
but i only draw with byteArray use function “extractBytes” not with “extractBytes2” !!!
Anyone can explain me how i can draw image with byteArray which got from “extractByte2”?
Thanks for all support!
Let’s start with the paint code.
ImageIO.read(in)is expecting a valid image format that one of it’s pluggable service provides knows how to read and convert to aBufferedImage.When you pass the byes from
extractBytes, you’re simply passing back an array of bytes that represents the actual image file. I’d be the same as sayingImage.read(new File("image/pikachu.png"))However, the data buffer returned from your
extractBytes2is returning a internal representation of the image data, which may not be “readable” byImageIO.UPDATED
Referenced from here
UPDATED
I had this wacky idea on the way home of how to convert a
BufferedImageto a byte array…The basic idea is to use
ImageIO.writeto write out theBufferedImageto aByteOutputStream…Here’s my test…