Jayadev
Jayadev

Reputation: 201

How to save android canvas as svg?

Is there any possible way to save the android canvas as svg. I know how to save it as png/jpeg. Im currently saving it as jpeg. Here is the code that I use now for saving.

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

I want the canvas to be saved as svg?

Upvotes: 3

Views: 2465

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101800

It is not clear whether you mean you want to save a Bitmap as an SVG, or you want to save a Canvas as an SVG. They are not necessarily the same things. From your sample code, it sounds like you mean to save a Bitmap.

Saving a bitmap

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

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

You have an SVG file, but it's still just a bitmap. It's the same as having a JPEG image in a PDF file.

It is possible to use tools to trace a bitmap and generate vector images. But that is a hard problem, and the tools that do it (like "potrace") don't usually produce results that can be used without manual tweaking.

Saving a Canvas

The other thing you might be referring to is recording Canvas 2D drawing commands (such as Canvas.drawRect() for example) and producing an SVG file from that. That is technically possible, but I am not aware of any tool or library that exists that does that.

Upvotes: 1

Related Questions