关于android zxing二维码开发这方面的技术,现在大家比较常用到的扫描二维码和扫描本地图片,今天刚解决的一个问题就是我的扫描本地图片二维码的功能老存在问题,有的二维码可以扫出来,有的扫不出来,看网上的帖子有人说需要什么将rgb转换成黑白,还有的说要转成yuv格式,试了一下,没有解决自己的问题,有可能我的技术还不到位吧,最后在一个demo里找到了这种方法,直接就解决了问题。
private void decode(final String picturePath) {
new Thread() {
@Override
public void run() {
Bitmap image = BitmapFactory.decodeFile(picturePath);
Bitmap bitmap = reduce(image,50,50,true);
RGBLuminanceSource source = new RGBLuminanceSource(bitmap);
BinaryBitmap binaryBitmap = new BinaryBitmap(
new HybridBinarizer(source));
Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
QRCodeReader reader = new QRCodeReader();
Result result = null;
try {
result = reader.decode(binaryBitmap, hints);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (ChecksumException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
} finally {
reader.reset();
}
Message message = Message.obtain();
if (result != null) {
message.what = 0;
message.obj = result.getText();
} else {
message.what = 1;
}
scanHandler.sendMessage(message);
}
}.start();
}
private Handler scanHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0) {
//扫描成功获取信息
Intent intent = new Intent(Details.this,WebViewactivity.class);
intent.putExtra("txt", msg.obj.toString());
startActivity(intent);
} else {
Toast.makeText(Details.this, "失败", Toast.LENGTH_LONG)
.show();
}
super.handleMessage(msg);
}
};
/**
* 压缩图片
* @param bitmap 源图片
* @param width 想要的宽度
* @param height 想要的高度
* @param isAdjust 是否自动调整尺寸, true图片就不会拉伸,false严格按照你的尺寸压缩
* @return Bitmap
* @author wangyongzheng
*/
public Bitmap reduce(Bitmap bitmap, int width, int height, boolean isAdjust) {
// 如果想要的宽度和高度都比源图片小,就不压缩了,直接返回原图
if (bitmap.getWidth() < width && bitmap.getHeight() < height) {return bitmap;}
// 根据想要的尺寸精确计算压缩比例, 方法详解:public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode);
// scale表示要保留的小数位, roundingMode表示如何处理多余的小数位,BigDecimal.ROUND_DOWN表示自动舍弃
float sx = new BigDecimal(width).divide(new BigDecimal(bitmap.getWidth()), 4, BigDecimal.ROUND_DOWN).floatValue();
float sy = new BigDecimal(height).divide(new BigDecimal(bitmap.getHeight()), 4, BigDecimal.ROUND_DOWN).floatValue();
if (isAdjust) {// 如果想自动调整比例,不至于图片会拉伸
sx = (sx < sy ? sx : sy);sy = sx;// 哪个比例小一点,就用哪个比例
}
Matrix matrix = new Matrix();
matrix.postScale(sx, sy);// 调用api中的方法进行压缩,就大功告成了
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}