在c#中将图像转换为图形

如何将图像转换为图形?

你需要一个Image来绘制你的图形,所以你可能已经有了图像:

Graphics g = Graphics.FromImage(image); 

您无法将Graphics对象转换为图像,因为Graphics对象不包含任何图像数据。

Graphics对象只是用于在canvas上绘制的工具。 该canvas通常是Bitmap对象或屏幕。

如果Graphics对象用于在Bitmap上绘图,那么您已经拥有了该图像。 如果使用Graphics对象在屏幕上绘图,则必须进行屏幕截图才能获得canvas的图像。

如果Graphics对象是从窗口控件创建的,则可以使用控件的DrawToBitmap方法在图像上而不是在屏幕上呈现控件。

正如达林所说,你可能已经有了这个形象。 如果不这样做,您可以创建一个新的并绘制到那个

 Image bmp = new Bitmap(width, height); using (Graphics g = Graphics.FromImage(bmp)) { // draw in bmp using g } bmp.Save(filename); 

保存将图像保存到硬盘驱动器上的文件中。

如果直接在Control的图形上绘图,则可以创建一个与控件尺寸相同的新Bitmap,然后调用Control.DrawToBitmap()。 然而,更好的方法通常是从Bitmap开始,绘制其图形(如Darin所建议的),然后将位图绘制到Control上。

将图形转换为位图的最佳方法是摆脱“使用”的东西:

  Bitmap b1 = new Bitmap(Screen.PrimaryScreen.Bounds.Width,Screen.PrimaryScreen.Bounds.Height); Graphics g = Graphics.FromImage(b1); g.CopyFromScreen(0, 0, Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height)); b1.Save("screen.bmp"); 

我在弄清楚如何将图形转换为位图时发现了这一点,它就像一个魅力。

我有一些如何使用它的例子:

  //1. Take a screenshot Bitmap b1 = new Bitmap(Screen.PrimaryScreen.Bounds.Width,Screen.PrimaryScreen.Bounds.Height); Graphics g = Graphics.FromImage(b1); g.CopyFromScreen(0, 0, Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height)); b1.Save("screen.bmp"); //2. Create pixels (stars) at a custom resolution, changing constantly like stars private void timer1_Tick(object sender, EventArgs e) { /* * Steps to use this code: * 1. Create new form * 2. Set form properties to match the settings below: * AutoSize = true * AutoSizeMode = GrowAndShrink * MaximizeBox = false * MinimizeBox = false * ShowIcon = false; * * 3. Create picture box with these properties: * Dock = Fill * */ // Size imageSize = new Size(400, 400); int minimumStars = 600; int maximumStars = 800; // Random r = new Random(); Bitmap b1 = new Bitmap(imageSize.Width, imageSize.Height); Graphics g = Graphics.FromImage(b1); g.Clear(Color.Black); for (int i = 0; i  

使用此代码,您可以使用Graphics Class的所有命令,并将它们复制到位图,从而允许您保存使用图形类设计的任何内容。

您可以利用这个优势。