5

我正在开发一个图片编辑工具,我需要在其中合并两个图像。大多数图像编辑工具(如 gimp)都使用PorterDuff 模式来合并或混合图像。我也在android中使用相同的方法。
由于 android 提供有限数量的 PorterDuff 模式,我无法达到预期的结果。所以,我正在考虑实现 android 中不包含的 PorterDuff 模式(重叠、强光、柔光、颜色燃烧、颜色减淡)。
问题是我不知道从哪里开始。因此,在这方面的任何参考或指导都将受到高度赞赏。

4

1 回答 1

3

这是在 android 中实现 Overlay PorterDuff 模式的方法:

public class MyPorterDuffMode
{

    public Bitmap applyOverlayMode(Bitmap srcBmp, Bitmap destBmp)
    {
        int width = srcBmp.getWidth();
        int height = srcBmp.getHeight();
        int srcPixels[] = new int[width * height];;
        int destPixels[] = new int[width * height];
        int resultPixels[] = new int[width * height];
        int aS = 0, rS = 0, gS = 0, bS = 0;
        int rgbS = 0;
        int aD = 0, rD = 0, gD = 0, bD = 0;
        int rgbD = 0;

        try
        {
            srcBmp.getPixels(srcPixels, 0, width, 0, 0, width, height);
            destBmp.getPixels(destPixels, 0, width, 0, 0, width, height);
            srcBmp.recycle();
            destBmp.recycle();
        }
        catch(IllegalArgumentException e)
        {
        }
        catch(ArrayIndexOutOfBoundsException e)
        {
        }

        for(int y = 0; y < height; y++)
        {
            for(int x = 0; x < width; x++)
            {
                rgbS = srcPixels[y*width + x];
                aS = (rgbS >> 24) & 0xff;
                rS = (rgbS >> 16) & 0xff;
                gS = (rgbS >>  8) & 0xff;
                bS = (rgbS      ) & 0xff;

                rgbD = destPixels[y*width + x];
                aD = ((rgbD >> 24) & 0xff);
                rD = (rgbD >> 16) & 0xff;
                gD = (rgbD >>  8) & 0xff;
                bD = (rgbD      )  & 0xff;

                //overlay-mode
                rS = overlay_byte(rD, rS, aS, aD);
                gS = overlay_byte(gD, gS, aS, aD);
                bS = overlay_byte(bD, bS, aS, aD);
                aS = aS + aD - Math.round((aS * aD)/255f);

                resultPixels[y*width + x] = ((int)aS << 24) | ((int)rS << 16) | ((int)gS << 8) | (int)bS;
            }
        }

        return Bitmap.createBitmap(resultPixels, width, height, srcBmp.getConfig());
    }



    // kOverlay_Mode
    int overlay_byte(int sc, int dc, int sa, int da) {
        int tmp = sc * (255 - da) + dc * (255 - sa);
        int rc;
        if (2 * dc <= da) {
            rc = 2 * sc * dc;
        } else {
            rc = sa * da - 2 * (da - dc) * (sa - sc);
        }
        return clamp_div255round(rc + tmp);
    }


    int clamp_div255round(int prod) {
        if (prod <= 0) {
            return 0;
        } else if (prod >= 255*255) {
            return 255;
        } else {
            return Math.round((float)prod/255);
        }
    }

}

注意:在提取位图时,将配置设置为 ARGB_8888,这很重要。
任何时候您想要进行图像混合或颜色处理,您都需要确保您处于 ARGB_8888 模式,而不是 RGB_565 模式。直到 2.3,android 通常会默认为 RGB_565 模式,除非你明确告诉它这样做以节省内存。

BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Config.ARGB_8888;
于 2012-11-06T11:02:31.247 回答