1. 程式人生 > >Android 把url生成二維碼並貼到給定的底圖上

Android 把url生成二維碼並貼到給定的底圖上

主要是用到了com.google.zxing jar包生成二維碼的功能,這個jar包需要自己接下載 

直接上程式碼

    public static Bitmap CreateBinaryCodeImageByUrl(String url,Bitmap bottomImg,int drawAtPointX,int drawAtPointY,int binaryCodeImgWidth)
    {
        try{
            Map<EncodeHintType, String> hints = new HashMap<EncodeHintType,String>();
            hints.put(EncodeHintType.CHARACTER_SET, 
"UTF-8"); BitMatrix bitMatrix = new MultiFormatWriter().encode(url,BarcodeFormat.QR_CODE,binaryCodeImgWidth,binaryCodeImgWidth,hints); int width = bottomImg.getWidth(); int height = bottomImg.getHeight(); Bitmap targetBmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
for (int posX = 0; posX < width; posX++ ){ for( int posY = 0; posY < height; posY++){ targetBmp.setPixel(posX, posY, bottomImg.getPixel(posX, posY)); } } int limitWidth = drawAtPointX + binaryCodeImgWidth;
int limitHeight = drawAtPointY + binaryCodeImgWidth; for ( int posX = drawAtPointX, matrixX = 0; posX < limitWidth; posX++,matrixX++){ for( int posY = drawAtPointY, matrixY=0; posY < limitHeight; posY++,matrixY++){ targetBmp.setPixel(posX, posY, bitMatrix.get(matrixX, matrixY)?0x000000FF:0xFFFFFFFF); } } return targetBmp; } catch(Exception e){return null; } }

引數說明:url 就是需要轉換成二維碼的圖片,bottomImg 就是底圖,drawAtPositionX 和 drawAtPositionY 表示二維碼在地圖上開始繪製的座標點(底圖左上角為座標原點)

binaryCodeImgWidth 表示生成二維碼的邊長

放上兩個bitmap 的生成方法

//截圖後儲存的圖片地址

Bitmap screenshotImg = BitmapFactory.decodeFile(imagePath);

//直接從資源包中取圖片

InputStream shareImgStream = instance.getResources().getAssets().open(“res/xx.png”);

BitMAP screenshotImg =  BitmapFactory.decodeStream(shareImgStream);

效果如下