|
java中生成二维码的方法基本有两种,Qrcode和Zxing两种方式。
但是Qrcode存储的数据有限,而且调起来比较麻烦,生成出来的二维码不好看,有点乱。
而Zxing是google公司的,转换的算法果然牛掰,直接就傻瓜式用就行了,生成的二维码也比较好看,看起来比较规范。
方法如下:
1、引入依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.0.0</version>
</dependency>
2、工具类
我又找到去白边的方法,也加到了这里边,可以查看下边的testEncode方法,通过传入deleteWhite 为true时,可实现去白边。
package springboot.xjweb.utils.zxing;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import static com.google.zxing.client.j2se.MatrixToImageConfig.BLACK;
import static com.google.zxing.client.j2se.MatrixToImageConfig.WHITE;
public class ZxingOrCodeUtils {
public static void testEncode(String content,String filePath,String fileName,boolean deleteWhite) throws WriterException, IOException {
int width = 200;
int height = 200;
String format = "png";
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, width, height, hints);
if(deleteWhite){
BufferedImage image = deleteWhite(bitMatrix);
File outputfile = new File(filePath+fileName);
ImageIO.write(image, "png", outputfile);
return;
}
Path path = FileSystems.getDefault().getPath(filePath, fileName);
MatrixToImageWriter.writeToPath(bitMatrix, format, path);
System.out.println("输出成功.");
}
public static void testDecode(String filePath) {
BufferedImage image;
try {
image = ImageIO.read(new File(filePath));
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = new MultiFormatReader().decode(binaryBitmap, hints);
System.out.println(result.getText());
} catch (IOException e) {
e.printStackTrace();
} catch (NotFoundException e) {
e.printStackTrace();
}
}
private static BufferedImage deleteWhite(BitMatrix matrix) {
int[] rec = matrix.getEnclosingRectangle();
int resWidth = rec[2] + 1;
int resHeight = rec[3] + 1;
BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
resMatrix.clear();
for (int i = 0; i < resWidth; i++) {
for (int j = 0; j < resHeight; j++) {
if (matrix.get(i + rec[0], j + rec[1]))
resMatrix.set(i, j);
}
}
int width = resMatrix.getWidth();
int height = resMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, resMatrix.get(x, y) ? BLACK
: WHITE);
}
}
return image;
}
public static void main(String[] args){
testDecode("D://zxing.png");
}
}
3、实际应用例子
下面例子中有两个地方要注意一下:
ImageIO.setUseCache(false); 这句话最好加上,如果不加,默认是先将文件生成到,项目运行的缓存中,比如你用java -jar运行,一般情况下你会放在c盘,如果你的c盘没有权限写入东西,那完了,妥妥的抛异常。加上没毛病。。。
getContent方法里,字符串中我加了\n,你没有看错,就是方便二维码读出的数据中,能够换行,如果不加,都在一行上,比较难看。
import com.google.zxing.WriterException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import springboot.xjweb.model.CbfQrImgeData;
import springboot.xjweb.service.dubboService.CbfDubboService;
import springboot.xjweb.utils.zxing.ZxingOrCodeUtils;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
@Controller
public class ImageController {
@Value("${spring.file.uploadpath}")
public String filePath;
@Autowired
private CbfDubboService cbfDubboService;
@RequestMapping(value = "/ndrestful/api/getQrCode", method = RequestMethod.GET)
public void test(HttpServletRequest request, HttpServletResponse response) throws IOException {
String qzbm = request.getParameter("qzbm");
String content =getContent(qzbm);
String fileName = "/"+qzbm+".png";
try {
ZxingOrCodeUtils.testEncode(content,filePath,fileName,true);
BufferedImage image = ImageIO.read(new File(filePath+fileName));
ImageIO.setUseCache(false);
ImageIO.write(image , "PNG", response.getOutputStream());
} catch (WriterException e) {
e.printStackTrace();
}
}
public String getContent(String qzbm){
if(qzbm == null){
return "\n未传入权证编码,查询失败";
}
CbfQrImgeData cbfQrImgeData = cbfDubboService.selectQrImageDataFromQzbm(qzbm);
if(cbfQrImgeData != null){
return "\n农村土地承包经营权证\n" +
"权证编码:"+qzbm+"\n" +
"发包方:"+cbfQrImgeData.getFbfmc()+"\n" +
"承包方:"+cbfQrImgeData.getCbfmc()+"\n" +
"总面积:"+cbfQrImgeData.getHtzmj()+"亩\n" +
"地块总数:"+cbfQrImgeData.getCbdkzs()+"块\n";
}else{
return "\n未匹配到相关数据";
}
}
}
|