如何将jpg,位图格式的图像转换成矢量格式的c#
本文关键字:格式 转换 图像 jpg 位图 | 更新日期: 2023-09-27 18:15:02
我尝试将jpg图像转换为矢量格式。我试图实现这段代码,但它是通过异常
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();
}
exception is:A generic error occurred in GDI+.请验证我的代码,我做了错误。
代码不能工作:Afaik Metafile
构造函数期望一个流已经包含一些元文件数据(即'.wmf'-File)或为空(对于新的元文件)
你应该创建一个新的元文件,从中创建一个图形上下文,将jpeg图像加载到一个单独的Image
对象中,并在元文件上下文中绘制它。然后您可以将元文件保存为"。wmf文件。
我自己没有这样做,但是我在CodeProject上找到了一篇文章,其中解释了关于创建元文件的许多(棘手的)细节。
但是请注意,这不是一个"真正的"位图到向量的转换。它只是将位图嵌入到。wmf"容器。例如,如果你尝试调整它的大小,你会得到与原始jpeg-Image相同的结果(即没有"平滑"缩放)。我在我的应用程序中得到了相同的错误,问题是由于将文件写入磁盘而发生的
E:'Temp'file.wmf
检查文件的写权限!我的目录在网络中是映射内存,所以我必须用通行证和用户名连接目录。确保父目录存在,并确保路径包含文件名和扩展名。如果它不工作,尝试运行程序作为admin
public string Main(Bitmap image)
{
string str = "";
try
{
int width = image.Width;
int height = image.Height;
Graphics offScreenBufferGraphics;
Metafile m;
using (MemoryStream stream = new MemoryStream())
{
using (offScreenBufferGraphics = Graphics.FromImage(image))
{
IntPtr deviceContextHandle = offScreenBufferGraphics.GetHdc();
m = new Metafile(
stream,
deviceContextHandle,
new RectangleF(0, 0, width, height),
MetafileFrameUnit.Pixel,
EmfType.EmfPlusOnly);
offScreenBufferGraphics.ReleaseHdc();
}
}
using (Graphics g = Graphics.FromImage(m))
{
// Set everything to high quality and Draw image
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.CompositingQuality = CompositingQuality.HighQuality;
MetafileHeader metafileHeader = m.GetMetafileHeader();
g.ScaleTransform(
metafileHeader.DpiX / g.DpiX,
metafileHeader.DpiY / g.DpiY);
g.PageUnit = GraphicsUnit.Pixel;
g.SetClip(new RectangleF(0, 0, width, height));
Point ulCorner = new Point(0, 0);
g.DrawImage(image, 0, 0, width, height);
}
// Get a handle to the metafile
IntPtr iptrMetafileHandle = m.GetHenhmetafile();
// Export metafile to an image file
CopyEnhMetaFile(iptrMetafileHandle, @"c:''Ginko-Bilobatest1234.wmf");
str = "wmf image successfully generated.";
}
catch (Exception ex)
{
str = ex.InnerException + ex.Message;
}
return str;
// Delete the metafile from memory
// DeleteEnhMetaFile(iptrMetafileHandle);
}