Stack Overflow archive
2 scoreaccepted

How to obtain Android Studio 1.5 menu image code as PNG file

score
2
question views
1.3K
license
CC BY-SA 3.0

This question is basically asking if it is possible to convert a raster image (PNG) to a vector graphic (VectorDrawable). There are many tools out there to do this but they all have limitations.

First, you should convert the PNG to a SVG. I have used ImageMagic in the past with fair results. For more options and information see these two StackOverflow posts:

ImageMagick png to svg Image Size

How to convert a PNG image to a SVG?

After you convert your PNG to a SVG, you can then use Android SVG to VectorDrawable.


If you want to convert an Android VectorDrawable to a PNG, you need to first convert the drawable to a SVG. I wrote a simple command-line tool (vector2svg) to do this. After you have the SVG there are many tools to convert the SVG to a PNG (just Google for one).

Edit: You can also save the VectorDrawable as a PNG on Android using the following method:

java
public static void vectorDrawableToPng(Context context, int drawableId, File file)
        throws IOException {
    final Drawable vectorDrawable = context.getResources().getDrawable(drawableId);
    // Convert the VectorDrawable to a Bitmap
    final Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
            vectorDrawable.getIntrinsicHeight(), Config.ARGB_8888);
    final Canvas canvas = new Canvas(bitmap);
    vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    vectorDrawable.draw(canvas);
    // Save the Bitmap as a PNG.
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(file, false);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.flush();
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
}

I don't recommend converting a PNG to a vector, but the above should answer the question.

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.