- 图像在现代社会被广泛使用,是数字时代我们捕捉和保存信息的基础。
对于开发人员来说,位图是读取和处理各种编程语言(包括 C#)中图像的最基本和最有用的工具。
在本教程中,我们将学习 C# 中的位图类。我们将讨论它提供的功能以及我们可以用来执行图像操作的方法和属性。这包括裁剪、调整大小、像素操作、调色板提取等。
C# 位图类
C# 中的“Bitmap”类封装了 GDI+ 位图,其中包含来自图形图像的像素数据和相关属性。因此,如果您需要处理像素驱动的图像,“Bitmap”类可以满足您的需求。
该类的语法如下:
public sealed class Bitmap : System. Drawing . Image
让我们探索如何使用此类处理图像。
加载图像
使用位图之前的第一步是将图像加载到应用程序中。我们可以使用“Bitmap”类并将路径传递给图像,如下例所示:
在本教程中,我们将学习 C# 中的位图类。我们将讨论它提供的功能以及我们可以用来执行图像操作的方法和属性。这包括裁剪、调整大小、像素操作、调色板提取等。
C# 位图类
C# 中的“Bitmap”类封装了 GDI+ 位图,其中包含来自图形图像的像素数据和相关属性。因此,如果您需要处理像素驱动的图像,“Bitmap”类可以满足您的需求。
该类的语法如下:
public sealed class Bitmap : System. Drawing . Image
让我们探索如何使用此类处理图像。
加载图像
使用位图之前的第一步是将图像加载到应用程序中。我们可以使用“Bitmap”类并将路径传递给图像,如下例所示:
using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap bitmap = new Bitmap("C:\\sample\\linuxhint\\telegram.png");
Console.WriteLine("Image Loaded Successfully!");
}
}
注意:这可能需要您在项目中安装System.Drawing.Common。
访问图像像素
为了操作加载的图像,我们需要处理像素数据。以下代码演示了如何获取图像的像素数据:
Color color = bitmap.GetPixel(1, 1);
Console.WriteLine($"Color of pixel at (1,1): {color}");
The “GetPixel” method allows us to retrieve the color of a specific pixel at the specified coordinates.
You can also use the SetPixel() method and specify the “x” and “y” coordinates and the color to the set.
Image Rotation
We can use the RotateFlip() method to rotate and flip a given image. For example, to rotate the image to 90 degrees without flipping, we can use the code as follows:
using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap bitmap = new Bitmap("C:\\sample\\linuxhint\\telegram.png");
bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
bitmap.Save("C:\\sample\\linuxhint\\telegram_rotated.png");
}
}
获取调色板
我们还可以使用“Bitmap”对象中的“Palette”属性获取给定图像的调色板。
例:
using System;
using System.Drawing;
using System.Drawing.Imaging;
class Program
{
static void Main()
{
Bitmap bitmap = new Bitmap("C:\\sample\\linuxhint\\telegram.png");
ColorPalette palette = bitmap.Palette;
Console.WriteLine("Color Palette:");
foreach (Color color in palette.Entries)
{
Console.WriteLine(color);
}
}
}
代码应提取并返回指定图像的调色板。
结论
在本教程中,我们学习了如何使用 C# 中的“Bitmap”类来读取和操作基于像素的图像。
1385

被折叠的 条评论
为什么被折叠?



