【源码】二维码生成及美化

activity.xml




    

AndroidManifest.xml



    

    
        
            
                

                
            
        
    

MainActivity.java

package com.showimage.start.showimage;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    private static final int height = 240;
    private static final int width = 240;
    private ImageView imageView;


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

        imageView = (ImageView) findViewById(R.id.imageView);
        Bitmap mBitmap = null;
        //生成不带logo的二维码
        //mBitmap = MakeQRCodeUtil.generateQRCode("https://www.baidu.com", width, height);
        //生成带logo的二维码
        mBitmap = MakeQRCodeUtil.generateQRCode(MakeQRCodeUtil.gainBitmap(this, R.drawable.test2),"https://www.baidu.com", width, height);
        //添加背景
        mBitmap = MakeQRCodeUtil.addBackground(mBitmap, MakeQRCodeUtil.gainBitmap(this, R.drawable.test1));
        //添加水印
        mBitmap = MakeQRCodeUtil.composeWatermark(mBitmap, MakeQRCodeUtil.gainBitmap(this, R.drawable.test3));
        //添加文字
        mBitmap = MakeQRCodeUtil.addTextToBitmap(mBitmap, "愿岁月静好,现世安稳");
        imageView.setImageBitmap(mBitmap);
    }
}

MakeQRCodeUtil.java

package com.showimage.start.showimage;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.util.HashMap;

/**
 * Created on 2016/2/24.
 * 生成二维码的工具类
 */
