繁体   English   中英

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

[英]Convert Image to Graphic in c#

如何将图像转换为图形?

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

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

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

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

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

Graphics g = Graphics.FromImage(image);

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

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
        * 
        */

        //<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 Class的所有命令,并将它们复制到位图,从而允许您保存使用图形类设计的任何内容。

您可以利用这个优势。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM