com.google.zxing.Result Java Examples

The following examples show how to use com.google.zxing.Result. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DecodeUtils.java    From SimplifyReader with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #2
Source File: ScanActivity.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
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();
	}
}
 
Example #3
Source File: HistoryManager.java    From android-apps with MIT License 6 votes vote down vote up
public List<HistoryItem> buildHistoryItems() {
  SQLiteOpenHelper helper = new DBHelper(activity);
  List<HistoryItem> items = new ArrayList<HistoryItem>();
  SQLiteDatabase db = null;
  Cursor cursor = null;
  try {
    db = helper.getReadableDatabase();
    cursor = db.query(DBHelper.TABLE_NAME, COLUMNS, null, null, null, null, DBHelper.TIMESTAMP_COL + " DESC");
    while (cursor.moveToNext()) {
      String text = cursor.getString(0);
      String display = cursor.getString(1);
      String format = cursor.getString(2);
      long timestamp = cursor.getLong(3);
      String details = cursor.getString(4);
      Result result = new Result(text, null, null, BarcodeFormat.valueOf(format), timestamp);
      items.add(new HistoryItem(result, display, details));
    }
  } finally {
    close(cursor, db);
  }
  return items;
}
 
Example #4
Source File: CaptureActivityHandler.java    From AirFree-Client with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void handleMessage(Message message) {
    if (message.what == R.id.restart_preview) {
        restartPreviewAndDecode();

    } else if (message.what == R.id.decode_succeeded) {
        state = State.SUCCESS;
        Bundle bundle = message.getData();

        activity.handleDecode((Result) message.obj, bundle);

    } else if (message.what == R.id.decode_failed) {// We're decoding as fast as possible, so when one
        // decode fails,
        // start another.
        state = State.PREVIEW;
        cameraManager.requestPreviewFrame(decodeThread.getHandler(), R.id.decode);

    } else if (message.what == R.id.return_scan_result) {
        activity.setResult(Activity.RESULT_OK, (Intent) message.obj);
        activity.finish();

    }
}
 
Example #5
Source File: WifiResultParser.java    From reacteu-app with MIT License 6 votes vote down vote up
@Override
public WifiParsedResult parse(Result result) {
  String rawText = getMassagedText(result);
  if (!rawText.startsWith("WIFI:")) {
    return null;
  }
  String ssid = matchSinglePrefixedField("S:", rawText, ';', false);
  if (ssid == null || ssid.length() == 0) {
    return null;
  }
  String pass = matchSinglePrefixedField("P:", rawText, ';', false);
  String type = matchSinglePrefixedField("T:", rawText, ';', false);
  if (type == null) {
    type = "nopass";
  }
  boolean hidden = Boolean.parseBoolean(matchSinglePrefixedField("B:", rawText, ';', false));
  return new WifiParsedResult(type, ssid, pass, hidden);
}
 
Example #6
Source File: RNCameraView.java    From react-native-camera-android with MIT License 6 votes vote down vote up
@Override
public void handleResult(Result result) {

    // Received Barcode Result!
    WritableMap event = Arguments.createMap();
    event.putString("data", result.getText());
    event.putString("type", result.getBarcodeFormat().toString());

    ReactContext reactContext = (ReactContext)getContext();
    reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
            getId(),
            "topChange",
            event);

    startCamera(mCameraId);
    setFlash(torchModeIsEnabled());
}
 
Example #7
Source File: RSS14Reader.java    From Tesseract-OCR-Scanner with Apache License 2.0 6 votes vote down vote up
@Override
public Result decodeRow(int rowNumber,
                        BitArray row,
                        Map<DecodeHintType,?> hints) throws NotFoundException {
  Pair leftPair = decodePair(row, false, rowNumber, hints);
  addOrTally(possibleLeftPairs, leftPair);
  row.reverse();
  Pair rightPair = decodePair(row, true, rowNumber, hints);
  addOrTally(possibleRightPairs, rightPair);
  row.reverse();
  for (Pair left : possibleLeftPairs) {
    if (left.getCount() > 1) {
      for (Pair right : possibleRightPairs) {
        if (right.getCount() > 1 && checkChecksum(left, right)) {
          return constructResult(left, right);
        }
      }
    }
  }
  throw NotFoundException.getNotFoundInstance();
}
 
