[英]Convert Image to Graphic in c#
如何將圖像轉換為圖形?
您無法將Graphics
對象轉換為圖像,因為Graphics
對象不包含任何圖像數據。
Graphics
對象只是用於在畫布上繪制的工具。 該畫布通常是Bitmap
對象或屏幕。
如果Graphics
對象用於在Bitmap
上繪圖,那么您已經擁有了該圖像。 如果使用Graphics
對象在屏幕上繪圖,則必須進行屏幕截圖才能獲得畫布的圖像。
如果Graphics
對象是從窗口控件創建的,則可以使用控件的DrawToBitmap
方法在圖像上而不是在屏幕上呈現控件。
你需要一個Image來繪制你的圖形,所以你可能已經有了圖像:
Graphics g = Graphics.FromImage(image);
如果直接在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.