之前由string生成Bitmap的算法;全黑,但是imageView显示正常
public static Bitmap CreateOneDCode(String content) throws WriterException {
// 生成一维条码,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
BitMatrix matrix = new MultiFormatWriter().encode(content,
BarcodeFormat.CODE_128, 500, 200);
int width = matrix.getWidth();
int height = matrix.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (matrix.get(x, y)) {
pixels[y * width + x] = 0xff000000;
}
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
// 通过像素数组生成bitmap,具体参考api
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
更改算法,正常了
private static final int BLACK = 0xff000000;
private static final int WHITE = 0xFFFFFFFF;
private static BarcodeFormat barcodeFormat= BarcodeFormat.CODE_128;
public static Bitmap creatBarcode(String contents, int desiredWidth,int desiredHeight) {
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result=null;
try {
result = writer.encode(contents, barcodeFormat, desiredWidth,
desiredHeight);
} catch (WriterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
// All are 0, or black, by default
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}