Example #8
Source File: GenericMultipleBarcodeReader.java    From ScreenCapture with MIT License 6 votes vote down vote up
private static Result translateResultPoints(Result result, int xOffset, int yOffset) {
  ResultPoint[] oldResultPoints = result.getResultPoints();
  if (oldResultPoints == null) {
    return result;
  }
  ResultPoint[] newResultPoints = new ResultPoint[oldResultPoints.length];
  for (int i = 0; i < oldResultPoints.length; i++) {
    ResultPoint oldPoint = oldResultPoints[i];
    if (oldPoint != null) {
      newResultPoints[i] = new ResultPoint(oldPoint.getX() + xOffset, oldPoint.getY() + yOffset);
    }
  }
  Result newResult = new Result(result.getText(),
                                result.getRawBytes(),
                                result.getNumBits(),
                                newResultPoints,
                                result.getBarcodeFormat(),
                                result.getTimestamp());
  newResult.putAllMetadata(result.getResultMetadata());
  return newResult;
}
 
Example #9
Source File: QRCodeScanActivity.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
@Override
public void handleMessage(Message message) {
    if (message.what == R.id.restart_preview) {
        restartPreviewAndDecode();
    } else if (message.what == R.id.decode_succeeded) { // 解析成功
        DevLogger.dTag(TAG, "解析成功");
        mState = State.SUCCESS;
        Bundle bundle = message.getData();
        mDecodeResult.handleDecode((Result) message.obj, bundle);
    } else if (message.what == R.id.decode_failed) { // 解析失败 ( 解析不出来触发 )
        DevLogger.dTag(TAG, "解析失败");
        // 表示预览中
        mState = State.PREVIEW;
        // 设置预览解码线程
        requestPreviewFrame(mDecodeThread.getHandler(), R.id.decode);
    }
}
 
Example #10
Source File: CaptureActivity.java    From Gizwits-SmartSocket_Android with MIT License 6 votes vote down vote up
/**
 * A valid barcode has been found, so give an indication of success and show
 * the results.
 * 
 * @param rawResult
 *            The contents of the barcode.
 * 
 * @param bundle
 *            The extras
 */
public void handleDecode(Result rawResult, Bundle bundle) {
	String text = rawResult.getText();
	Log.i("test", text);
	if (text.contains("product_key=") & text.contains("did=")
			&& text.contains("passcode=")) {

		inactivityTimer.onActivity();
		product_key = getParamFomeUrl(text, "product_key");
		did = getParamFomeUrl(text, "did");
		passcode = getParamFomeUrl(text, "passcode");
		Log.i("passcode product_key did", passcode + " " + product_key
				+ " " + did);
		ToastUtils.showShort(this, "扫码成功");
		mHandler.sendEmptyMessage(handler_key.START_BIND.ordinal());

	} else {
		handler = new CaptureActivityHandler(this, cameraManager,
				DecodeThread.ALL_MODE);
	}
}
 
Example #11
Source File: QRCodeReader.java    From reacteu-app with MIT License 6 votes vote down vote up
@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;
}
 
Example #12
Source File: CaptureActivity.java    From DoraemonKit with Apache License 2.0 6 votes vote down vote up
/**
 * Handler scan result
 *
 * @param result
 * @param barcode
 */
public void handleDecode(Result result, Bitmap barcode) {
    inactivityTimer.onActivity();
    playBeepSoundAndVibrate();
    String resultString = result.getText();
    if (TextUtils.isEmpty(resultString)) {
        Toast.makeText(CaptureActivity.this, "Scan failed!", Toast.LENGTH_SHORT).show();
    } else {
        Intent resultIntent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString(INTENT_EXTRA_KEY_QR_SCAN, resultString);
        resultIntent.putExtras(bundle);
        this.setResult(RESULT_OK, resultIntent);
    }
    CaptureActivity.this.finish();
}
 
Example #13
Source File: ParcelableResultDecorator.java    From privacy-friendly-qr-scanner with GNU General Public License v3.0 6 votes vote down vote up
ParcelableResultDecorator(Parcel in) {
    try {
        int numBits = in.readInt();
        long timestamp = in.readLong();
        String text = in.readString();
        BarcodeFormat barcodeFormat = BarcodeFormat.values()[in.readInt()];

        byte[] rawBytes = new byte[in.readInt()];
        in.readByteArray(rawBytes);

        ResultPoint[] resultPoints = new ResultPoint[in.readInt()];
        for(int i = 0; i < resultPoints.length; i++) {
            resultPoints[i] = new ResultPoint(in.readFloat(), in.readFloat());
        }

        this.result = new Result(text, rawBytes, numBits, resultPoints, barcodeFormat, timestamp);
    } catch (Exception e) {
        // result will be null if reading fails
    }
}
 
