Skip to content

Instantly share code, notes, and snippets.

@adrianoluis
Created February 8, 2017 02:51
Show Gist options
  • Select an option

  • Save adrianoluis/fa9374d7f2f8ca1115b00cc83cd7aacd to your computer and use it in GitHub Desktop.

Select an option

Save adrianoluis/fa9374d7f2f8ca1115b00cc83cd7aacd to your computer and use it in GitHub Desktop.

Revisions

  1. adrianoluis revised this gist Feb 8, 2017. 1 changed file with 0 additions and 4 deletions.
    4 changes: 0 additions & 4 deletions QRCodeUtil.java
    Original file line number Diff line number Diff line change
    @@ -11,10 +11,6 @@ public class QRCodeUtil {

    private QRCodeUtil() {}

    public static Bitmap encodeAsBitmap(String source, float width, float height) {
    return encodeAsBitmap(source, ViewUtil.dpToPx(width), ViewUtil.dpToPx(height));
    }

    public static Bitmap encodeAsBitmap(String source, int width, int height) {
    BitMatrix result;

  2. adrianoluis created this gist Feb 8, 2017.
    45 changes: 45 additions & 0 deletions QRCodeUtil.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@

    import android.graphics.Bitmap;
    import android.graphics.Color;

    import com.google.zxing.BarcodeFormat;
    import com.google.zxing.MultiFormatWriter;
    import com.google.zxing.WriterException;
    import com.google.zxing.common.BitMatrix;

    public class QRCodeUtil {

    private QRCodeUtil() {}

    public static Bitmap encodeAsBitmap(String source, float width, float height) {
    return encodeAsBitmap(source, ViewUtil.dpToPx(width), ViewUtil.dpToPx(height));
    }

    public static Bitmap encodeAsBitmap(String source, int width, int height) {
    BitMatrix result;

    try {
    result = new MultiFormatWriter().encode(source, BarcodeFormat.QR_CODE, width, height, null);
    } catch (IllegalArgumentException | WriterException e) {
    // Unsupported format
    return null;
    }

    final int w = result.getWidth();
    final int h = result.getHeight();
    final int[] pixels = new int[w * h];

    for (int y = 0; y < h; y++) {
    final int offset = y * w;
    for (int x = 0; x < w; x++) {
    pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.WHITE;
    }
    }

    final Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, width, 0, 0, w, h);

    return bitmap;
    }

    }