本篇文章中涉及到的代码还未经过认真验证,因此将两篇文章的代码复制下来并将转载地址附在每一片代码的后面供以后详细参考。
(第一种)
private Bitmap encodeAsBitmap(String contents, BarcodeFormat format,
int desiredWidth, int desiredHeight) throws WriterException {
final int WHITE = 0xFFFFFFFF; // 可以指定其他颜色,让二维码变成彩色效果
final int BLACK = 0xFF000000;
HashMap<EncodeHintType, String> hints = null;
String encoding = guessAppropriateEncoding(contents);
if (encoding != null) {
hints = new HashMap<EncodeHintType, String>(2);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result = writer.encode(contents, format, desiredWidth,
desiredHeight, hints);
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
// All are 0, or black, by default
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) {
return "UTF-8";
}
}
return null;
}
转载地址:android zxing 生成二维码
(第二种)
package com.demo;
import java.io.File;
import java.util.Hashtable;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class Test
{
private static String CHANGE_LINE = "\r\n";
/**
* 编码
*
* @param contents
* @param width
* @param height
* @param imgPath
*/
public void encode(String contents, int width, int height, String imgPath)
{
Hashtable<Object, Object> hints = new Hashtable<Object, Object>();
// 指定纠错等级
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
// 指定编码格式
hints.put(EncodeHintType.CHARACTER_SET, "GBK");
try
{
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter.writeToFile(bitMatrix, "jpg", new File(imgPath));
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args)
{
String imgPath = "E:/devTools/360wallpaper.jpg";
StringBuffer s = new StringBuffer("<html><body>");
s.append("姓名:xxx").append(Test.CHANGE_LINE);
s.append("<img src=http://imgsrc.baidu.com/forum/w%3D580/sign=c152b344a0ec08fa260013af69ef3d4d/023b5bb5c9ea15ce0082f7f2b6003af33b87b2d8.jpg />");
s.append("</body></html>");
int width = 300, height = 300;
Test handler = new Test();
handler.encode(s.toString(), width, height, imgPath);
System.out.println("Michael ,you have finished zxing encode.");
}
}
转载地址:
使用ZXing生成二维码