Example #14
Source File: CaptureActivity.java    From myapplication with Apache License 2.0 6 votes vote down vote up
/**
 * 从相册返回扫描结果
 *
 * @param uri 图片地址
 */
private void operateAlbumScanResult(Uri uri) {
    int myWidth = getResources().getDisplayMetrics().widthPixels;
    int myHeight = getResources().getDisplayMetrics().heightPixels;

    Glide.with(CaptureActivity.this)
            .load(uri)
            .asBitmap()
            .into(new SimpleTarget<Bitmap>(myWidth, myHeight) {
                @Override
                public void onResourceReady(Bitmap resource,
                                            GlideAnimation<? super Bitmap> glideAnimation) {
                    Result resultZxing = new DecodeUtils(DecodeUtils.DECODE_DATA_MODE_ALL)
                            .decodeWithZxing(resource);
                    Log.i(TAG, "resultZxing >> " + resultZxing);

                    if (resultZxing != null) {
                        handleDecode(resultZxing, null);
                    } else {
                        SystemUtils.showHandlerToast(CaptureActivity.this,
                                "未发现二维码/条形码");
                    }
                }
            });
}
 
Example #15
Source File: PDF417Reader.java    From barcodescanner-lib-aar with MIT License 6 votes vote down vote up
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()]);
}
 
Example #16
Source File: GenericMultipleBarcodeReader.java    From QrCodeScanner with GNU General Public License v3.0 5 votes vote down vote up
@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()]);
}
 
Example #17
Source File: CaptureActivity.java    From android-apps with MIT License 5 votes vote down vote up
/**
 * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
 *
 * @param barcode   A bitmap of the captured image.
 * @param rawResult The decoded results which contains the points to draw.
 */
private void drawResultPoints(Bitmap barcode, Result rawResult) {
  ResultPoint[] points = rawResult.getResultPoints();
  if (points != null && points.length > 0) {
    Canvas canvas = new Canvas(barcode);
    Paint paint = new Paint();
    paint.setColor(getResources().getColor(R.color.result_image_border));
    paint.setStrokeWidth(3.0f);
    paint.setStyle(Paint.Style.STROKE);
    Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2);
    canvas.drawRect(border, paint);

    paint.setColor(getResources().getColor(R.color.result_points));
    if (points.length == 2) {
      paint.setStrokeWidth(4.0f);
      drawLine(canvas, paint, points[0], points[1]);
    } else if (points.length == 4 &&
               (rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A ||
                rawResult.getBarcodeFormat() == BarcodeFormat.EAN_13)) {
      // Hacky special case -- draw two lines, for the barcode and metadata
      drawLine(canvas, paint, points[0], points[1]);
      drawLine(canvas, paint, points[2], points[3]);
    } else {
      paint.setStrokeWidth(10.0f);
      for (ResultPoint point : points) {
        canvas.drawPoint(point.getX(), point.getY(), paint);
      }
    }
  }
}
 
Example #18
Source File: ProductResultParser.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
public ProductParsedResult parse(Result result)
    {
        BarcodeFormat barcodeformat = result.getBarcodeFormat();
        if (barcodeformat == BarcodeFormat.UPC_A || barcodeformat == BarcodeFormat.UPC_E || barcodeformat == BarcodeFormat.EAN_8 || barcodeformat == BarcodeFormat.EAN_13) goto _L2; else goto _L1
_L1:
        return null;
_L2:
        String s;
        s = result.getText();
        int i = s.length();
        int j = 0;
label0:
        do
        {
label1:
            {
                if (j >= i)
                {
                    break label1;
                }
                char c = s.charAt(j);
                if (c < '0' || c > '9')
                {
                    break label0;
                }
                j++;
            }
        } while (true);
        if (true) goto _L1; else goto _L3
_L3:
        String s1;
        if (barcodeformat == BarcodeFormat.UPC_E)
        {
            s1 = UPCEReader.convertUPCEtoUPCA(s);
        } else
        {
            s1 = s;
        }
        return new ProductParsedResult(s, s1);
    }
 
