android 二维码生成及解析

Demo创建前需要导入zixing.jar包或者创建的依赖类库;(这里是导入的依赖库);jar包可自行去下载

清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example.mycode" >
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.VIBRATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/bt_saomiao"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="扫描二维码" />
    <TextView
        android:id="@+id/tv_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="12sp"
        android:gravity="center"
        android:text="扫码返回的结果"
        android:textSize="20sp" />
    <EditText
        android:id="@+id/input_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入要编码的内容" />
    <Button
        android:id="@+id/creat"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="生成二维码" />
    <Button
        android:id="@+id/creat_logo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="生成带logo的二维码" />
    <ImageView
        android:id="@+id/ivShow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />
</LinearLayout>

java代码:

package example.mycode;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.zxing.activity.CaptureActivity;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class MainActivity extends AppCompatActivity {
    private TextView tv_result;
    private ImageView ivShow;
    private EditText input_content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv_result = (TextView) findViewById(R.id.tv_result);
        ivShow = (ImageView) findViewById(R.id.ivShow);
        input_content = (EditText) findViewById(R.id.input_content);
    }

    public void click(View view) {
        switch (view.getId()) {
            case R.id.bt_saomiao://扫描
                Toast.makeText(MainActivity.this, "请对准要扫描的条形码或者二维码......", Toast.LENGTH_SHORT).show();
                Intent startScan = new Intent(MainActivity.this, CaptureActivity.class);
                // startActivity(startScan);
                startActivityForResult(startScan, 0);
                break;

            case R.id.creat://创建普通二维码
                creatCode();
                break;

            case R.id.creat_logo://创建带有logo的二维码
                creat_logoCode();
                break;
        }
    }

    /**
     * 创建普通二维码
     */
    String content;//编辑框输入的内容(
    private void creatCode() {
        content = input_content.getText().toString();
        if (TextUtils.isEmpty(content)) {
            Toast.makeText(MainActivity.this, "请输入编码内容...", Toast.LENGTH_SHORT).show();
        } else {
            try {
                //TODO 也可以生成二维码
//                    Bitmap qrcod = EncodingHandler.createQRCode(in, 400);
//                    img.setImageBitmap(qrcod);
                // 写入数据信息到图片
                int width = 400;
                int height = 400;
                QRCodeWriter qrCodeWriter = new QRCodeWriter();
                //将内容编码
                BitMatrix matrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height);
                //创建像素数组
                int ms[] = new int[width * height];
                //变换赋值
                for (int y = 0; y < height; y++) {
                    for (int x = 0; x < width; x++) {
                        if (matrix.get(x, y)) {
                            ms[y * width + x] = 0xff000000;  //黑点
                        } else {
                            ms[y * width + x] = 0xffffffff; //白点
                        }
                    }
                }

                //TODO 缓存;创建bitmap对象
                Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                //setPixels是可以向图像写入颜色;根据新像素生成新图片  //获取像素 bitmap.getPixel
                image.setPixels(ms, 0, width, 0, 0, width, height);
                //二维码存储路径
                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/普通二维码_" + System.currentTimeMillis() + ".png";
                FileOutputStream out = new FileOutputStream(path);
                //TODO 压缩
                image.compress(Bitmap.CompressFormat.PNG, 100, out);
                //TODO 展示图片
                ivShow.setImageBitmap(image);
                Log.e("MMMM", "创建成功");
            } catch (WriterException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建带有logo的二维码
     */
    private void creat_logoCode() {
        content = input_content.getText().toString();
        if (TextUtils.isEmpty(content)) {
            Toast.makeText(MainActivity.this, "请输入编码内容...", Toast.LENGTH_SHORT).show();
        } else {
            try {
                // 写入数据信息到图片
                int width = 400, height = 400;
                QRCodeWriter qrCodeWriter = new QRCodeWriter();
                //把内容编码
                BitMatrix matrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height);
                //创建像素数组
                int ms[] = new int[width * height];
                //变换赋值
                for (int y = 0; y < height; y++) {
                    for (int x = 0; x < width; x++) {
                        if (matrix.get(x, y)) {
                            ms[y * width + x] = 0xff000000; //黑点
                        } else {
                            ms[y * width + x] = 0xffffffff;//白点
                        }
                    }
                }
                //TODO 缓存 创建bitmap对象
                Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                //setPixels是可以向图像写入颜色;根据新像素生成新图片  //获取像素 bitmap.getPixels()
                image.setPixels(ms, 0, width, 0, 0, width, height);
                //logo的地址
                Bitmap logo = BitmapFactory.decodeFile("/storage/sdcard0/bb.png");
                //添加logo到二维码
                image = insertLogo(image, logo);
                //TODO 展示图片
                ivShow.setImageBitmap(image);

                //存储生成的二维码地址
                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/logo二维码_" + System.currentTimeMillis() + ".png";
                FileOutputStream out = new FileOutputStream(path);
                //TODO 压缩
                image.compress(Bitmap.CompressFormat.PNG, 100, out);
                Log.e("MMMM", "创建成功");

            } catch (WriterException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 插入logo图片
     *
     * @param src
     * @param logo
     * @return
     */
    public Bitmap insertLogo(Bitmap src, Bitmap logo) {
        //获取两张图片的宽高
        int width = src.getWidth();
        int height = src.getHeight();
        int logowidth = logo.getWidth();
        int logoheight = logo.getHeight();
        //大小图片的比例
        float scale = width * 1.0f / 5 / logowidth;
        //缓冲区
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        //获取缓冲区画布
        Canvas canvas = new Canvas(bitmap);
        //画大图片
        canvas.drawBitmap(src, 0, 0, null);
        canvas.scale(scale, scale, width / 2, height / 2);
        //画小图片
        canvas.drawBitmap(logo, (width - logoheight) / 2, (height - logoheight) / 2, null);
        //保存所画内容
        canvas.save(Canvas.ALL_SAVE_FLAG);
        //还原画布
        canvas.restore();
        return bitmap;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            String result = data.getExtras().getString("result");
            tv_result.setText(result);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值