簡體   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