Example #19
Source File: UPCAReader.java    From ZXing-Orient with Apache License 2.0 5 votes vote down vote up
private static Result maybeReturnResult(Result result) throws FormatException {
  String text = result.getText();
  if (text.charAt(0) == '0') {
    return new Result(text.substring(1), null, result.getResultPoints(), BarcodeFormat.UPC_A);
  } else {
    throw FormatException.getFormatInstance();
  }
}
 
Example #20
Source File: UPCAReader.java    From QrCodeScanner with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Result decodeRow(int rowNumber,
                        BitArray row,
                        int[] startGuardRange,
                        Map<DecodeHintType,?> hints)
    throws NotFoundException, FormatException, ChecksumException {
  return maybeReturnResult(ean13Reader.decodeRow(rowNumber, row, startGuardRange, hints));
}
 
Example #21
Source File: CaptureActivity.java    From barcodescanner-lib-aar with MIT License 5 votes vote down vote up
private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) {
  // Bitmap isn't used yet -- will be used soon
  if (handler == null) {
    savedResultToShow = result;
  } else {
    if (result != null) {
      savedResultToShow = result;
    }
    if (savedResultToShow != null) {
      Message message = Message.obtain(handler, R.id.decode_succeeded, savedResultToShow);
      handler.sendMessage(message);
    }
    savedResultToShow = null;
  }
}
 
Example #22
Source File: CaptureActivity.java    From CodeScaner with MIT License 5 votes vote down vote up
/**
     * A valid barcode has been found, so give an indication of success and show the results.
     *
     * @param rawResult   The contents of the barcode.
     * @param scaleFactor amount by which thumbnail was scaled
     * @param barcode     A greyscale bitmap of the camera data which was decoded.
     */
    public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) {
        inactivityTimer.onActivity();

        boolean fromLiveScan = barcode != null;
        if (fromLiveScan) {
            beepManager.playBeepSoundAndVibrate();
        }

        String resultString = rawResult.getText();
        //FIXME
        if (TextUtils.isEmpty(resultString)) {
            Toast.makeText(CaptureActivity.this, "扫描二维码失败了", Toast.LENGTH_SHORT).show();
        } else {
            Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putByteArray(KEY_RESULT, resultString.getBytes());
            // 不能使用Intent传递大于40kb的bitmap,可以使用一个单例对象存储这个bitmap
//            bundle.putParcelable("bitmap", barcode);
            resultIntent.putExtras(bundle);
            this.setResult(RESULT_OK, resultIntent);
        }
        if (DEBUG) {
            long time = System.currentTimeMillis() - mScanStartTime;
            Toast.makeText(this, ("Time: " + time / 1000.0f), Toast.LENGTH_SHORT).show();
            drawResultPoints(barcode, scaleFactor, rawResult);
            viewfinderView.drawResultBitmap(barcode);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    CaptureActivity.this.finish();
                }
            }, 3000);
        } else {
            CaptureActivity.this.finish();
        }
    }
 
Example #23
Source File: HttpAndTCPSameJVMTest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testQRWorks() throws Exception {
    HttpGet getRequest = new HttpGet(httpServerUrl + clientPair.token + "/qr");
    String cloneToken;
    try (CloseableHttpResponse response = httpclient.execute(getRequest)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("image/png", response.getFirstHeader("Content-Type").getValue());
        byte[] data = EntityUtils.toByteArray(response.getEntity());
        assertNotNull(data);

        //get the data from the input stream
        BufferedImage image = ImageIO.read(new ByteArrayInputStream(data));

        //convert the image to a binary bitmap source
        LuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        QRCodeReader reader = new QRCodeReader();
        Result result = reader.decode(bitmap);
        String resultString = result.getText();
        assertTrue(resultString.startsWith("blynk://token/clone/"));
        assertTrue(resultString.endsWith("?server=127.0.0.1&port=10443"));
        cloneToken = resultString.substring(
                resultString.indexOf("blynk://token/clone/") + "blynk://token/clone/".length(),
                resultString.indexOf("?server=127.0.0.1&port=10443"));
        assertEquals(32, cloneToken.length());
    }

    clientPair.appClient.send("getProjectByCloneCode " + cloneToken);
    DashBoard dashBoard = clientPair.appClient.parseDash(1);
    assertEquals("My Dashboard", dashBoard.name);
}
 
