Android Using ZXing Generate QR Code

后端 未结 4 1032
你的背包
你的背包 2020-12-29 21:06

I was having some problem when trying to generate QR code in Android Programming. Here is the Tutorial I followed. When my generate button on click, I am calling this method

4条回答
  •  生来不讨喜
    2020-12-29 22:03

    Here is how you can generate an image with QR code from a string -

    screenshot

    First add the following line to build.gradle file in your Android Studio project:

    dependencies {
        ....
        compile 'com.google.zxing:core:3.2.1'
    }
    

    Or if still using Eclipse with ADT-plugin add ZXing's core.jar from Maven repository to the libs subdir of your Eclipse ADT project (here fullscreen):

    Eclipse

    And then use the sample code from my MainActivity.java:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView imageView = (ImageView) findViewById(R.id.qrCode);
        try {
            Bitmap bitmap = encodeAsBitmap(STR);
            imageView.setImageBitmap(bitmap);
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }
    
    Bitmap encodeAsBitmap(String str) throws WriterException {
        BitMatrix result;
        try {
            result = new MultiFormatWriter().encode(str, 
                BarcodeFormat.QR_CODE, WIDTH, WIDTH, null);
        } catch (IllegalArgumentException iae) {
            // Unsupported format
            return null;
        }
        int w = result.getWidth();
        int h = result.getHeight();
        int[] pixels = new int[w * h];
        for (int y = 0; y < h; y++) {
            int offset = y * w;
            for (int x = 0; x < w; x++) {
                pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, w, h);
        return bitmap;
    }
    

提交回复
热议问题