title: Optimizing Per Pixel Blending on Android Bitmaps
body: <p>I am trying to apply blend filters on two images (in this case HardLight). HardLight is not supported in the base Android library, so, I am doing it by hand on each pixel. The first run is working, but the speed is less than stellar. Generating a 500x500 image from a base 500x500 image and a 500x500 filter is taking way too long. This chunk of code is used to generate thumbnails as well (72x72), and it integral to the core of the application. I'd love some advice and/or hints on how to speed this up.</p>
  
  <p>If huge gains can be made by making the assumption that neither image will have alpha, that is fine. <em>NOTE</em>: BlendMode and alpha are values not used in the example (BlendMode will chose the type of blend, in this case I hardcoded HardLight).</p>
  
  <pre><code>public Bitmap blendedBitmap(Bitmap source, Bitmap layer, BlendMode blendMode, float alpha) {
      Bitmap base = source.copy(Config.ARGB_8888, true);
      Bitmap blend = layer.copy(Config.ARGB_8888, false);
  
      IntBuffer buffBase = IntBuffer.allocate(base.getWidth() * base.getHeight());
      base.copyPixelsToBuffer(buffBase);
      buffBase.rewind();
  
      IntBuffer buffBlend = IntBuffer.allocate(blend.getWidth() * blend.getHeight());
      blend.copyPixelsToBuffer(buffBlend);
      buffBlend.rewind();
  
      IntBuffer buffOut = IntBuffer.allocate(base.getWidth() * base.getHeight());
      buffOut.rewind();
  
      while (buffOut.position() &lt; buffOut.limit()) {
          int filterInt = buffBlend.get();
          int srcInt = buffBase.get();
  
          int redValueFilter = Color.red(filterInt);
          int greenValueFilter = Color.green(filterInt);
          int blueValueFilter = Color.blue(filterInt);
  
          int redValueSrc = Color.red(srcInt);
          int greenValueSrc = Color.green(srcInt);
          int blueValueSrc = Color.blue(srcInt);
  
          int redValueFinal = hardlight(redValueFilter, redValueSrc);
          int greenValueFinal = hardlight(greenValueFilter, greenValueSrc);
          int blueValueFinal = hardlight(blueValueFilter, blueValueSrc);
  
          int pixel = Color.argb(255, redValueFinal, greenValueFinal, blueValueFinal);
  
          buffOut.put(pixel);
      }
  
      buffOut.rewind();
  
      base.copyPixelsFromBuffer(buffOut);
      blend.recycle();
  
      return base;
  }
  
  private int hardlight(int in1, int in2) {
      float image = (float)in2;
      float mask = (float)in1;
      return ((int)((image &lt; 128) ? (2 * mask * image / 255):(255 - 2 * (255 - mask) * (255 - image) / 255)));
  
  }
  </code></pre>