tags:

views:

40

answers:

1

I am attempting to create clipping mask out of a PNG with an alpha channel by copying the alpha values from my PNG over another same sized image. All using LockBits and then UnlockBits. It appears that my channel is correctly being set but I don't see it being used in subsequent drawing operations.

In an attempt to simplify things as much as I can, I used virtually the same logic to only set the Red channel value in a single image but after saving the image, again, no change. If I step through the code, the Red channel valid is being correctly set. Here is that simplified code. Any comments or help is appreciated.

        var image = Image.FromFile(@"C:\imaging\image.jpg");
        image.LoadRed();
        image.Save(@"C:\imaging\output.jpg");

    // image.jpg and output.jpg are the same.
    // I would expect output to be washed over with lots of red but it isn't

   public static void LoadRed(this Image destination)
    {
        var destinationBitmap = new Bitmap(destination);

        const int blueChannel = 0;
        const int greenChannel = 1;
        const int redChannel = 2;
        const int alphaChannel = 3;

        var rec = new Rectangle(Point.Empty, destination.Size);

        var destinationData = destinationBitmap.LockBits(rec, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

        unsafe
        {
            byte* destinationPointer = (byte*)destinationData.Scan0.ToPointer();

            destinationPointer += redChannel;

            for (int i = rec.Width * rec.Height; i > 0; i--)
            {
                *destinationPointer = 255;
                destinationPointer += 4;
            }
        }

        destinationBitmap.UnlockBits(destinationData);
    }
+1  A: 

Your problem is related to the fact that you create a new Bitmap instance using the image given to your extension method as a parameter. Once the method is finished, though, you are saving the original image, not the modified bitmap.

Change your extension method to work on types of System.Drawing.Bitmap.

Jim Brissom
Ah yes. I just figured that out! I have been bashing my head on this one one and off for a couple of days. I was about to delete the question but you win! +1!
Andrew Robinson
Glad to hear that it finally works ;)
Jim Brissom