简体   繁体   中英

Multiply two images in C# as multiply two layers in Photoshop

我有两个图像,我想在C#中将这两个图像相乘在一起,因为我们在Photoshop中相乘了两个图层。

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 ie 255 and if it is <0 then it should be set as Black ie 0

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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM