How to parse a vector drawable pulled out from server to View?

Viewed 898

In general vector drawables are compiled, and accessed with their ids in execution time.

My project consist of pulling out images from a server. For now, i'm doing it for png files, but i would try it with vectors ".xml".

I'm able to download those, but i can't parse them in drawable type to show them in views.

How can i do this with a bunch of bytes representing the vectors resources and parsing them to drawables ?

It would be a huge thing for my app since it will be much much lighter, and good for those pixelized pictures.

2 Answers

The inflate method may be helpful, but you could use a third party library:androidsvg. Don't reproduce the wheel if possible.

If you can access the image from the server via url, use Glide to load it to your View. By so doing, you don't have to download the image to your storage before using it in an ImageView. However, if you still want to get the image as a byte array and display it in a view, use the code snippet below...

Bitmap bm = BitmapFactory.decodeFile("/path/to/yourimage.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object   
byte[] b = baos.toByteArray(); //This is the image byte
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT); //Encoded string

Furthermore, you can convert the string to a Bitmap and then pass it to your ImageView.

byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap bmp= BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
image.setImageBitmap(bmp);

Let me know if you have any question concerning this, I'd be glad to help.

Related