溫馨提示×

c# drawimage顏色如何設置

c#
小樊
100
2024-11-24 21:25:10
欄目: 編程語言

在C#中,要使用System.Drawing命名空間中的DrawImage方法繪制圖像并設置顏色,你需要先創建一個Color對象來表示所需的顏色,然后將其應用到圖像上。以下是一個示例:

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

class Program
{
    static void Main()
    {
        // 加載圖像
        using (Image originalImage = Image.FromFile("path/to/your/image.jpg"))
        {
            // 創建一個新的Color對象,表示要應用的顏色(例如紅色)
            Color redColor = Color.Red;

            // 創建一個新的Bitmap對象,用于存儲應用顏色后的圖像
            using (Bitmap coloredImage = new Bitmap(originalImage.Width, originalImage.Height))
            {
                // 使用Graphics對象繪制原始圖像到新的Bitmap上
                using (Graphics g = Graphics.FromImage(coloredImage))
                {
                    // 設置繪制圖像時的背景顏色
                    g.Clear(Color.White);

                    // 繪制原始圖像到新的Bitmap上
                    g.DrawImage(originalImage, 0, 0);

                    // 創建一個ImageAttributes對象,用于設置顏色遮罩
                    ImageAttributes imageAttributes = new ImageAttributes();

                    // 創建一個ColorMatrix對象,表示要應用的顏色矩陣(在這種情況下,我們將其設置為紅色)
                    ColorMatrix colorMatrix = new ColorMatrix();
                    colorMatrix.Matrix3x2[0, 0] = 1;
                    colorMatrix.Matrix3x2[0, 1] = 0;
                    colorMatrix.Matrix3x2[1, 0] = 0;
                    colorMatrix.Matrix3x2[1, 1] = 1;
                    colorMatrix.Matrix3x2[2, 0] = 0;
                    colorMatrix.Matrix3x2[2, 1] = 0;

                    // 將顏色矩陣應用到ImageAttributes對象中
                    imageAttributes.SetColorMatrix(colorMatrix);

                    // 使用帶有顏色遮罩的Graphics對象繪制原始圖像到新的Bitmap上
                    g.DrawImage(originalImage, 0, 0, originalImage.Width, originalImage.Height, 0, 0, originalImage.Width, originalImage.Height, GraphicsUnit.Pixel, imageAttributes);

                    // 保存應用顏色后的圖像
                    coloredImage.Save("path/to/your/colored_image.jpg");
                }
            }
        }
    }
}

在這個示例中,我們首先加載了一個名為image.jpg的圖像,然后創建了一個新的Color對象(紅色)和一個新的Bitmap對象(coloredImage)。接下來,我們使用Graphics對象將原始圖像繪制到新的Bitmap上,并設置背景顏色為白色。然后,我們創建了一個ImageAttributes對象和一個ColorMatrix對象,并將顏色矩陣設置為紅色。最后,我們將顏色矩陣應用到ImageAttributes對象中,并使用帶有顏色遮罩的Graphics對象將原始圖像繪制到新的Bitmap上。最后,我們將應用顏色后的圖像保存為colored_image.jpg。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女