Search code examples
c#image-processingbitmapargb

Convert ARGB to PARGB


I've been looking for a fast alternative method of SetPixel() and I have found this link : C# - Faster Alternatives to SetPixel and GetPixel for Bitmaps for Windows Forms App

So my problem is that I've an image and I want to create a copy as a DirectBitmap object but first I need to convert ARGB to PARGB so I used this code:

    public static Color PremultiplyAlpha(Color pixel)
    {
        return Color.FromArgb(
            pixel.A,
            PremultiplyAlpha_Component(pixel.R, pixel.A),
            PremultiplyAlpha_Component(pixel.G, pixel.A),
            PremultiplyAlpha_Component(pixel.B, pixel.A));
    }

    private static byte PremultiplyAlpha_Component(byte source, byte alpha) 
    { 
        return (byte)((float)source * (float)alpha / (float)byte.MaxValue + 0.5f); 
    }

and Here's my copy code:

    DirectBitmap DBMP = new DirectBitmap(img.Width, img.Height);
        MyImage myImg = new MyImage(img as Bitmap);

        for (int i = 0; i < img.Width; i++)
        {
            for (int j = 0; j < img.Height; j++)
            {
                Color PARGB = NativeWin32.PremultiplyAlpha(Color.FromArgb(myImg.RGB[i, j].Alpha, 
                    myImg.RGB[i, j].R, myImg.RGB[i, j].G, myImg.RGB[i, j].B));

                byte[] bitMapData = new byte[4];
                bitMapData[3] = (byte)PARGB.A;
                bitMapData[2] = (byte)PARGB.R;
                bitMapData[1] = (byte)PARGB.G;
                bitMapData[0] = (byte)PARGB.B;


                DBMP.Bits[(i * img.Height) + j] = BitConverter.ToInt32(bitMapData, 0);
            }
        }

MyImage : a class containing a Bitmap object along with an array of struct RGB storing the colors of each pixel

However, this code gives me a messed up image. what am I doing wrong?


Solution

  • Bitmap data is organized horizontal line after horizontal line. Therefore, your last line should be:

    DBMP.Bits[j * img.Width + i] = BitConverter.ToInt32(bitMapData, 0);