I know the image is valid because I can convert the IplImage to an Image and even draw it on a JPanel. But when I convert a byte array to an Image most of the time I get null reference to an Image. Look at this code below to get a picture what I am facing with and comments, questions, answers are all welcome and even tips are all welcome.
Image i = Convert.getImage(image);
byte[] buffer = Convert.getBytes(image);
Image i2 = Convert.getImage(buffer);
//i2 is a null reference and i is a valid image. i can be drawn but i2 is useless.
Convert class:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Security;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.ByteArrayInputStream;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
/**
*
* @author danny
*/
public final class Convert
{
public static Image getImage(IplImage image)
{
return image.getBufferedImage();
}
public static byte[] getBytes(IplImage image)
{
byte[] buffer;
BufferedImage bI = image.getBufferedImage();
buffer = ((DataBufferByte) (bI).getRaster().getDataBuffer()).getData();
return buffer;
}
public static String getString(byte[] buffer)
{
return new String(buffer);
}
public static Image getImage(byte[] buffer)
{
try
{
Image i = ImageIO.read(new ByteArrayInputStream(buffer));
return i;
}
catch (Exception e)
{
System.out.printf("Exception Message:\n%s", e.getMessage() );
return null;
}
}
}
Now some of you may ask why do I need as a byte array. Well because I need to send across a network.
Extra Things To Be Aware Of:
Update:
I have tried using the ToolKit class to create an image from a byte array. But it fails probably because it is not a JPEG or GIF. Although it does return a valid Image object the Image object is pointing to an image that is blank. Here is the code I was trying to use but failed to do so.
public static Image getImage(byte[] buffer)
{
try
{
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image i = toolkit.createImage(buffer);
return i;
}
catch (Exception e)
{
System.out.printf("Exception Message:\n%s", e.getMessage() );
return null;
}
}
DataBufferByte.getData will: "Returns the default (first) byte data array." The first bank that is. That seems an uncertain, incomplete way to get the bytes; especially on the way back. Besides there is the implementation dependent cast from DataBuffer to DataBufferByte.
ImageIO can write to an OutputStream, for instance to a ByteArrayOutputStream, of which you can take the bytes. And on the other side ImageIO can read it in again. That is not the pure only-pixel-data you had in mind, but fool-proof.