下面列出了怎么用com.google.zxing.common.HybridBinarizer的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 解析二维码 (ZXing)
*
* @param file 二维码图片
* @return
* @throws Exception
*/
public static String decode(File file) throws Exception {
BufferedImage image;
image = ImageIO.read(file);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
}
/**
* 条形码解码
*
* @param imgPath
* @return String
*/
public static String decode(String imgPath) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(new File(imgPath));
if (image == null) {
System.out.println("the decode image may be not exit.");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
result = new MultiFormatReader().decode(bitmap, null);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 二维码解码
*
* @param imgPath
* @return String
*/
public static String decode2(String imgPath) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(new File(imgPath));
if (image == null) {
System.out.println("the decode image may be not exit.");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, "GBK");
result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 读取二维码图片
*
* @param path
* @return
* @throws Exception
*/
public static String read(String path) throws Exception {
File file = new File(path);
BufferedImage image;
image = ImageIO.read(file);
if (Objects.isNull(image)) {
throw new RuntimeException("无法读取源文件");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
@SuppressWarnings("rawtypes")
EnumMap<DecodeHintType, String> hints = Maps.newEnumMap(DecodeHintType.class);
//解码设置编码方式为:utf-8
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
}
/**
* 解析QR图内容
*
* @param imageView
* @return
*/
public static String readImage(ImageView imageView) {
String content = null;
Map<DecodeHintType, String> hints = new HashMap<>();
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
// 获得待解析的图片
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
RGBLuminanceSource source = new RGBLuminanceSource(bitmap);
BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
QRCodeReader reader = new QRCodeReader();
try {
Result result = reader.decode(bitmap1, hints);
// 得到解析后的文字
content = result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return content;
}
/**
* 使用YUV解析bitmap
*
* @param data
* @param width
* @param height
* @param hintTypeMap
* @return
*/
private Result decodeFromYUV(int[] data, int width, int height, Map<DecodeHintType, ?> hintTypeMap) {
Result result = null;
byte[] yuv = convertRGBToYuv(data, new byte[width * height], width, height);
PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(yuv, width, height, 0, 0, width, height, false);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
result = new MultiFormatReader().decode(binaryBitmap, hintTypeMap);
} catch (NotFoundException e) {
//使用GlobalHistogramBinarizer算法进行解析
try {
result = new MultiFormatReader().decode(new BinaryBitmap(new GlobalHistogramBinarizer(source)), hintTypeMap);
} catch (NotFoundException e1) {
e1.printStackTrace();
}
}
return result;
}
/**
* 图片解析
*/
protected ShadowSocksDetailsEntity parseURL(String imgURL) throws IOException, NotFoundException {
Connection.Response resultImageResponse = getConnection(imgURL).execute();
Map<DecodeHintType, Object> hints = new LinkedHashMap<>();
// 解码设置编码方式为:utf-8,
hints.put(DecodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name());
//优化精度
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
//复杂模式,开启PURE_BARCODE模式
hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
try (BufferedInputStream bytes = resultImageResponse.bodyStream()) {
BufferedImage image = ImageIO.read(bytes);
Binarizer binarizer = new HybridBinarizer(new BufferedImageLuminanceSource(image));
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Result res = new MultiFormatReader().decode(binaryBitmap, hints);
return parseLink(res.toString());
}
}
/**
* 图片解析
*/
protected ShadowSocksDetailsEntity parseImg(String imgURL) throws IOException, NotFoundException {
String str = StringUtils.removeFirst(imgURL, "data:image/png;base64,");
Map<DecodeHintType, Object> hints = new LinkedHashMap<>();
// 解码设置编码方式为:utf-8,
hints.put(DecodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name());
//优化精度
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
//复杂模式,开启PURE_BARCODE模式
hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
try (ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decodeBase64(str))) {
BufferedImage image = ImageIO.read(bis);
Binarizer binarizer = new HybridBinarizer(new BufferedImageLuminanceSource(image));
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Result res = new MultiFormatReader().decode(binaryBitmap, hints);
return parseLink(res.toString());
}
}
@Override
public ReadableMap decodeRGBBitmap(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
bitmap.recycle();
RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
BinaryBitmap bBitmap = new BinaryBitmap(new HybridBinarizer(source));
WritableMap result = null;
try {
Result decodeResult = mReader.decode(bBitmap, mHints);
result = Arguments.createMap();
result.putInt("format", symbolToFormat(decodeResult.getBarcodeFormat()));
result.putString("content", decodeResult.getText());
} catch (NotFoundException ignored) {
}
return result;
}
/**
* 读二维码并输出携带的信息
*/
public static void readQrCode(InputStream inputStream) throws IOException {
//从输入流中获取字符串信息
BufferedImage image = ImageIO.read(inputStream);
//将图像转换为二进制位图源
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
QRCodeReader reader = new QRCodeReader();
Result result = null;
try {
result = reader.decode(bitmap);
} catch (ReaderException e) {
e.printStackTrace();
}
System.out.println(result.getText());
}
/**
* 解析二维码
*
* @param file
* 二维码图片
* @return
* @throws Exception
*/
public static String decode(InputStream in) throws Exception {
BufferedImage image = ImageIO.read(in);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
in.close();
return resultStr;
}
public static String decode(File file) throws Exception {
BufferedImage image;
image = ImageIO.read(file);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(
image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable hints = new Hashtable();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
}
public static Result decodeImage(final String path) {
Bitmap bitmap = QrUtils.decodeSampledBitmapFromFile(path, 256, 256);
// Google Photo 相册中选取云照片是会出现 Bitmap == null
if (bitmap == null) return null;
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
// RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
PlanarYUVLuminanceSource source1 = new PlanarYUVLuminanceSource(getYUV420sp(width, height, bitmap), width, height, 0, 0, width, height, false);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source1));
// BinaryBitmap binaryBitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source1));
HashMap<DecodeHintType, Object> hints = new HashMap<>();
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
try {
return new MultiFormatReader().decode(binaryBitmap, hints);
} catch (NotFoundException e) {
e.printStackTrace();
}
return null;
}
public Result decodeWithZxing(Bitmap bitmap) {
MultiFormatReader multiFormatReader = new MultiFormatReader();
multiFormatReader.setHints(changeZXingDecodeDataMode());
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
Result rawResult = null;
RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
rawResult = multiFormatReader.decodeWithState(binaryBitmap);
} catch (ReaderException re) {
// continue
} finally {
multiFormatReader.reset();
}
return rawResult;
}
/**
* 条形码解码
*
* @param imgPath
* @return String
*/
public static String decode(String imgPath) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(new File(imgPath));
if (image == null) {
System.out.println("the decode image may be not exit.");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
result = new MultiFormatReader().decode(bitmap, null);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 二维码解码
*
* @param imgPath
* @return String
*/
public static String decode2(String imgPath) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(new File(imgPath));
if (image == null) {
System.out.println("the decode image may be not exit.");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, "GBK");
result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Decode all barcodes in the image
*/
private String multiple(BufferedImage img) throws NotFoundException, ChecksumException, FormatException {
long begin = System.currentTimeMillis();
LuminanceSource source = new BufferedImageLuminanceSource(img);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
com.google.zxing.Reader reader = new MultiFormatReader();
MultipleBarcodeReader bcReader = new GenericMultipleBarcodeReader(reader);
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
StringBuilder sb = new StringBuilder();
for (Result result : bcReader.decodeMultiple(bitmap, hints)) {
sb.append(result.getText()).append(" ");
}
SystemProfiling.log(null, System.currentTimeMillis() - begin);
log.trace("multiple.Time: {}", System.currentTimeMillis() - begin);
return sb.toString();
}
public String decodeWithZxing(byte[] data, int width, int height, Rect crop) {
MultiFormatReader multiFormatReader = new MultiFormatReader();
multiFormatReader.setHints(changeZXingDecodeDataMode());
Result rawResult = null;
PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(data, width, height,
crop.left, crop.top, crop.width(), crop.height(), false);
if (source != null) {
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
rawResult = multiFormatReader.decodeWithState(bitmap);
} catch (ReaderException re) {
// continue
} finally {
multiFormatReader.reset();
}
}
return rawResult != null ? rawResult.getText() : null;
}
public String decodeWithZxing(Bitmap bitmap) {
MultiFormatReader multiFormatReader = new MultiFormatReader();
multiFormatReader.setHints(changeZXingDecodeDataMode());
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
Result rawResult = null;
RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
if (source != null) {
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
rawResult = multiFormatReader.decodeWithState(binaryBitmap);
} catch (ReaderException re) {
// continue
} finally {
multiFormatReader.reset();
}
}
return rawResult != null ? rawResult.getText() : null;
}
private String decode(byte[] data, int width, int height) {
ScannerManager manager = mManager.get();
if (manager == null) {
return null;
}
Rect rect = manager.getFramingRectInPreview();
PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(data,
width, height, rect.left, rect.top, rect.right, rect.bottom, false);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
QRCodeReader reader = new QRCodeReader();
try {
Result result = reader.decode(bitmap, mHints);
return result.getText();
} catch (ReaderException e) {
// Ignore as we will repeatedly decode the preview frame
return null;
}
}
public String decode(final Bitmap image){
final long start = System.currentTimeMillis();
final int width = image.getWidth(), height = image.getHeight();
final int[] pixels = new int[width * height];
image.getPixels(pixels, 0, width, 0, 0, width, height);
final RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
final BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
Result rawResult = mMultiFormatReader.decodeWithState(bitmap);
final long end = System.currentTimeMillis();
Log.d(TAG, "QRCode decode in " + (end - start) + "ms");
Log.d(TAG, rawResult.toString());
return rawResult.getText();
} catch (NotFoundException re) {
Log.w(TAG, re);
return null;
}finally {
mMultiFormatReader.reset();
}
}
private void decode(final byte[] data) {
final PlanarYUVLuminanceSource source = cameraManager.buildLuminanceSource(data);
final BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
hints.put(DecodeHintType.NEED_RESULT_POINT_CALLBACK, (ResultPointCallback) dot -> runOnUiThread(() -> scannerView.addDot(dot)));
final Result scanResult = reader.decode(bitmap, hints);
runOnUiThread(() -> handleResult(scanResult));
} catch (final ReaderException x) {
// retry
cameraHandler.post(fetchAndDecodeRunnable);
} finally {
reader.reset();
}
}
public static String decode(BufferedImage image) {
// convert the image to a binary bitmap source
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
// decode the barcode
QRCodeReader reader = new QRCodeReader();
try {
@SuppressWarnings("rawtypes")
Hashtable hints = new Hashtable();
Result result = reader.decode(bitmap, hints);
return result.getText();
} catch (ReaderException e) {
// the data is improperly formatted
}
return "";
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
// TODO Auto-generated method stub
if (mDialog.isShowing())
return;
LuminanceSource source = new PlanarYUVLuminanceSource(data, mWidth, mHeight, mLeft, mTop, mAreaWidth, mAreaHeight, false);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(
source));
Result result;
try {
result = mMultiFormatReader.decode(bitmap, null);
if (result != null) {
mDialog.setTitle("Result");
mDialog.setMessage(result.getText());
mDialog.show();
}
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String decode(BufferedImage image) {
// convert the image to a binary bitmap source
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
// decode the barcode
QRCodeReader reader = new QRCodeReader();
try {
@SuppressWarnings("rawtypes")
Hashtable hints = new Hashtable();
Result result = reader.decode(bitmap, hints);
return result.getText();
} catch (ReaderException e) {
// the data is improperly formatted
}
return "";
}
/**
* 获取解码结果
*
* @param bitmap
* @return
*/
public Result getRawResult(Bitmap bitmap) {
if (bitmap == null) {
return null;
}
try {
return multiFormatReader.decodeWithState(new BinaryBitmap(
new HybridBinarizer(new BitmapLuminanceSource(bitmap))));
}
catch (NotFoundException e) {
e.printStackTrace();
}
return null;
}
private void decode(final byte[] data) {
final PlanarYUVLuminanceSource source = cameraManager.buildLuminanceSource(data);
final BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
hints.put(DecodeHintType.NEED_RESULT_POINT_CALLBACK, (ResultPointCallback) dot -> runOnUiThread(() -> scannerView.addDot(dot)));
final Result scanResult = reader.decode(bitmap, hints);
runOnUiThread(() -> handleResult(scanResult));
} catch (final ReaderException x) {
// retry
cameraHandler.post(fetchAndDecodeRunnable);
} finally {
reader.reset();
}
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
int previewWidth = camera.getParameters().getPreviewSize().width;
int previewHeight = camera.getParameters().getPreviewSize().height;
PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(
data, previewWidth, previewHeight, 0, 0, previewWidth,
previewHeight, false);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Reader reader = new QRCodeReader();
try {
Result result = reader.decode(bitmap);
String text = result.getText();
Intent intent = new Intent();
intent.setData(Uri.parse(text));
setResult(RESULT_OK, intent);
finish();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Not Found",
Toast.LENGTH_SHORT).show();
}
}
/**
* 使用RGB解析bitmap
*
* @param data
* @param width
* @param height
* @param hintTypeMap
* @return
*/
private Result decodeFromRGB(int[] data, int width, int height, Map<DecodeHintType, ?> hintTypeMap) {
RGBLuminanceSource source = new RGBLuminanceSource(width, height, data);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
return new MultiFormatReader().decode(binaryBitmap, hintTypeMap);
} catch (NotFoundException e) {
e.printStackTrace();
}
return null;
}
/**
* 解析二维码图片
* @param bitmap 待解析的二维码图片
* @param qrScanCallBack 解析结果回调
*/
public static void decodeQRCode(final Bitmap bitmap, final QRScanCallBack qrScanCallBack) {
if (bitmap == null) {
if (qrScanCallBack != null) {
qrScanCallBack.onResult(false, null, new Exception("bitmap is null"));
}
return;
}
// 开始解析
DevThreadManager.getInstance(5).execute(new Runnable() {
@Override
public void run() {
try {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
Result result = new MultiFormatReader().decode(new BinaryBitmap(new HybridBinarizer(source)), DECODE_HINTS);
// 触发回调
if (qrScanCallBack != null) {
qrScanCallBack.onResult((result != null), result, null);
}
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "decodeQRCode");
// 触发回调
if (qrScanCallBack != null) {
qrScanCallBack.onResult(false, null, e);
}
}
}
});
}