Search in sources :

Example 1 with WriterException

use of com.google.zxing.WriterException in project android-zxingLibrary by yipianfengye.

the class CodeUtils method createImage.

/**
     * 生成二维码图片
     * @param text
     * @param w
     * @param h
     * @param logo
     * @return
     */
public static Bitmap createImage(String text, int w, int h, Bitmap logo) {
    if (TextUtils.isEmpty(text)) {
        return null;
    }
    try {
        Bitmap scaleLogo = getScaleLogo(logo, w, h);
        int offsetX = w / 2;
        int offsetY = h / 2;
        int scaleWidth = 0;
        int scaleHeight = 0;
        if (scaleLogo != null) {
            scaleWidth = scaleLogo.getWidth();
            scaleHeight = scaleLogo.getHeight();
            offsetX = (w - scaleWidth) / 2;
            offsetY = (h - scaleHeight) / 2;
        }
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //容错级别
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        //设置空白边距的宽度
        hints.put(EncodeHintType.MARGIN, 0);
        BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, w, h, hints);
        int[] pixels = new int[w * h];
        for (int y = 0; y < h; y++) {
            for (int x = 0; x < w; x++) {
                if (x >= offsetX && x < offsetX + scaleWidth && y >= offsetY && y < offsetY + scaleHeight) {
                    int pixel = scaleLogo.getPixel(x - offsetX, y - offsetY);
                    if (pixel == 0) {
                        if (bitMatrix.get(x, y)) {
                            pixel = 0xff000000;
                        } else {
                            pixel = 0xffffffff;
                        }
                    }
                    pixels[y * w + x] = pixel;
                } else {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * w + x] = 0xff000000;
                    } else {
                        pixels[y * w + x] = 0xffffffff;
                    }
                }
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, w, 0, 0, w, h);
        return bitmap;
    } catch (WriterException e) {
        e.printStackTrace();
    }
    return null;
}
Also used : Bitmap(android.graphics.Bitmap) BinaryBitmap(com.google.zxing.BinaryBitmap) QRCodeWriter(com.google.zxing.qrcode.QRCodeWriter) EncodeHintType(com.google.zxing.EncodeHintType) Hashtable(java.util.Hashtable) BitMatrix(com.google.zxing.common.BitMatrix) WriterException(com.google.zxing.WriterException)

Example 2 with WriterException

use of com.google.zxing.WriterException in project weex-example by KalicyZhou.

the class PDF417HighLevelEncoder method determineConsecutiveBinaryCount.

/**
   * Determines the number of consecutive characters that are encodable using binary compaction.
   *
   * @param msg      the message
   * @param startpos the start position within the message
   * @param encoding the charset used to convert the message to a byte array
   * @return the requested character count
   */
private static int determineConsecutiveBinaryCount(String msg, int startpos, Charset encoding) throws WriterException {
    final CharsetEncoder encoder = encoding.newEncoder();
    int len = msg.length();
    int idx = startpos;
    while (idx < len) {
        char ch = msg.charAt(idx);
        int numericCount = 0;
        while (numericCount < 13 && isDigit(ch)) {
            numericCount++;
            //textCount++;
            int i = idx + numericCount;
            if (i >= len) {
                break;
            }
            ch = msg.charAt(i);
        }
        if (numericCount >= 13) {
            return idx - startpos;
        }
        ch = msg.charAt(idx);
        if (!encoder.canEncode(ch)) {
            throw new WriterException("Non-encodable character detected: " + ch + " (Unicode: " + (int) ch + ')');
        }
        idx++;
    }
    return idx - startpos;
}
Also used : CharsetEncoder(java.nio.charset.CharsetEncoder) WriterException(com.google.zxing.WriterException)

Example 3 with WriterException

use of com.google.zxing.WriterException in project weex-example by KalicyZhou.

the class QRCodeEncoder method encodeFromStreamExtra.

// Handles send intents from the Contacts app, retrieving a contact as a VCARD.
private void encodeFromStreamExtra(Intent intent) throws WriterException {
    format = BarcodeFormat.QR_CODE;
    Bundle bundle = intent.getExtras();
    if (bundle == null) {
        throw new WriterException("No extras");
    }
    Uri uri = bundle.getParcelable(Intent.EXTRA_STREAM);
    if (uri == null) {
        throw new WriterException("No EXTRA_STREAM");
    }
    byte[] vcard;
    String vcardString;
    InputStream stream = null;
    try {
        stream = activity.getContentResolver().openInputStream(uri);
        if (stream == null) {
            throw new WriterException("Can't open stream for " + uri);
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[2048];
        int bytesRead;
        while ((bytesRead = stream.read(buffer)) > 0) {
            baos.write(buffer, 0, bytesRead);
        }
        vcard = baos.toByteArray();
        vcardString = new String(vcard, 0, vcard.length, "UTF-8");
    } catch (IOException ioe) {
        throw new WriterException(ioe);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
            // continue
            }
        }
    }
    Log.d(TAG, "Encoding share intent content:");
    Log.d(TAG, vcardString);
    Result result = new Result(vcardString, vcard, null, BarcodeFormat.QR_CODE);
    ParsedResult parsedResult = ResultParser.parseResult(result);
    if (!(parsedResult instanceof AddressBookParsedResult)) {
        throw new WriterException("Result was not an address");
    }
    encodeQRCodeContents((AddressBookParsedResult) parsedResult);
    if (contents == null || contents.isEmpty()) {
        throw new WriterException("No content to encode");
    }
}
Also used : AddressBookParsedResult(com.google.zxing.client.result.AddressBookParsedResult) Bundle(android.os.Bundle) InputStream(java.io.InputStream) ParsedResult(com.google.zxing.client.result.ParsedResult) AddressBookParsedResult(com.google.zxing.client.result.AddressBookParsedResult) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Uri(android.net.Uri) WriterException(com.google.zxing.WriterException) Result(com.google.zxing.Result) ParsedResult(com.google.zxing.client.result.ParsedResult) AddressBookParsedResult(com.google.zxing.client.result.AddressBookParsedResult)

