Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to serialize an image (compatible with Swing) from Java to Android?

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 the java.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.

like image 331
Eng.Fouad Avatar asked Dec 21 '22 23:12

Eng.Fouad


2 Answers

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);
like image 72
Eng.Fouad Avatar answered Jan 25 '23 22:01

Eng.Fouad


Use ImageIO to write the image to "png" or "jpg". e.g. http://docs.oracle.com/javase/tutorial/2d/images/saveimage.html

like image 43
StanislavL Avatar answered Jan 25 '23 23:01

StanislavL