关于Android二维码——1.生成二维码

使用zxing包。创建项目,建一个imageview用来显示生成的二维码。

两种二维码,一、纯二维码,比较简单识别率也高。二、中间嵌入图片的二维码。需要在生成二维码后嵌入图片。

一、

public class mainActivity extends Activity{
private int QR_WIDTH = 300;  //二维码的宽
private int QR_HEIGHT = 300; //二维码的高
int FOREGROUND_COLOR = 0xff000000;//黑色
// 背景色
int BACKGROUND_COLOR = 0xffffffff;//白色
private int logoWidth = 40;
private static final int IMAGE_HALFWIDTH = 40;//宽度值,影响中间图片大小  
private ImageView rg;
private Bitmap logo; 
private String str = "648567128@qq.com....";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.erweima);
Log.i("tt","mylog:11");
rg = (ImageView) findViewById(R.id.erweima);
logo=BitmapFactory.decodeResource(super.getResources(),R.drawable.dd);
}

@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
//不嵌入图片的 原始二维码
createQRImage(str);
//嵌入图片的二维码
/*
try {
cretaeBitmap(str,logo);
} catch (WriterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}

}

//上面为Activity固定模式,下面为 调用的方法。方法放在类中。我这里是单独写出来的 ,要拷贝的话 放入到上一个括号中。

 public void createQRImage(String url)
   {
       try
       {
           //判断URL合法性
           if (url == null || "".equals(url) || url.length() < 1)
           {
               return;
           }
           Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
           hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
           //图像数据转换,使用了矩阵转换
           BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
           int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
           //下面这里按照二维码的算法,逐个生成二维码的图片,
           //两个for循环是图片横列扫描的结果
           for (int y = 0; y < QR_HEIGHT; y++)
           {
               for (int x = 0; x < QR_WIDTH; x++)
               {
                   if (bitMatrix.get(x, y))
                   {
                       pixels[y * QR_WIDTH + x] = 0xff000000;
                   }else
                   {
                       pixels[y * QR_WIDTH + x] = 0xffffffff;
                   }
               }
           }
           //生成二维码图片的格式,使用ARGB_8888
           Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888);
           bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
           //显示到一个ImageView上面
           rg.setImageBitmap(bitmap);
           
       }
       catch (WriterException e)
       {
           e.printStackTrace();
       }
   }

//至此 不带图片的二维码就会 ok。下面是 嵌入图片的二维码生成方式。把onStart中的方法注释,下面的方法放出来。

//嵌入的图片为bmp格式的位图。事先放入工程中,并找到该图片、下面方法中的传入的icon就为嵌入的图片名。我在类变量中就先拿到该嵌入

//图:logo=BitmapFactory.decodeResource(super.getResources(),R.drawable.dd);

 public void cretaeBitmap(String str, Bitmap icon) throws WriterException {
// 缩放一个40*40的图片
icon = Untilly.zoomBitmap(icon, IMAGE_HALFWIDTH);
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//hints.put(EncodeHintType.MARGIN, 1);
// 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
BitMatrix matrix = new MultiFormatWriter().encode(str,BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
int width = matrix.getWidth();
int height = matrix.getHeight();
// 二维矩阵转为一维像素数组,也就是一直横着排了
int halfW = width / 2;
int halfH = height / 2;
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (x > halfW - IMAGE_HALFWIDTH && x < halfW + IMAGE_HALFWIDTH&& y > halfH - IMAGE_HALFWIDTH&& y < halfH + IMAGE_HALFWIDTH) {
pixels[y * width + x] = icon.getPixel(x - halfW+ IMAGE_HALFWIDTH, y - halfH + IMAGE_HALFWIDTH);
} else {
if (matrix.get(x, y)) {
pixels[y * width + x] = FOREGROUND_COLOR;
} else { // 无信息设置像素点为白色
pixels[y * width + x] = BACKGROUND_COLOR;
}
}


}
}
Bitmap mBitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
// 通过像素数组生成bitmap
mBitmap.setPixels(pixels, 0, width, 0, 0, width, height);
rg.setImageBitmap(mBitmap);
// return mBitmap;
}

//这里要调用一个工具类来缩放 嵌入的图片。

//Untilly.java  这里不怎么会传文件 我就拷贝上来,放入工程中就ok

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Random;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.widget.Toast;




/**
 * 工具类
 * @author LJC
 *
 */
public class Untilly {
/**
*  缩放图片
* @param icon
* @param h
* @return
*/
public static Bitmap  zoomBitmap(Bitmap icon,int h){
// 缩放图片
Matrix m = new Matrix();
float sx = (float) 2 * h / icon.getWidth();
float sy = (float) 2 * h / icon.getHeight();
m.setScale(sx, sy);
// 重新构造一个2h*2h的图片
return Bitmap.createBitmap(icon, 0, 0,icon.getWidth(), icon.getHeight(), m, false);
}


/**

* @param fileName
* @return byte[]
*/
public static  byte[] readFile(String fileName)
{
FileInputStream fis=null;
ByteArrayOutputStream baos=null;
byte[] data=null;
try {
fis=new FileInputStream(fileName);
byte[] buffer=new byte[8*1024];
int readSize=-1;
baos=new ByteArrayOutputStream();
while((readSize=fis.read(buffer))!=-1)
{
baos.write(buffer, 0, readSize);
}
return baos.toByteArray();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally
{
try {
if (fis!=null)
{
fis.close();
}
if (baos!=null)
baos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return data;

}

/**

* @param data 数据
* @param path 路径
* @param fileName 文件名
* @return true成功 false失败
*/
public static boolean writeToSdcard(byte[]data,String path,String fileName)
{
FileOutputStream fos=null;
try {
//判断有没有文件夹
File filePath=new File(path);
if(!filePath.exists())
{
//创建文件夹
filePath.mkdirs();
}

//判断有没有同名的文件
File file=new File(path+fileName);
//有的话,删除
if (file.exists())
{
file.delete();
}
//写文件
fos=new FileOutputStream(file);
fos.write(data);
fos.flush();
return true;
// }
 
} catch (Exception e) {
return false;
// TODO: handle exception
}finally
{
try {
if (fos!=null)
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

//到这 二维码的生成就ok了  建议嵌入的图片不能过大,过大二维码就扫不出来了。


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值