views:

75

answers:

2

Hi,

I have two images and I want to multiply these two images together in C# as we multiply two layers in photoshop.

Thanks

A: 

Here I have a suggestion - I didn't test it, so sorry for any errors - I'm also assuming that both images have the same size and are greylevel.

Basically I'm multiplying the image A for the relative pixel percentage of image B.

You can try different formulas like:

int result = ptrB[0] * ( (ptrA[0] / 255) + 1); or int result = (ptrB[0] * ptrA[0]) / 255;

Never forget to check for overflow (above 255)

public void Multiply(Bitmap srcA, Bitmap srcB, Rectangle roi)
    {
        BitmapData dataA = SetImageToProcess(srcA, roi);
        BitmapData dataB = SetImageToProcess(srcB, roi);

        int width = dataA.Width;
        int height = dataA.Height;
        int offset = dataA.Stride - width;

        unsafe
        {
            byte* ptrA = (byte*)dataA.Scan0;
            byte* ptrB = (byte*)dataB.Scan0;

            for (int y = 0; y < height; ++y)
            {
                for (int x = 0; x < width; ++x, ++ptrA, ++ptrB)
                {
                    int result = ptrA[0] * ( (ptrB[0] / 255) + 1);
                    ptrA[0] = result > 255 ? 255 : (byte)result;
                }
                ptrA += offset;
                ptrB += offset;
            }
        }
        srcA.UnlockBits(dataA);         
        srcB.UnlockBits(dataB);         
    }

    static public BitmapData SetImageToProcess(Bitmap image, Rectangle roi)
    {
        if (image != null)
            return image.LockBits(
                roi,
                ImageLockMode.ReadWrite,
                image.PixelFormat);

        return null;
    }
Andres
A: 

I have found the method by which the layers are multiplied in photoshop or any other application.

Following is the formula that I have found on GIMP documentation. It says that

E=(M*I)/255

where M and I are the color component(R,G,B) values of the two layers. We have to apply this to every color component. E will be the resultant value for that color component.

If the color component values are >255 then it should be set to white i.e. 255 and if it is <0 then it should be set as Black i.e. 0

Vinod Maurya