Code: Select all
public static byte[] imageToBytes(Image img) {
//scaled image to bytes
int width = img.getWidth();
int height = img.getHeight();
try {
int[] argb = new int[width * height];
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
try {
img.getRGB(argb, 0, width, 0, 0, width, height);
dout.writeInt(width);
dout.writeInt(height);
for (int i = 0; i < argb.length; i++) {
dout.writeInt(argb[i]);
}
return bout.toByteArray();
} catch (OutOfMemoryError ex) {
System.gc();
return "".getBytes();
}
} catch (Exception e) {
// this won't happen, because we're writing to a ByteArrayOutputStream
return "".getBytes();
}
}