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

8
如何将图片转换为图形?
5个回答

24

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

Graphics对象只是用于在画布上绘制的工具。这个画布通常是一个Bitmap对象或屏幕。

如果Graphics对象用于在Bitmap上进行绘制,则您已经拥有该图像。如果Graphics对象用于在屏幕上绘制,则需要截屏才能获得画布的图像。

如果Graphics对象是从窗口控件创建的,则可以使用控件的DrawToBitmap方法将控件渲染为图像而不是屏幕上的显示。


@Sorush:我已经修复了。(作为将来的参考,如果你想评论以便Hesam能够收到通知,你应该在问题上发表评论,而不是在回答上。) - Guffa

12

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

Graphics g = Graphics.FromImage(image);

1
这是与问题相反的情况:问题是:从图形到图像,而不是你所回答的从图像到图形。 - Tarek.Mh

12

正如Darin所说,你可能已经有了这张图片。如果没有,你可以创建一个新的并在其上进行绘制

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

Save将图像保存到硬盘上的文件中。


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

0
将图形转换为位图的最佳方法是摆脱“using”内容:
        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
        * 
        */

        //<Definitions>
        Size imageSize = new Size(400, 400);
        int minimumStars = 600;
        int maximumStars = 800;
        //</Definitions>

        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 <r.Next(minimumStars, maximumStars); i++)
        {
            int x = r.Next(1, imageSize.Width);
            int y = r.Next(1, imageSize.Height);
            b1.SetPixel(x, y, Color.WhiteSmoke);
        }
        pictureBox1.Image = b1;

    }

通过这段代码,您可以使用 Graphics 类的所有命令,并将它们复制到位图中,从而允许您保存使用 Graphics 类设计的任何内容。
您可以利用这一点。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接