【问题标题】:Merge two images(Byte array format) to a single image with alpha将两个图像(字节数组格式)合并为具有 alpha 的单个图像
【发布时间】:2015-07-30 16:14:54
【问题描述】:

如何使用 alpha 掩码将两个字节数组图像合并到图像中。我想使用字节操作在其他带有 alpha 的图像之上添加一个图像。

字节数组图像如何实现?

【问题讨论】:

    标签: android image-processing bytearray alphablending


    【解决方案1】:

    考虑到您使用的是真彩色格式(此处为 32 位 - ARGB),您可以这样做。添加伪代码,使其对任何语言都有用(实际上用 Java 编写有点懒惰;))。

    Assuming Color Struct - 4 bytes per each color
    
    //Prefill with color information
    Color[] image1; 
    Color[] image2;
    
    Color[] composedImage;
    
    //For individual color components. Just normal blend equation.
    composedImage[i].r = (1-image2[i].a) * image1[i].r + image2[i].a * image2[i].r;
    composedImage[i].g = (1-image2[i].a) * image1[i].g + image2[i].a * image2[i].g;
    composedImage[i].b = (1-image2[i].a) * image1[i].b + image2[i].a * image2[i].b;
    
    
    //For final alpha
    composedImage[_i].a = image1[_i].a + image2[_i].a * (1 -_image1[_i].a); //This is just by observation.
    

    为了优化,

    1. 可以完全忽略为composedImage创建内存并覆盖任何一个输入图像(如果适合您的情况)。

    2. 预计算常用操作 例如:(1-image2[i].a)

    3. 如果您要在多个位置混合第二张图像,则使用预乘颜色值会更有意义并避免乘法运算。

    上面应该让你现在潜入! ^_^

    【讨论】:

      【解决方案2】:

      我有这个代码。您需要将图像转换为 Drawable 格式,但这很容易。

      只需传入一个资源对象和 2 个可绘制对象。

      public static Bitmap GetOverlayedImage(Resources res, Drawable img1, Drawable img2) {
          float den = res.getDisplayMetrics().density;
          int dip = (int) (80 * den + 0.5f);
          int sz = (int) (128 * den + 0.5f);
      
          Drawable[] layers = new Drawable[2];
          layers[0] = img1;
          layers[1] = img2;
      
          LayerDrawable layerDrawable = new LayerDrawable(layers);
          layerDrawable.setLayerInset(1, dip, dip, 0, 00);
      
          Bitmap b = Bitmap.createBitmap(sz, sz, Bitmap.Config.ARGB_8888);
          layerDrawable.setBounds(0, 0, sz, sz);
          layerDrawable.draw(new Canvas(b));
      
          return b;
      }
      

      【讨论】:

      • 我想要一些可以直接合并而不转换为 Drawbles/Bitmaps 的东西。由于在相机预览时使用此逻辑,我无法保留每次在 onDraw 中运行的重量级逻辑。如果我使用它,它会抛出异常。
      猜你喜欢
      • 2016-04-15
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多