C# GDI中怎樣實(shí)現(xiàn)圖像處理

c#
小樊
81
2024-10-11 09:39:48
欄目: 編程語言

在C#的GDI+中實(shí)現(xiàn)圖像處理,你可以使用Bitmap類來創(chuàng)建、操作和保存圖像。以下是一些基本的圖像處理操作示例:

  1. 創(chuàng)建一個(gè)新的Bitmap對(duì)象:
Bitmap bmp = new Bitmap(width, height);
  1. 使用Graphics對(duì)象在Bitmap上繪制:
Graphics g = Graphics.FromImage(bmp);
g.DrawEllipse(Pens.Black, x, y, width, height);
  1. 保存Bitmap到文件:
bmp.Save("output.jpg", ImageFormat.Jpeg);
  1. 從文件加載Bitmap:
Bitmap loadedBmp = new Bitmap("input.jpg");
  1. 獲取Bitmap的寬度和高度:
int width = loadedBmp.Width;
int height = loadedBmp.Height;
  1. 修改像素值:

你可以通過LockBits方法鎖定Bitmap的像素?cái)?shù)據(jù),然后直接訪問和修改像素值。這是一個(gè)示例代碼,它將Bitmap的所有像素顏色設(shè)置為紅色:

BitmapData bmpData = loadedBmp.LockBits(
    new Rectangle(0, 0, loadedBmp.Width, loadedBmp.Height),
    ImageLockMode.ReadOnly,
    loadedBmp.PixelFormat);

int bytesPerPixel = Bitmap.GetPixelFormatSize(loadedBmp.PixelFormat) / 8;
int byteCount = bmpData.Stride * loadedBmp.Height;
byte[] pixels = new byte[byteCount];
IntPtr ptrFirstPixel = bmpData.Scan0;
Marshal.Copy(ptrFirstPixel, pixels, 0, pixels.Length);

for (int y = 0; y < loadedBmp.Height; y++)
{
    int currentLine = y * bmpData.Stride;
    for (int x = 0; x < loadedBmp.Width; x++)
    {
        int currentPixel = currentLine + x * bytesPerPixel;
        byte[] pixel = new byte[bytesPerPixel];
        Marshal.Copy(ptrFirstPixel + currentPixel, pixel, 0, bytesPerPixel);

        // 修改像素值,例如設(shè)置為紅色
        pixel[0] = 255; // 紅色通道
        pixel[1] = 0;   // 綠色通道
        pixel[2] = 0;   // 藍(lán)色通道

        Marshal.Copy(pixel, 0, ptrFirstPixel + currentPixel, bytesPerPixel);
    }
}

loadedBmp.UnlockBits(bmpData);

注意:上述代碼中的Marshal.CopyLockBits方法用于在原始像素?cái)?shù)據(jù)和內(nèi)存之間進(jìn)行數(shù)據(jù)傳輸。你需要根據(jù)你的需求來修改像素值。

這只是C# GDI+中圖像處理的一些基本示例。你可以使用更多的GDI+類和方法來實(shí)現(xiàn)更復(fù)雜的圖像處理功能,例如縮放、旋轉(zhuǎn)、裁剪、濾鏡效果等。

0