static void Main()
{
Bitmap aa = file2img("test.jpg");
Bitmap cc = img_color_gradation(aa,100,0,0);
img2file(cc, "test1.jpg");
}
色階調整代碼
public static unsafe Bitmap img_color_gradation(Bitmap src, int r, int g, int b)
{
int width = src.Width;
int height = src.Height;
Bitmap back = new Bitmap(width, height);
Rectangle rect = new Rectangle(0, 0, width, height);
//這種速度最快
BitmapData bmpData = src.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);//24位rgb顯示一個像素,即一個像素點3個字節,每個字節是BGR分量。Format32bppRgb是用4個字節表示一個像素
byte* ptr = (byte*)(bmpData.Scan0);
for (int j = 0; j < height; j++)
{
for (int i = 0; i < width; i++)
{
//ptr[2]爲r值,ptr[1]爲g值,ptr[0]爲b值
int red = ptr[2] + r; if (red > 255) red = 255; if (red < 0) red = 0;
int green = ptr[1] + g; if (green > 255) green = 255; if (green < 0) green = 0;
int blue = ptr[0] + b; if (blue > 255) blue = 255; if (blue < 0) blue = 0;
back.SetPixel(i, j, Color.FromArgb(red, green, blue));
ptr += 3; //Format24bppRgb格式每個像素佔3字節
}
ptr += bmpData.Stride - bmpData.Width * 3;//每行讀取到最後“有用”數據時,跳過未使用空間XX
}
src.UnlockBits(bmpData);
return back;
}
圖片讀取,和存儲函數
//圖片讀取
public static Bitmap file2img(string filepath)
{
Bitmap b = new Bitmap(filepath);
return b;
}
//圖片生成
public static void img2file(Bitmap b, string filepath)
{
b.Save(filepath);
}