生成二维码图片,并以流传输到前端页面显示

特别声明---该文章只为备忘

jar包下载链接:

http://maven.aliyun.com/nexus/#welcome

本项目所需要的jar包:

zxing-javase.jar   QRUtil依赖包---二维码图片

nutz-1.r.65.jar    nutz框架的依赖


生成二维码图片的Util

public  class QRUtil {
                public static String image_url ="";


            public static String testEncoder(String str) {
                    String nstr="";
                    String text = str;   
                    System.out.println(text);
                    int width = 200;   
                    int height = 200;   
                    String format = "jpg";  


                    Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();  
                    hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
                    BitMatrix bitMatrix = null;
                    try {
                        
                        bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
                    } catch (WriterException e1) { 
                        e1.printStackTrace();
                    }    
                    String imgid = UUID.randomUUID().toString();
                    
                    //将图片动态存入项目目录
                    String t=Thread.currentThread().getContextClassLoader().getResource("").getPath();
                    int num=t.indexOf(".metadata");
                   String path=t.substring(1,num).replace('/', '\\')+"imageTest\\WebContent\\image\\";
                    File outputFile = new File(path+imgid+".jpg");  
                    image_url =outputFile.getPath();
                    try {
                        MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
                    } catch (IOException e) { 
                        e.printStackTrace();
                    }
                                return nstr;
        
            }


        }

Nutz框架代码

@At("/span")
@Ok("jsp:show")
    public void login(@Param("username")String name, @Param("city")String city, HttpSession session,HttpServletRequest req,HttpServletResponse response) throws Exception {
                String Userlogin = "http://ttts.besttoptoday.com/lc/login" + "?username="+ name+"&city=" +city;
                System.out.println(Userlogin);
                QRUtil.testEncoder(Userlogin);
    }
        
        @At("/imageShow")
          public void imageGet(HttpSession session,HttpServletRequest req,HttpServletResponse response) throws Exception{
              
                    String image_url =  QRUtil.image_url;
                    System.out.println(image_url);
                        
                    File filePic = new File(image_url);  
                if(filePic.exists()){  
                    FileInputStream is = new FileInputStream(filePic);  
                    int i = is.available(); // 得到文件大小    
                    byte data[] = new byte[i];    
                    is.read(data); // 读数据    
                    is.close();    
                    response.setContentType("image/*"); // 设置返回的文件类型    
                    response.setHeader("Pragma", "no-cache");
                    response.setHeader("Cache-Control", "no-cache");
                    response.setDateHeader("Expires", 0);
                    OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象    
                    toClient.write(data); // 输出数据    
                    toClient.close();    
                }
      }
      

页面则在img标签中src直接访问项目请求

生成二维码后,可以将其转换为图片格式保存在数据库中。在前端页面中,可以使用<img>标签来显示图片,将数据库中的图片数据转换为base64格式,然后将其作为src属性值即可。具体实现方式可以参考如下代码: ```java // 生成二维码 String content = "hello world"; int width = 200; // 图片宽度 int height = 200; // 图片高度 String format = "png"; // 图片格式 Hashtable hints = new Hashtable(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints); // 保存二维码图片到数据库(假设使用MySQL) try { Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456"); String sql = "insert into qrcode (content, image) values (?, ?)"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, content); ByteArrayOutputStream baos = new ByteArrayOutputStream(); MatrixToImageWriter.writeToStream(bitMatrix, format, baos); byte[] imageBytes = baos.toByteArray(); ps.setBytes(2, imageBytes); ps.executeUpdate(); ps.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } ``` 在前端页面中,可以使用如下代码来显示数据库中保存的二维码图片: ```html <img src="data:image/png;base64,${base64EncodedImage}"> ``` 其中,${base64EncodedImage}是在后台将数据库中保存的二维码图片数据转换为base64格式后传递到前端的变量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值