How to convert jpg,bitmap format image into vector format in c#

Saroop Trivedi picture Saroop Trivedi · Nov 16, 2011 · Viewed 7k times · Source

I try to convert the jpg image into vector format.I try to implement this code but it's through the exeception

 public void Run()
        {
            Control c = new Control();           
            Graphics grfx = c.CreateGraphics();
           //ReadImage(ImageName) method return the Image to Byte Array
            MemoryStream ms = new MemoryStream(ReadImage(@"E:\Temp\1.jpg"));
            IntPtr ipHdc = grfx.GetHdc();
            Metafile mf = new Metafile(ms,ipHdc);
            grfx.ReleaseHdc(ipHdc);
            grfx.Dispose();
            grfx = Graphics.FromImage(mf);
            mf.Save(@"E:\Temp\file.wmf", ImageFormat.Wmf);//Get Exception on this line
            grfx.Dispose();
        }

Exeception is :A generic error occurred in GDI+. Please verify my code where i did the mistake. Thanks in Advance

Answer

MartinStettner picture MartinStettner · Nov 16, 2011

The code cannot work: Afaik the Metafile constructor expects a stream which already contains some metafile data (i.e. an '.wmf'-File) or is empty (for new metafiles)

You should create a new metafile, create a graphics context from it, load the jpeg image into a separate Image object and draw it on the metafile context. Then you can save the metafile as ".wmf" files.

I didn't do this myself, but i found an article on CodeProject which explains many of the (tricky) details about metafile creation.

Note however that this is not a "real" bitmap to vector conversion. It merely embeds the bitmap into an ".wmf" container. If you try to resize it for example, you'll get the same results as for the original jpeg-Image (i.e. no "smooth" scaling).