What is the best way to serialize an image (compatible with Swing) from Java to Android?
Solution 1
Here is the solution: Use BufferedImage
on Java side and convert it to byte array, then on the Android side, get the byte array and convert it to Bitmap
.
Java side:
public static byte[] imageToByteArray(BufferedImage image) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
return baos.toByteArray();
}
/*
public static BufferedImage byteArrayToImage(byte[] imageArray) throws IOException
{
return ImageIO.read(new ByteArrayInputStream(imageArray));
}
*/
Android side:
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inDither = true;
opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
byte[] imageByteArray = getImageByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length, opt);
imageView.setImageBitmap(bitmap);
Solution 2
Use ImageIO to write the image to "png" or "jpg". e.g. http://docs.oracle.com/javase/tutorial/2d/images/saveimage.html
Comments
-
Eng.Fouad almost 2 years
I'm developing an Android app which is a quiz. On the other hand, I'm developing a desktop tool that is based entirely on Swing. The desktop tool is used to inserts the quiz's questions and produces a serialized object file which contains all the questions on it. I used
java.awt.Image
to hold an image that is attached with a question.Unfortunately, when I've finished developing the desktop tool and go to the Android side, I figured out that Android has no
java.awt.Image
. So my question is, is there anyway to include thejava.awt.Image
within the Android app? or is there another class available in both Java and Android that deals with Image, besides supporting the Swing components? or at least, is there an alternative to solve the problem I've faced?Notes: You may wonder why I'm serializing the object and not just fetching the questions from XML or database. That's because, I have a need to have a tree data structure as categories of the questions; each category has list of questions beside a sub-category.
-
Eng.Fouad about 12 yearsI want to serialize the image not to save it as an image file.
-
japreiss about 12 yearsSaving an image as a file is serialization. Is there extra information in the
awt.Image
that you'd lose by saving to a common format? -
Eng.Fouad about 12 years@japreiss No. But I just want to attach every/some question with an image, so instead of saving a lot of image files, I think of using an image instance variable inside the question class that holds an actual image.
-
StanislavL about 12 yearsAdd custom serialization to your class. Make the image as transient but image binary content (byte array) should be serializable. Then restore it on android side.