Example 4 with WriterException

use of com.google.zxing.WriterException in project weex-example by KalicyZhou.

the class EncodeActivity method share.

private void share() {
    QRCodeEncoder encoder = qrCodeEncoder;
    if (encoder == null) {
        // Odd
        Log.w(TAG, "No existing barcode to send?");
        return;
    }
    String contents = encoder.getContents();
    if (contents == null) {
        Log.w(TAG, "No existing barcode to send?");
        return;
    }
    Bitmap bitmap;
    try {
        bitmap = encoder.encodeAsBitmap();
    } catch (WriterException we) {
        Log.w(TAG, we);
        return;
    }
    if (bitmap == null) {
        return;
    }
    File bsRoot = new File(Environment.getExternalStorageDirectory(), "BarcodeScanner");
    File barcodesRoot = new File(bsRoot, "Barcodes");
    if (!barcodesRoot.exists() && !barcodesRoot.mkdirs()) {
        Log.w(TAG, "Couldn't make dir " + barcodesRoot);
        showErrorMessage(R.string.msg_unmount_usb);
        return;
    }
    File barcodeFile = new File(barcodesRoot, makeBarcodeFileName(contents) + ".png");
    if (!barcodeFile.delete()) {
        Log.w(TAG, "Could not delete " + barcodeFile);
    // continue anyway
    }
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(barcodeFile);
        bitmap.compress(Bitmap.CompressFormat.PNG, 0, fos);
    } catch (FileNotFoundException fnfe) {
        Log.w(TAG, "Couldn't access file " + barcodeFile + " due to " + fnfe);
        showErrorMessage(R.string.msg_unmount_usb);
        return;
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ioe) {
            // do nothing
            }
        }
    }
    Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:"));
    intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name) + " - " + encoder.getTitle());
    intent.putExtra(Intent.EXTRA_TEXT, contents);
    intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + barcodeFile.getAbsolutePath()));
    intent.setType("image/png");
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
    startActivity(Intent.createChooser(intent, null));
}
Also used : Bitmap(android.graphics.Bitmap) FileOutputStream(java.io.FileOutputStream) FileNotFoundException(java.io.FileNotFoundException) Intent(android.content.Intent) IOException(java.io.IOException) File(java.io.File) WriterException(com.google.zxing.WriterException)

Example 5 with WriterException

use of com.google.zxing.WriterException in project weex-example by KalicyZhou.

the class EncodeActivity method onResume.

@Override
protected void onResume() {
    super.onResume();
    // This assumes the view is full screen, which is a good assumption
    WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
    Display display = manager.getDefaultDisplay();
    Point displaySize = new Point();
    display.getSize(displaySize);
    int width = displaySize.x;
    int height = displaySize.y;
    int smallerDimension = width < height ? width : height;
    smallerDimension = smallerDimension * 7 / 8;
    Intent intent = getIntent();
    if (intent == null) {
        return;
    }
    try {
        boolean useVCard = intent.getBooleanExtra(USE_VCARD_KEY, false);
        qrCodeEncoder = new QRCodeEncoder(this, intent, smallerDimension, useVCard);
        Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
        if (bitmap == null) {
            Log.w(TAG, "Could not encode barcode");
            showErrorMessage(R.string.msg_encode_contents_failed);
            qrCodeEncoder = null;
            return;
        }
        ImageView view = (ImageView) findViewById(R.id.image_view);
        view.setImageBitmap(bitmap);
        TextView contents = (TextView) findViewById(R.id.contents_text_view);
        if (intent.getBooleanExtra(Intents.Encode.SHOW_CONTENTS, true)) {
            contents.setText(qrCodeEncoder.getDisplayContents());
            setTitle(qrCodeEncoder.getTitle());
        } else {
            contents.setText("");
            setTitle("");
        }
    } catch (WriterException e) {
        Log.w(TAG, "Could not encode barcode", e);
        showErrorMessage(R.string.msg_encode_contents_failed);
        qrCodeEncoder = null;
    }
}
Also used : Bitmap(android.graphics.Bitmap) Intent(android.content.Intent) TextView(android.widget.TextView) Point(android.graphics.Point) ImageView(android.widget.ImageView) Point(android.graphics.Point) WriterException(com.google.zxing.WriterException) WindowManager(android.view.WindowManager) Display(android.view.Display)

Aggregations

WriterException (com.google.zxing.WriterException)32 Bitmap (android.graphics.Bitmap)14 BitMatrix (com.google.zxing.common.BitMatrix)10 QRCodeWriter (com.google.zxing.qrcode.QRCodeWriter)10 IOException (java.io.IOException)8 Intent (android.content.Intent)7 EncodeHintType (com.google.zxing.EncodeHintType)7 BitArray (com.google.zxing.common.BitArray)7 FileOutputStream (java.io.FileOutputStream)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 Hashtable (java.util.Hashtable)4 Point (android.graphics.Point)3 Uri (android.net.Uri)3 Bundle (android.os.Bundle)3 Display (android.view.Display)3 WindowManager (android.view.WindowManager)3 ImageView (android.widget.ImageView)3 TextView (android.widget.TextView)3 Result (com.google.zxing.Result)3 AddressBookParsedResult (com.google.zxing.client.result.AddressBookParsedResult)3