下面列出了怎么用com.google.zxing.BinaryBitmap的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 二维码解码
*
* @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;
}
/**
* 解析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;
}
@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();
}
}
@Override
public Result decode(BinaryBitmap image, Map<DecodeHintType, ?> hints) throws NotFoundException, ChecksumException, FormatException {
DecoderResult decoderResult;
ResultPoint[] points;
if (hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE)) {
BitMatrix bits = extractPureBits(image.getBlackMatrix());
decoderResult = decoder.decode(bits, hints);
points = NO_POINTS;
} else {
DetectorResult detectorResult = new Detector(image.getBlackMatrix()).detect(hints);
decoderResult = decoder.decode(detectorResult.getBits(), hints);
points = detectorResult.getPoints();
}
Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.QR_CODE);
List<byte[]> byteSegments = decoderResult.getByteSegments();
if (byteSegments != null) {
result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
}
String ecLevel = decoderResult.getECLevel();
if (ecLevel != null) {
result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
}
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;
}
private static Result[] decode(BinaryBitmap image, Map<DecodeHintType, ?> hints, boolean multiple)
throws NotFoundException, FormatException, ChecksumException {
List<Result> results = new ArrayList<>();
PDF417DetectorResult detectorResult = Detector.detect(image, hints, multiple);
for (ResultPoint[] points : detectorResult.getPoints()) {
DecoderResult decoderResult = PDF417ScanningDecoder.decode(detectorResult.getBits(), points[4], points[5],
points[6], points[7], getMinCodewordWidth(points), getMaxCodewordWidth(points));
Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.PDF_417);
result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, decoderResult.getECLevel());
PDF417ResultMetadata pdf417ResultMetadata = (PDF417ResultMetadata) decoderResult.getOther();
if (pdf417ResultMetadata != null) {
result.putMetadata(ResultMetadataType.PDF417_EXTRA_METADATA, pdf417ResultMetadata);
}
results.add(result);
}
return results.toArray(new Result[results.size()]);
}
@Override
public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints)
throws NotFoundException, ChecksumException, FormatException {
DecoderResult decoderResult;
ResultPoint[] points;
if (hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE)) {
BitMatrix bits = extractPureBits(image.getBlackMatrix());
decoderResult = decoder.decode(bits);
points = NO_POINTS;
} else {
DetectorResult detectorResult = new Detector(image.getBlackMatrix()).detect();
decoderResult = decoder.decode(detectorResult.getBits());
points = detectorResult.getPoints();
}
Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points,
BarcodeFormat.DATA_MATRIX);
List<byte[]> byteSegments = decoderResult.getByteSegments();
if (byteSegments != null) {
result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
}
String ecLevel = decoderResult.getECLevel();
if (ecLevel != null) {
result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
}
return result;
}
@Override
public Result decode(BinaryBitmap image, Map<DecodeHintType, ?> hints)
throws NotFoundException, ChecksumException, FormatException {
DecoderResult decoderResult;
ResultPoint[] points;
if (hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE)) {
BitMatrix bits = extractPureBits(image.getBlackMatrix());
decoderResult = decoder.decode(bits);
points = NO_POINTS;
} else {
DetectorResult detectorResult = new Detector(image.getBlackMatrix()).detect();
decoderResult = decoder.decode(detectorResult.getBits());
points = detectorResult.getPoints();
}
Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points,
BarcodeFormat.DATA_MATRIX);
List<byte[]> byteSegments = decoderResult.getByteSegments();
if (byteSegments != null) {
result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
}
String ecLevel = decoderResult.getECLevel();
if (ecLevel != null) {
result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
}
return result;
}
/**
* 条形码解码
*
* @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;
}
public Result decode(BinaryBitmap binarybitmap, Map map)
{
if (map != null && map.containsKey(DecodeHintType.PURE_BARCODE))
{
BitMatrix bitmatrix = a(binarybitmap.getBlackMatrix());
DecoderResult decoderresult = d.decode(bitmatrix, map);
ResultPoint aresultpoint[] = a;
Result result = new Result(decoderresult.getText(), decoderresult.getRawBytes(), aresultpoint, BarcodeFormat.MAXICODE);
String s = decoderresult.getECLevel();
if (s != null)
{
result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, s);
}
return result;
} else
{
throw NotFoundException.getNotFoundInstance();
}
}
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;
}
@Override
public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints)
throws NotFoundException, ChecksumException, FormatException {
DecoderResult decoderResult;
if (hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE)) {
BitMatrix bits = extractPureBits(image.getBlackMatrix());
decoderResult = decoder.decode(bits, hints);
} else {
throw NotFoundException.getNotFoundInstance();
}
ResultPoint[] points = NO_POINTS;
Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.MAXICODE);
String ecLevel = decoderResult.getECLevel();
if (ecLevel != null) {
result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
}
return result;
}
/**
* <p>Detects a PDF417 Code in an image. Only checks 0 and 180 degree rotations.</p>
*
* @param image barcode image to decode
* @param hints optional hints to detector
* @param multiple if true, then the image is searched for multiple codes. If false, then at most one code will
* be found and returned
* @return {@link PDF417DetectorResult} encapsulating results of detecting a PDF417 code
* @throws NotFoundException if no PDF417 Code can be found
*/
public static PDF417DetectorResult detect(BinaryBitmap image, Map<DecodeHintType,?> hints, boolean multiple)
throws NotFoundException {
// TODO detection improvement, tryHarder could try several different luminance thresholds/blackpoints or even
// different binarizers
//boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
BitMatrix bitMatrix = image.getBlackMatrix();
List<ResultPoint[]> barcodeCoordinates = detect(multiple, bitMatrix);
if (barcodeCoordinates.isEmpty()) {
bitMatrix = bitMatrix.clone();
bitMatrix.rotate180();
barcodeCoordinates = detect(multiple, bitMatrix);
}
return new PDF417DetectorResult(bitMatrix, barcodeCoordinates);
}
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 static Result[] decode(BinaryBitmap image, Map<DecodeHintType, ?> hints, boolean multiple)
throws NotFoundException, FormatException, ChecksumException {
List<Result> results = new ArrayList<>();
PDF417DetectorResult detectorResult = Detector.detect(image, hints, multiple);
for (ResultPoint[] points : detectorResult.getPoints()) {
DecoderResult decoderResult = PDF417ScanningDecoder.decode(detectorResult.getBits(), points[4], points[5],
points[6], points[7], getMinCodewordWidth(points), getMaxCodewordWidth(points));
Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.PDF_417);
result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, decoderResult.getECLevel());
PDF417ResultMetadata pdf417ResultMetadata = (PDF417ResultMetadata) decoderResult.getOther();
if (pdf417ResultMetadata != null) {
result.putMetadata(ResultMetadataType.PDF417_EXTRA_METADATA, pdf417ResultMetadata);
}
results.add(result);
}
return results.toArray(new Result[results.size()]);
}
@Override
public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints)
throws NotFoundException, ChecksumException, FormatException {
DecoderResult decoderResult;
if (hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE)) {
BitMatrix bits = extractPureBits(image.getBlackMatrix());
decoderResult = decoder.decode(bits, hints);
} else {
throw NotFoundException.getNotFoundInstance();
}
ResultPoint[] points = NO_POINTS;
Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.MAXICODE);
String ecLevel = decoderResult.getECLevel();
if (ecLevel != null) {
result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
}
return result;
}
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;
}
/**
* <p>Detects a PDF417 Code in an image. Only checks 0 and 180 degree rotations.</p>
*
* @param image barcode image to decode
* @param hints optional hints to detector
* @param multiple if true, then the image is searched for multiple codes. If false, then at most one code will
* be found and returned
* @return {@link PDF417DetectorResult} encapsulating results of detecting a PDF417 code
* @throws NotFoundException if no PDF417 Code can be found
*/
public static PDF417DetectorResult detect(BinaryBitmap image, Map<DecodeHintType,?> hints, boolean multiple)
throws NotFoundException {
// TODO detection improvement, tryHarder could try several different luminance thresholds/blackpoints or even
// different binarizers
//boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
BitMatrix bitMatrix = image.getBlackMatrix();
List<ResultPoint[]> barcodeCoordinates = detect(multiple, bitMatrix);
if (barcodeCoordinates.isEmpty()) {
bitMatrix = bitMatrix.clone();
bitMatrix.rotate180();
barcodeCoordinates = detect(multiple, bitMatrix);
}
return new PDF417DetectorResult(bitMatrix, barcodeCoordinates);
}
/**
* Decode the data within the viewfinder rectangle, and time how long it took. For efficiency,
* reuse the same reader objects from one decode to the next.
*
* @param data The YUV preview frame.
*/
public CameraDecodeResult decode(byte[] data,boolean horizontal) {
int width = mCameraManger.getCameraConfig().getCameraResolution().x;
int height = mCameraManger.getCameraConfig().getCameraResolution().y;
Result rawResult = null;
if (!horizontal){
// 这里需要将获取的data翻转一下,因为相机默认拿的的横屏的数据
byte[] rotatedData = new byte[data.length];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++)
rotatedData[x * height + height - y - 1] = data[x + y * width];
}
int tmp = width; // Here we are swapping, that's the difference to #11
width = height;
height = tmp;
data= rotatedData;
}
PlanarYUVLuminanceSource source = mCameraManger.buildLuminanceSource(data, width, height,horizontal);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
rawResult = multiFormatReader.decodeWithState(bitmap);
} catch (ReaderException re) {
// continue
} finally {
multiFormatReader.reset();
}
Log.e(TAG, "decode:" + rawResult);
CameraDecodeResult cameraDecodeResult = new CameraDecodeResult();
cameraDecodeResult.setDecodeResult(rawResult);
if (rawResult != null){
// TODO: 2016/11/5
// cameraDecodeResult.setDecodeByte(bundleThumbnail(source));
}
cameraDecodeResult.setDecodeByte(bundleThumbnail(source));
return cameraDecodeResult;
}
@Override
public final Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints)
throws NotFoundException, ChecksumException, FormatException {
DecoderResult decoderResult;
ResultPoint[] points;
if (hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE)) {
BitMatrix bits = extractPureBits(image.getBlackMatrix());
decoderResult = decoder.decode(bits, hints);
points = NO_POINTS;
} else {
DetectorResult detectorResult = new Detector(image.getBlackMatrix()).detect(hints);
decoderResult = decoder.decode(detectorResult.getBits(), hints);
points = detectorResult.getPoints();
}
// If the code was mirrored: swap the bottom-left and the top-right points.
if (decoderResult.getOther() instanceof QRCodeDecoderMetaData) {
((QRCodeDecoderMetaData) decoderResult.getOther()).applyMirroredCorrection(points);
}
Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.QR_CODE);
List<byte[]> byteSegments = decoderResult.getByteSegments();
if (byteSegments != null) {
result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
}
String ecLevel = decoderResult.getECLevel();
if (ecLevel != null) {
result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
}
if (decoderResult.hasStructuredAppend()) {
result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE,
decoderResult.getStructuredAppendSequenceNumber());
result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_PARITY,
decoderResult.getStructuredAppendParity());
}
return result;
}
public Result[] zxing( Mat inputImage ) throws ChecksumException, FormatException {
int w = inputImage.width();
int h = inputImage.height();
Mat southEast;
if (mBugRotate) {
southEast = inputImage.submat(h-h/4 , h , 0 , w/2 - h/4 );
} else {
southEast = inputImage.submat(0, h / 4, w / 2 + h / 4, w);
}
Bitmap bMap = Bitmap.createBitmap(southEast.width(), southEast.height(), Bitmap.Config.ARGB_8888);
org.opencv.android.Utils.matToBitmap(southEast, bMap);
southEast.release();
int[] intArray = new int[bMap.getWidth()*bMap.getHeight()];
//copy pixel data from the Bitmap into the 'intArray' array
bMap.getPixels(intArray, 0, bMap.getWidth(), 0, 0, bMap.getWidth(), bMap.getHeight());
LuminanceSource source = new RGBLuminanceSource(bMap.getWidth(), bMap.getHeight(),intArray);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result[] results = {};
try {
results = qrCodeMultiReader.decodeMultiple(bitmap);
}
catch (NotFoundException e) {
}
return results;
}
@Override
public Result[] decodeMultiple(BinaryBitmap image, Map<DecodeHintType,?> hints)
throws NotFoundException {
List<Result> results = new ArrayList<>();
doDecodeMultiple(image, hints, results, 0, 0, 0);
if (results.isEmpty()) {
throw NotFoundException.getNotFoundInstance();
}
return results.toArray(new Result[results.size()]);
}
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);
final int thumbnailWidth = source.getThumbnailWidth();
final int thumbnailHeight = source.getThumbnailHeight();
final float thumbnailScaleFactor = (float) thumbnailWidth / source.getWidth();
final Bitmap thumbnailImage = Bitmap.createBitmap(thumbnailWidth, thumbnailHeight,
Bitmap.Config.ARGB_8888);
thumbnailImage.setPixels(
source.renderThumbnail(), 0, thumbnailWidth, 0, 0, thumbnailWidth, thumbnailHeight);
runOnUiThread(() -> handleResult(scanResult, thumbnailImage, thumbnailScaleFactor));
} catch (final ReaderException x) {
// retry
cameraHandler.post(fetchAndDecodeRunnable);
} finally {
reader.reset();
}
}
@Override
public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException, FormatException,
ChecksumException {
Result[] result = decode(image, hints, false);
if (result == null || result.length == 0 || result[0] == null) {
throw NotFoundException.getNotFoundInstance();
}
return result[0];
}
/**
* 读取二维码
* @param file 二维码源
* @throws Exception
*/
private static void readCode(File file) throws Exception{
BufferedImage encodedBufferedImage = ImageIO.read(file) ;
LuminanceSource source = new BufferedImageLuminanceSource(encodedBufferedImage);
Result result = new QRCodeReader().decode(new BinaryBitmap(new HybridBinarizer(source)));
System.out.println(result.getText());
}
@Override
public Result decode(BinaryBitmap image, Map<DecodeHintType, ?> hints) throws NotFoundException, FormatException {
try {
return doDecode(image, hints);
} catch (NotFoundException nfe) {
boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
if (tryHarder && image.isRotateSupported()) {
BinaryBitmap rotatedImage = image.rotateCounterClockwise();
Result result = doDecode(rotatedImage, hints);
// Record that we found it rotated 90 degrees CCW / 270 degrees
// CW
Map<ResultMetadataType, ?> metadata = result.getResultMetadata();
int orientation = 270;
if (metadata != null && metadata.containsKey(ResultMetadataType.ORIENTATION)) {
// But if we found it reversed in doDecode(), add in that
// result here:
orientation = (orientation + (Integer) metadata.get(ResultMetadataType.ORIENTATION)) % 360;
}
result.putMetadata(ResultMetadataType.ORIENTATION, orientation);
// Update result points
ResultPoint[] points = result.getResultPoints();
if (points != null) {
int height = rotatedImage.getHeight();
for (int i = 0; i < points.length; i++) {
points[i] = new ResultPoint(height - points[i].getY() - 1, points[i].getX());
}
}
return result;
} else {
throw nfe;
}
}
}
@Nullable
public static Result decodeLuminanceSource(@NonNull final MultiFormatReader reader,
@NonNull final LuminanceSource luminanceSource) throws ReaderException {
try {
return reader.decodeWithState(new BinaryBitmap(new HybridBinarizer(luminanceSource)));
} catch (final NotFoundException e) {
return reader.decodeWithState(
new BinaryBitmap(new HybridBinarizer(luminanceSource.invert())));
} finally {
reader.reset();
}
}
public static String decode(InputStream in) throws Exception {
BufferedImage image = ImageIO.read(in);
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码
return result.getText();
}
@Override
public final Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints)
throws NotFoundException, ChecksumException, FormatException {
DecoderResult decoderResult;
ResultPoint[] points;
if (hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE)) {
BitMatrix bits = extractPureBits(image.getBlackMatrix());
decoderResult = decoder.decode(bits, hints);
points = NO_POINTS;
} else {
DetectorResult detectorResult = new Detector(image.getBlackMatrix()).detect(hints);
decoderResult = decoder.decode(detectorResult.getBits(), hints);
points = detectorResult.getPoints();
}
// If the code was mirrored: swap the bottom-left and the top-right points.
if (decoderResult.getOther() instanceof QRCodeDecoderMetaData) {
((QRCodeDecoderMetaData) decoderResult.getOther()).applyMirroredCorrection(points);
}
Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.QR_CODE);
List<byte[]> byteSegments = decoderResult.getByteSegments();
if (byteSegments != null) {
result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
}
String ecLevel = decoderResult.getECLevel();
if (ecLevel != null) {
result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
}
if (decoderResult.hasStructuredAppend()) {
result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE,
decoderResult.getStructuredAppendSequenceNumber());
result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_PARITY,
decoderResult.getStructuredAppendParity());
}
return result;
}