如何在 C# 中引用图片
在 C# 中引用图片有多种方法,具体取决于应用程序类型和所用控件。
最常用的方法是使用
Image类,它可以从文件或资源中加载图像。以下是引用图像的步骤:
声明 Image
对象:
<code class="c#">Image myImage;</code>加载图像:
从文件加载:
<code class="c#">myImage = Image.FromFile("image.png");</code>
从资源加载:
<code class="c#">myImage = Image.FromStream(typeof(MyApplication).Assembly.GetManifestResourceStream("MyNamespace.image.png"));</code>
使用图像:
显示图像:
<code class="c#">pictureBox1.Image = myImage;</code>
绘制图像:
<code class="c#">Graphics g = this.CreateGraphics(); g.DrawImage(myImage, new Point(0, 0));</code>
另一种方法是使用
Bitmap类,它允许直接操作图像像素。
声明 Bitmap
对象:
<code class="c#">Bitmap myBitmap;</code>加载或创建图像:
从文件加载:
<code class="c#">myBitmap = new Bitmap("image.png");</code>
创建新图像:
<code class="c#">myBitmap = new Bitmap(100, 100);</code>使用图像:
显示图像:
<code class="c#">pictureBox1.Image = myBitmap;</code>
操作像素:
<code class="c#">// 获得像素颜色 Color pixelColor = myBitmap.GetPixel(10, 10); // 设置像素颜色 myBitmap.SetPixel(10, 10, Color.Red);</code>
