Thanks for satisfying my curiosity...
And this can be used in other ways, like decoding a Base64 image from a Mime e-mail message, for example.
I tried and had the same issue... Actually, -1 in height and width means the image isn't loaded: "If the height is not yet known, this method returns -1 and the specified ImageObserver object is notified later."
After lot of experiments and searches on the Net, I found a solution:
import java.awt.Toolkit;
Image GetFromJPEG(byte[] jpegBytes)
{
Image jpegImage = null;
println("Jpeg data length: " + jpegBytes.length);
try
{
jpegImage = Toolkit.getDefaultToolkit().createImage(jpegBytes);
}
catch (Exception e)
{
println("Problem creating image: " + e.toString() + ": " + e.getMessage());
}
// Image isn't loaded yet, we have to wait for end of processing of the data
// Stupid way, I suppose I should use an ImageObserver...
float waitTime = 0;
while (jpegImage.getHeight(null) == -1)
{
delay(25); // Don't hog CPU!
waitTime += 0.025;
}
println("After " + int(waitTime) + "s, I get an image of width " +
jpegImage.getWidth(null) + " and height " + jpegImage.getHeight(null));
return jpegImage;
}
byte[] bytes = null;
Image img = null;
void setup()
{
noLoop();
try
{
InputStream in = new FileInputStream("D:/_PhiLhoSoft/Processing/Johnson.jpg");
int l = in.available();
println("L: " + l);
bytes = new byte[l];
in.read(bytes);
}
catch (Exception e)
{
println("Problem reading image: " + e.toString() + ": " + e.getMessage());
}
// Initial load
img = GetFromJPEG(bytes);
println(img.getClass().toString());
// sun.awt.image.ToolkitImage tki = (sun.awt.image.ToolkitImage) img;
// BufferedImage bi = tki.getBufferedImage();
// println(bi.getClass().toString());
size(img.getWidth(null), img.getHeight(null));
}
void draw()
{
// println(frameRate);
// arraycopy(b, c);
// injectHDT(c,dhtHeaders[0]+21+int(random(hdt[0].length-1)),byte(int(random(254))));
PImage pimg = new PImage(img);
image(pimg, 0, 0);
}
Notice the image is actually a sun.awt.image.ToolkitImage, a proprietary class which is deprecated... but still used, apparently, by the JVM. The problem is that I haven't found any API description of this class.
I solved that load delay issue by a simple loop, a cleaner way would be, probably, to make a class implementing the ImageObserver interface and wait for this class to be notified of the load.
In Processing, I chose the simpler way!
[EDIT] Improving a bit the code...