Thank you very much Graham! I did it.
If anyone else needs something like this, here is the complete code:
Image to byte[] (only for J2ME):
Code:
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.lcdui.Image;
public class ImageToByteArray {
public static byte[] getByteArray(Image img) {
byte[] bytes = null;
int width = img.getWidth();
int height = img.getHeight();
int[] pixels = new int[width * height];
img.getRGB(pixels, 0, width, 0, 0, width, height);
try {
// convert int[] to byte[]
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
// I suggest writing these first: you'll need them to convert back
dout.writeInt(width);
dout.writeInt(height);
// then the pixels
for (int i = 0; i < pixels.length; i++) {
dout.writeInt(pixels[i]);
}
bytes = bout.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
}
byte[] to Image (only for J2SE):
Code:
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.MemoryImageSource;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
public class ByteArrayToImage {
public static Image getImage(byte[] bytes) {
Image image = null;
try {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
DataInputStream dis = new DataInputStream(bais);
int w = dis.readInt();
int h = dis.readInt();
int[] pixels = new int[w * h];
for (int i = 0; i < pixels.length; i++) {
pixels[i] = dis.readInt();
}
image = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(w, h, pixels, 0, w));
} catch(IOException e) {
e.printStackTrace();
}
return image;
}
}