How to save android canvas as svg?

Is there a way to save android canvas as svg. I know how to save it as png / jpeg. Im currently saving it as jpeg. Here is the code I'm using now to save.

            Bitmap bitmap = canvas.getDrawingCache();
            String path = Environment.getExternalStorageDirectory().getAbsolutePath();
            File file = new File(path+"/image.jpg");
            FileOutputStream ostream;
            try {
                ostream = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
                Toast.makeText(getApplicationContext(), "image saved", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();


I want to save the canvas as svg?


source to share

1 answer

It's not clear if you mean you want to save the bitmap as SVG, or if you want to save the Canvas as SVG. They are not necessarily the same. From your code sample, it looks like you want to keep the bitmap.

Saving a bitmap

As Der Gollum said, saving the bitmap as SVG does nothing. SVG is a vector format. You can put a bitmap in SVG like in the following example (assuming a 640x480 image). SVG files are just XML, so you can create something like the following:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "">
<svg version="1.1" xmlns=""
     width="640px" height="480px">
  <image width="640" height="480"
         xlink:href="data:image/jpeg;base64,...base64 encoded image data here..."/>


You have an SVG file, but it's still just a bitmap. It looks like a JPEG image in a PDF file.

You can use tools for tracing a bitmap and creating vector images. But this is a tricky problem, and tools that do it (like "potrace") usually do not produce results that can be used without manual tuning.

Saving the canvas

Another thing you might want to pay attention to is recording Canvas 2D drawing commands (for example Canvas.drawRect()

) and creating an SVG file from it. It is technically possible, but I am not aware of any tool or library that exists that does this.



All Articles