Example #24
Source File: ScanFromWebPageManager.java    From barcodescanner-lib-aar with MIT License 5 votes vote down vote up
String buildReplyURL(Result rawResult, ResultHandler resultHandler) {
  String result = returnUrlTemplate;
  result = replace(CODE_PLACEHOLDER,
                   returnRaw ? rawResult.getText() : resultHandler.getDisplayContents(), result);
  result = replace(RAW_CODE_PLACEHOLDER, rawResult.getText(), result);
  result = replace(FORMAT_PLACEHOLDER, rawResult.getBarcodeFormat().toString(), result);
  result = replace(TYPE_PLACEHOLDER, resultHandler.getType().toString(), result);
  result = replace(META_PLACEHOLDER, String.valueOf(rawResult.getResultMetadata()), result);
  return result;
}
 
Example #25
Source File: QRCodeReaderView.java    From DanDanPlayForAndroid with MIT License 5 votes vote down vote up
@Override
protected void onPostExecute(Result result) {
    super.onPostExecute(result);

    final QRCodeReaderView view = viewRef.get();

    // Notify we found a QRCode
    if (view != null && result != null && view.mOnQRCodeReadListener != null) {
        // Transform resultPoints to View coordinates
        final PointF[] transformedPoints =
                transformToViewCoordinates(view, result.getResultPoints());
        view.mOnQRCodeReadListener.onQRCodeRead(result.getText(), transformedPoints);
    }
}
 
Example #26
Source File: MultiFormatOneDReader.java    From reacteu-app with MIT License 5 votes vote down vote up
@Override
public Result decodeRow(int rowNumber,
                        BitArray row,
                        Map<DecodeHintType,?> hints) throws NotFoundException {
  for (OneDReader reader : readers) {
    try {
      return reader.decodeRow(rowNumber, row, hints);
    } catch (ReaderException re) {
      // continue
    }
  }

  throw NotFoundException.getNotFoundInstance();
}
 
Example #27
Source File: UPCAReader.java    From weex with Apache License 2.0 5 votes vote down vote up
private static Result maybeReturnResult(Result result) throws FormatException {
  String text = result.getText();
  if (text.charAt(0) == '0') {
    return new Result(text.substring(1), null, result.getResultPoints(), BarcodeFormat.UPC_A);
  } else {
    throw FormatException.getFormatInstance();
  }
}
 
Example #28
Source File: ScanActivity.java    From bither-android with Apache License 2.0 5 votes vote down vote up
public void handleResult(final Result scanResult, Bitmap thumbnailImage,
		final float thumbnailScaleFactor) {
	vibrate();
	// superimpose dots to highlight the key features of the qr code
	final ResultPoint[] points = scanResult.getResultPoints();
	if (points != null && points.length > 0) {
		final Paint paint = new Paint();
		paint.setColor(getResources().getColor(R.color.scan_result_dots));
		paint.setStrokeWidth(10.0f);

		final Canvas canvas = new Canvas(thumbnailImage);
		canvas.scale(thumbnailScaleFactor, thumbnailScaleFactor);
		for (final ResultPoint point : points)
			canvas.drawPoint(point.getX(), point.getY(), paint);
	}

	Matrix matrix = new Matrix();
	matrix.postRotate(90);
	thumbnailImage = Bitmap.createBitmap(thumbnailImage, 0, 0,
			thumbnailImage.getWidth(), thumbnailImage.getHeight(), matrix,
			false);
	scannerView.drawResultBitmap(thumbnailImage);

	final Intent result = getIntent();
	result.putExtra(INTENT_EXTRA_RESULT, scanResult.getText());
	setResult(RESULT_OK, result);

	// delayed finish
	new Handler().post(new Runnable() {
		@Override
		public void run() {
			finish();
		}
	});
}
 
Example #29
Source File: ScanActivity.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
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();
    }
}
 
Example #30
Source File: ResultHandler.java    From reacteu-app with MIT License 5 votes vote down vote up
ResultHandler(Activity activity, ParsedResult result, Result rawResult) {
   this.result = result;
   this.activity = activity;
   this.rawResult = rawResult;
   this.customProductSearch = parseCustomSearchURL();

fakeR = new FakeR(activity);

// Make sure the Shopper button is hidden by default. Without this, scanning a product followed
   // by a QR Code would leave the button on screen among the QR Code actions.
   View shopperButton = activity.findViewById(fakeR.getId("id", "shopper_button"));
   shopperButton.setVisibility(View.GONE);
 }