Android, Blur Bitmap instantly?

前端 未结 2 1387
既然无缘
既然无缘 2021-02-03 13:49

So I\'m trying to blur an image as fast as possible(instant feel like), as the activity needs to be updated as I press the Blur button.

The problem I am having is that,

2条回答
  •  臣服心动
    2021-02-03 13:58

    Gaussian blur is expensive to do accurately. A much faster approximation can be done by just iteratively averaging the pixels. It's still expensive to blur the image a lot but you can redraw between each iteration to at least give instant feedback and a nice animation of the image blurring.

    static void blurfast(Bitmap bmp, int radius) {
      int w = bmp.getWidth();
      int h = bmp.getHeight();
      int[] pix = new int[w * h];
      bmp.getPixels(pix, 0, w, 0, 0, w, h);
    
      for(int r = radius; r >= 1; r /= 2) {
        for(int i = r; i < h - r; i++) {
          for(int j = r; j < w - r; j++) {
            int tl = pix[(i - r) * w + j - r];
            int tr = pix[(i - r) * w + j + r];
            int tc = pix[(i - r) * w + j];
            int bl = pix[(i + r) * w + j - r];
            int br = pix[(i + r) * w + j + r];
            int bc = pix[(i + r) * w + j];
            int cl = pix[i * w + j - r];
            int cr = pix[i * w + j + r];
    
            pix[(i * w) + j] = 0xFF000000 |
                (((tl & 0xFF) + (tr & 0xFF) + (tc & 0xFF) + (bl & 0xFF) + (br & 0xFF) + (bc & 0xFF) + (cl & 0xFF) + (cr & 0xFF)) >> 3) & 0xFF |
                (((tl & 0xFF00) + (tr & 0xFF00) + (tc & 0xFF00) + (bl & 0xFF00) + (br & 0xFF00) + (bc & 0xFF00) + (cl & 0xFF00) + (cr & 0xFF00)) >> 3) & 0xFF00 |
                (((tl & 0xFF0000) + (tr & 0xFF0000) + (tc & 0xFF0000) + (bl & 0xFF0000) + (br & 0xFF0000) + (bc & 0xFF0000) + (cl & 0xFF0000) + (cr & 0xFF0000)) >> 3) & 0xFF0000;
          }
        }
      }
      bmp.setPixels(pix, 0, w, 0, 0, w, h);
    }
    

提交回复
热议问题