c#将图片所有像素转为深色调

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用
public static Image ConvertToSepia(Image orginalImage)
{
    Bitmap newImage = new Bitmap(orginalImage);
    BitmapData orginalData = (orginalImage as Bitmap).LockBits(new Rectangle(0, 0, orginalImage.Width, orginalImage.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

    BitmapData newData = (newImage as Bitmap).LockBits(new Rectangle(0, 0, orginalImage.Width, orginalImage.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
    int orginalstride = orginalData.Stride;
    System.IntPtr orginalScan0 = orginalData.Scan0;

    int newstride = newData.Stride;
    System.IntPtr newScan0 = newData.Scan0;
    unsafe
    {
        byte* pOrginal = (byte*)(void*)orginalScan0;
        byte* pNew = (byte*)(void*)newScan0;

        int nOffset = orginalstride - orginalImage.Width * 3;

        byte red, green, blue;

        for (int y = 0; y < orginalImage.Height; ++y)
        {
            for (int x = 0; x < orginalImage.Width; ++x)
            {
                blue = pOrginal[0];
                green = pOrginal[1];
                red = pOrginal[2];

                int newRed = red * 393 / 1000 + green * 769 / 1000 + blue * 189 / 1000;
                int newGreen = red * 349 / 1000 + green * 686 / 1000 + blue * 168 / 1000;
                int newBlue = red * 272 / 1000 + green * 534 / 1000 + blue * 131 / 1000;
                newRed = Math.Min(newRed, 255);
                newGreen = Math.Min(newGreen, 255);
                newBlue = Math.Min(newBlue, 255);

                pNew[0] = Convert.ToByte(newBlue);
                pNew[1] = Convert.ToByte(newGreen);
                pNew[2] = Convert.ToByte(newRed);

                pOrginal += 3;
                pNew += 3;
            }
            pOrginal += nOffset;
            pNew += nOffset;
        }
    }
    (orginalImage as Bitmap).UnlockBits(orginalData);
    (newImage as Bitmap).UnlockBits(newData);
    return newImage;
}

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:洗牌算法

下一篇:linq to xml操作XML的c#代码