因为项目有个功能需要打印二维码,因为我比较喜欢使用html+css+js实现,所以首先想到的是jquery.qrcode.js插件,这个插件可以用canvas和table生成二维码,效果也不错,不过对中文支持有问题,这个插件默认使用canvas,所以使用ie的时候,需要指定参数render,只要参数值不是canvas就会用table生成。由于这个问题,我在github,fork了一个,做了如下的修改:
[javascript] view
plain copy
//true if support
function canvassupport() {
return !!document.createelement('canvas').getcontext;
}
return this.each(function(){
//if the browser not support canvas,then table.
if(!canvassupport()){
options.render = "table";
}
var element = options.render == "canvas" ? createcanvas() : createtable();
$(element).appendto(this);
});
修改后就不需要指定render参数,如果不支持canvas就会用table.
使用canvas有个缺点就是网页打印的时候显示不出来...这个问题好像已经有解决办法了,我没有去找,我直接用的table。不过打印似乎仍然有问题。
jquery.qrcode.js插件地址:https://github.com/jeromeetienne/jquery-qrcode
js有问题,所以只能通过zxing来输出二维码,写了如下的servlet代码:
[java] view
@suppresswarnings("serial")
public class qrcodeservlet extends httpservlet {
private static final int black = -16777216;
private static final int white = -1;
private bufferedimage tobufferedimage(bitmatrix matrix) {
int width = matrix.getwidth();
int height = matrix.getheight();
bufferedimage image = new bufferedimage(width, height,bufferedimage.type_int_argb);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setrgb(x, y, matrix.get(x, y) ? black : white);
return image;
}
@override
protected void doget(httpservletrequest req, httpservletresponse resp)
throws servletexception, ioexception {
try {
string content = req.getparameter("m");
if(content==null||content.equals("")){
resp.setcontenttype("text/plain;charset=utf-8");
resp.getoutputstream().write("二维码内容不能为空!".getbytes("utf-8"));
resp.getoutputstream().close();
int imgwidth = 110;
int imgheight = 110;
string width = req.getparameter("w");
string height = req.getparameter("h");
if(width!=null&&!width.equals("")){
try {
imgwidth = integer.parseint(width);
} catch (exception e) {}
if(height!=null&&!height.equals("")){
imgheight = integer.parseint(height);
bitmatrix bytematrix;
hashtable<encodehinttype, object> hints = new hashtable<encodehinttype, object>();
hints.put(encodehinttype.error_correction, errorcorrectionlevel.h);
bytematrix = new multiformatwriter().encode(
new string(content.getbytes("utf-8"),"iso-8859-1"),
barcodeformat.qr_code,
imgwidth,
imgheight,
hints);
bufferedimage image = tobufferedimage(bytematrix);
resp.setcontenttype("image/png");
imageio.write(image, "png", resp.getoutputstream());
} catch (exception e) {
}
参数m必须有,参数h、w可选,默认的宽高为110px。
由于zxing默认的编码为iso-8859-1,所以使用其他编码的时候会出现乱码,即使执行其他的编码方式,还是有问题,如果转换为iso-8859-1就没有乱码。
还有一个很重要的内容,就是使用zxing的时候必须导出png格式的二维码,导出jpg格式的时候,颜色就不是黑白的,很让人费解,希望有人能给出原因。
二维码效果图: