2017-05-03 136 views
1

我已经将一个字符串编码为QR位图。图片变成这样:Android QR位图需要帮助删除保证金

image of QR bitmap

我需要做什么改变,使周围有没有QR空格?我尝试阅读有关MultiFormatWriter()和setPixels()的文档,但无法找到它错误的地方。 这里是代码:

Bitmap encodeAsBitmap(String str) throws WriterException { 
    BitMatrix result; 
    try { 
     result = new MultiFormatWriter().encode(str, 
       BarcodeFormat.QR_CODE, 500, 500, null); 
    } catch (IllegalArgumentException iae) { 
     return null; 
    } 

    int w = result.getWidth(); 
    int h = result.getHeight(); 
    int[] pixels = new int [w * h]; 
    for (int i = 0; i < h; i++) { 
     int offset = i * w; 
     for (int j = 0; j < w; j++) { 
      pixels[offset + j] = result.get(i, j) ? BLACK : WHITE; 
     } 
    } 

    Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); 
    bitmap.setPixels(pixels, 0, 500, 0, 0, w, h); 
    return bitmap; 

} 

回答

0

我认为问题是你在你的位图设置像素的方式。

按照documentation

步幅INT:颜色中的像素[]中的编号,以行之间跳过。通常这个值将与位图的宽度相同,但可以更大(或负)。

因此,我建议如下:

bitmap.setPixels(pixels, 0, w, 0, 0, w, h); 

编辑: 只注意到你假设输入的大小是500,你可以尝试计算它(假设你的字符串代表一个正方形)。如果它是一个矩形,您必须能够以某种方式计算大小,以便MultiFormatWriter可以读取它。

所以,你的代码可以是:

Bitmap encodeAsBitmap(String str, int size) throws WriterException { 

    BitMatrix result; 
    try { 
     result = new MultiFormatWriter().encode(str, 
       BarcodeFormat.QR_CODE, size, size, null); 
    } catch (IllegalArgumentException iae) { 
     return null; 
    } 

    int[] pixels = new int [size * size]; 
    for (int i = 0; i < size; i++) { 
     int offset = i * size; 
     for (int j = 0; j < size; j++) { 
      pixels[offset + j] = result.get(i, j) ? BLACK : WHITE; 
     } 
    } 

    Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); 
    bitmap.setPixels(pixels, 0, size, 0, 0, size, size); 
    return bitmap; 

} 
+0

它仍然具有输出边缘图像:( – Toeffen

+0

我更新的代码 –

+0

更新给出了ImageView的宽度和str.length()的高度,它使。 ImageView不可见,但是这是很好的方向,我们可能需要结果的长度(也许是?) – Toeffen