c#图片色阶调整、亮度调整

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);  
}  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章