【问题标题】:Better alternative to .getPixel()?.getPixel() 的更好替代方案?
【发布时间】:2014-05-28 05:24:11
【问题描述】:

我在我的 Android 应用程序 中使用此代码将位图转换为纯黑白并且它可以工作:

public Bitmap ConvertToThreshold(Bitmap anythingBmap)
{
    int width = anythingBmap.getWidth();
    int height = anythingBmap.getHeight();
    int threshold = 120;
    for(int x=0;x<width;x++){
        for(int y=0;y<height;y++){

            int pixel = anythingBmap.getPixel(x, y);
            int gray = Color.red(pixel);
            if(gray < threshold){
                anythingBmap.setPixel(x, y, 0xFF000000);
            } else{
                anythingBmap.setPixel(x, y, 0xFFFFFFFF);
            }
        }
    }
    return anythingBmap;
}

.getPixel() 非常慢的问题,因此这需要很长时间来处理。有更快的方法吗?

谢谢

【问题讨论】:

    标签: java android imaging


    【解决方案1】:

    使用公共无效getPixels (int[] pixels, int offset, int stride, int x, int y, int width, int height)。这将一次返回所有像素。

    【讨论】:

    • 在这种方法中如何处理单个像素?
    • 它是一个扁平矩阵。所以第n行第m列的像素位于数组位置n*width+m
    【解决方案2】:

    更好的方法是为像素处理创建一个 int[] 缓冲区。之后,您只需要将数组复制到位图。需要用到的方法:

    public void copyPixelsFromBuffer (Buffer src)
    public void copyPixelsToBuffer (Buffer dst)
    private static IntBuffer makeBuffer(int[] src, int n) {
             IntBuffer dst = IntBuffer.allocate(n);
             for (int i = 0; i < n; i++) {
                 dst.put(src[i]);
             }
             dst.rewind();
             return dst;
         }
    

    示例代码:

    final int N = mWidth * mHeight;
    mBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
    int[] data8888 = new int[N];
    mBitmap.copyPixelsFromBuffer(makeBuffer(data8888, N));
    

    【讨论】:

      猜你喜欢
      • 2011-05-13
      • 1970-01-01
      • 2016-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-15
      • 2011-10-26
      相关资源
      最近更新 更多