Actually, i've hit a snag with the new code Jeff posted above. The problem is that getScaledInstance(...) returns an image whereas i require a BufferedImage object because i later cast the image to this class and convert it to a jpeg using the code below:
BufferedImage bimg = null;
int w = image.getWidth(null);
int h = image.getHeight(null);
System.out.println("w: "+w+" h: "+h);
int[] pixels = new int[w * h];
PixelGrabber pg = new PixelGrabber(image, 0, 0, w, h, pixels, 0, w);
try {
pg.grabPixels();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
bimg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
bimg.setRGB(0, 0, w, h, pixels, 0, w);
// Encode as a JPEG
ByteArrayOutputStream bout = new ByteArrayOutputStream();
try {
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bout);
encoder.encode((BufferedImage)image);
//bout.close();
}catch(Exception e){
System.err.println("An error occured while trying to convert img to jpg:"+e);
}
byte[] ba = bout.toByteArray();
I was actually surprised to see this code work in the first place because image was meant to be initially an Image object but the BufferedImage cast was allowed to occur and the code seemed to work. Now that i have this line in my code:
image = image.getScaledInstance(w, h, Image.SCALE_AREA_AVERAGING);
i get a classCastException.
so i guess my question is whether there's another way to convert an image object into a jpeg without having to use a BufferedImage.
For background info, my code is meant to do this:
grab a screenshot (using Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); etc)
scale it to fit into a panel and disply it
convert the image into a jpeg and then into base64 format
this is turning out to be much more difficult than i first expected...
