如何将图片转换为图形?
你无法将Graphics
对象转换为图像,因为Graphics
对象不包含任何图像数据。
Graphics
对象只是用于在画布上绘制的工具。这个画布通常是一个Bitmap
对象或屏幕。
如果Graphics
对象用于在Bitmap
上进行绘制,则您已经拥有该图像。如果Graphics
对象用于在屏幕上绘制,则需要截屏才能获得画布的图像。
如果Graphics
对象是从窗口控件创建的,则可以使用控件的DrawToBitmap
方法将控件渲染为图像而不是屏幕上的显示。
你需要一个图像来绘制你的图形,所以你可能已经有了这个图像:
Graphics g = Graphics.FromImage(image);
正如Darin所说,你可能已经有了这张图片。如果没有,你可以创建一个新的并在其上进行绘制
Image bmp = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bmp)) {
// draw in bmp using g
}
bmp.Save(filename);
Save将图像保存到硬盘上的文件中。
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;
}