public class MakeQRCodeUtil {
    //转换位图
    private static Bitmap bitMatrix2Bitmap(BitMatrix matrix) {
        int WIDTH = matrix.getWidth();
        int HEIGHT = matrix.getHeight();
        int[] pixels = new int[WIDTH * HEIGHT];
        for (int y = 0; y < WIDTH; y++) {
            for (int x = 0; x < HEIGHT; x++) {
                int color = Color.WHITE;
                if (matrix.get(x, y)) {
                    color = 0xFF0094FF + y/2;// 蓝色
                    // 有内容的部分,颜色设置为黑色,当然这里可以自己修改成喜欢的颜色
//                    if (x < WIDTH / 2 && y < HEIGHT / 2) {
//                        color = 0xFF0094FF;// 蓝色
//                        //Integer.toHexString(new Random().nextInt());
//                    } else if (x < WIDTH / 2 && y > HEIGHT / 2) {
//                        color = 0xFFFED545;// 黄色
//                    } else if (x > WIDTH / 2 && y > HEIGHT / 2) {
//                        color = 0xFF5ACF00;// 绿色
//                    } else {
//                        color = 0xFF000000;// 黑色
//                    }
                }
                pixels[x + (y * WIDTH)] = color;
            }
        }

        Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.RGB_565);
        bitmap.setPixels(pixels, 0, WIDTH, 0, 0, WIDTH, HEIGHT);
        return bitmap;
    }

    //添加logo
    private static Bitmap addLogo(Bitmap src, Bitmap logo) {
        if (logo == null) {
            return src;
        }
        // 获取图片的宽高
        int srcWidth = src.getWidth();
        int srcHeight = src.getHeight();
        int logoWidth = logo.getWidth();
        int logoHeight = logo.getHeight();
        if (logoWidth == 0 || logoHeight == 0) {
            return src;
        }
        // logo大小为二维码整体大小的1/5
        float scaleFactor = srcWidth * 1.0f / 5 / logoWidth;
        Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
        try {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(src, 0, 0, null);
            canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
            canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);
            canvas.save(Canvas.ALL_SAVE_FLAG);
            canvas.restore();
        } catch (Exception e) {
            bitmap = null;
            e.getStackTrace();
        }

        return bitmap;
    }

    /**
     * 从资源文件中获取图片
     *
     * @param context    上下文
     * @param drawableId 资源文件id
     * @return
     */
    public static Bitmap gainBitmap(Context context, int drawableId) {
        Bitmap bmp = BitmapFactory.decodeResource(context.getResources(),
                drawableId);
        return bmp;
    }

    /**
     * 在图片右下角添加水印
     *
     * @param srcBMP  原图
     * @param markBMP 水印图片
     * @return 合成水印后的图片
     */
    public static Bitmap composeWatermark(Bitmap srcBMP, Bitmap markBMP) {
        if (srcBMP == null) {
            return null;
        }
        // 创建一个新的和SRC长度宽度一样的位图
        Bitmap newb = Bitmap.createBitmap(srcBMP.getWidth(),
                srcBMP.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas cv = new Canvas(newb);
        // 在 0,0坐标开始画入原图
        cv.drawBitmap(srcBMP, 0, 0, null);
        // 在原图的右下角画入水印
        cv.drawBitmap(markBMP, srcBMP.getWidth() - markBMP.getWidth() * 2 / 5,
                srcBMP.getHeight() * 6 / 7, null);
        // 保存
        cv.save(Canvas.ALL_SAVE_FLAG);
        // 存储
        cv.restore();
        return newb;
    }

    /**
     * 给二维码图片加背景
     */
    public static Bitmap addBackground(Bitmap foreground, Bitmap background) {
        int bgWidth = background.getWidth();
        int bgHeight = background.getHeight();
        int fgWidth = foreground.getWidth();
        int fgHeight = foreground.getHeight();
        Bitmap newmap = Bitmap
                .createBitmap(bgWidth, bgHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newmap);
        canvas.drawBitmap(background, 0, 0, null);
        canvas.drawBitmap(foreground, (bgWidth - fgWidth) / 2,
                (bgHeight - fgHeight) * 2 / 5 + 70, null);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return newmap;
    }
//-----------------------------------------------------------------------------------------------------------------------
    public static Bitmap generateQRCode(Bitmap logo, String content, int width, int height) {
        return  addLogo(generateQRCode(content, width, height), logo);
    }

    //生成二维码
    public static Bitmap generateQRCode(String content, int width, int height) {
        try {
            HashMap hints = new HashMap();
            // 设置编码方式utf-8
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            //设置二维码的纠错级别为h
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            BitMatrix matrix = new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE, width, height, hints);
            return bitMatrix2Bitmap(matrix);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Bitmap addTextToBitmap(Bitmap bmpSrc, String text) {
        int srcWidth = bmpSrc.getWidth();
        int srcHeight = bmpSrc.getHeight();

        // 先计算text所需要的height
        int textSize = 20;
        int padding = 3;
        int textLinePadding = 1;
        // 每行的文字
        int perLineWords = (srcWidth - 2 * padding) / textSize;
        int lineNum = text.length() / perLineWords;
        lineNum = text.length() % perLineWords == 0 ? lineNum : lineNum + 1;
        int textTotalHeight = lineNum * (textSize + textLinePadding) + 2 * padding;

        Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight + textTotalHeight,
                Bitmap.Config.ARGB_8888);
        try {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawColor(Color.WHITE);
            canvas.drawBitmap(bmpSrc, 0, 0, null);
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setColor(Color.BLACK);
            paint.setTextSize(textSize);
            String lineText;
            for (int i = 0, startY = srcHeight + textSize, start, end; i < lineNum; i++) {
                start = i * perLineWords;
                end = start + perLineWords;
                lineText = text.substring(start, end > text.length() ? text.length() : end);
                canvas.drawText(lineText, padding, startY, paint);
                startY += textSize + textLinePadding;
            }
            canvas.save(Canvas.ALL_SAVE_FLAG);
            canvas.restore();
        } catch (Exception e) {
            bitmap = null;
            e.getStackTrace();
        }
        return bitmap;
    }
}

以上就是全部源码,如果有调试问题,欢迎留言告知,谢谢!!

你可能感兴趣的:(android应用,源码,二维码,彩色二维码)