Android扫码/生成二维码并保存

使用Zxing第三方库完成解码。

声明:

使用的源Demo来自

源demo可以完美编译运行。

以下是我做的改动。

使得解析出来的文本可选:

<TextViewandroid:id="@+id/scan_result"android:layout_width="fill_parent"android:layout_height="wrap_content"android:textColor="@android:color/black"android:textIsSelectable="true"android:textSize="18sp" />

添加菜单:

可以保存生成的二维码图片到手机:

/** * 保存生成的二維碼圖片 */private void saveQrCodePicture() {final File qrImage = new File(Environment.getExternalStorageDirectory(), qrStrEditText.getText().toString()+".jpg");if(qrImage.exists()){qrImage.delete();}try {qrImage.createNewFile();} catch (IOException e) {e.printStackTrace();}FileOutputStream fOut = null;try {fOut = new FileOutputStream(qrImage);} catch (FileNotFoundException e) {e.printStackTrace();}if(qrCodeBitmap == null){Toast.makeText(this,R.string.image_not_exist, Toast.LENGTH_SHORT).show();return;}qrCodeBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);try {fOut.flush();fOut.close();Toast.makeText(this,R.string.image_save_sucess, Toast.LENGTH_SHORT).show();} catch (IOException e) {e.printStackTrace();}}其中:qrCodeBitmap 生成的二维码Bitmap。</pre><pre name="code" class="html">

注意:在这里可能会遇到“保存的二维码图片是全黑”的问题。原因是在源代码在生成二维码的时候,只是对有数据的地方使用了黑色填充,没有数据的地方没有处理,,而bitmap在compress成jpg/png的时候,默认背景是黑色的,所以就是全黑了。解决办法是在生成二维码的时候讲没有数据的部分使用白色填充,就可以了。具体代码如下:

</pre><pre name="code" class="java"><pre name="code" class="java">for (int y = 0; y < height; y++) {for (int x = 0; x < width; x++) {if (matrix.get(x, y)) {pixels[y * width + x] = BLACK;}else{pixels[y * width + x] = WHITE;}}}就是在for循环里面加一个else,填充白色。

还有另一个问题就是SD卡权限问题:

要将图片保存到SD卡中,就需要有SD卡的读写权限。

在mainfest中添加

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

找寻隐藏在山间的纯净和那“鸟鸣山更幽”的飞鸟。

Android扫码/生成二维码并保存

相关文章:

你感兴趣的文章:

标签云: