[英]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.