.net 处理图片亮度

在网上搜索到一段代码,其中需要unsafe模式使用指针移动来操作修改图片数据!

重新修改使用Marshal类来替换处理unsafe代码段,代码如下 c++/cli,C#的直接按照语法修改下就可以了!

Bitmap^ UpdateImageLight(Bitmap^ bmp,int degree)
    {
        
if(bmp==nullptr)
            
return nullptr;
        
if(degree<-255
            degree
=-255;
        
if (degree>255
            degree
=255;
        
try{
            Rectangle rect 
= Rectangle(0,0,bmp->Width,bmp->Height);
            BitmapData
^ bmpData = bmp->LockBits( rect, ImageLockMode::ReadWrite,PixelFormat::Format24bppRgb);//24位rgb模式,一个像素点有3 byte数据
            IntPtr ptr = bmpData->Scan0; //bmpData数据段首地址
            int bytes = bmpData->Stride * bmp->Height;
            array
<Byte>^rgbValues = gcnew array<Byte>(bytes);
            System::Runtime::InteropServices::Marshal::Copy( ptr, rgbValues, 
0, bytes ); //复制ptr指针开始的 bytes大小数据到 rgbValue
            int offset = bmpData->Stride - bmp->Width * 3;
            
int k = 0,pix=0;
            
for (int y = 0; y < bmp->Height; y++)
            {
                
for (int x = 0; x < bmp->Width; x++)
                {
                    
// 处理指定位置像素的亮度
                    for (int i = 0; i < 3; i++)
                    {
                        pix 
= rgbValues[k+i] + degree;
                        
if (degree < 0) rgbValues[k+i] = (Byte)Math::Max(0, pix);
                        
if (degree > 0) rgbValues[k+i] = (Byte)Math::Min(255, pix);
                    }
                    k 
+= 3
                }
                k 
+= offset;
            }
            System::Runtime::InteropServices::Marshal::Copy( rgbValues, 
0, ptr, bytes );//处理过的数据复制回原地址
            bmp->UnlockBits(bmpData);
            
return bmp;
        }
        
catch(Exception^ ex)
        {
            
return nullptr;
        }
    }
原文地址:https://www.cnblogs.com/cxwx/p/1791722.html