controller代码如下:
- /*
- * 生成二维码
- * */
- @GetMapping("/testEwm")
- @ResponseBody
- public void createQRCode( String data, Integer height ,Integer width, HttpServletResponse response,String type) throws Exception {
- response.setHeader("Pragma", "no-cache");
- response.setHeader("Cache-Control", "no-cache");
- response.setDateHeader("Expires", 0);
- response.setContentType("image/jpeg");
- int ht=200;
- int wt=200;
- BufferedImage image = ewm.createImage(data,null==height?ht:height,null==width?wt:width,type);
- // 创建二进制的输出流
- ServletOutputStream out = response.getOutputStream();
- ImageIO.write(image, "jpeg", out);
- }
service层只需更改type类型就可以调整对应二维码颜色,代码如下:
- //生成二维码
- public static BufferedImage createImage(String content, int ht, int wt,String type) {
- Hashtable
hints = new Hashtable(); - hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
- hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
- hints.put(EncodeHintType.MARGIN, 1);
- BitMatrix bitMatrix = null;
- try {
- bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, wt, ht, hints);
- } catch (WriterException e) {
- e.printStackTrace();
- }
- int width = bitMatrix.getWidth();
- int height = bitMatrix.getHeight();
- BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
- /**
- * 0x00ff0000,// Red
- * 0x0000ff00,// Green
- * 0x000000ff,// Blue
- * 0xff000000,// Alpha
- */
-
- int color = 0x0000ff00;
- if ("1".equals(type)){
- color = 0x00ff0000;
- }
- if ("2".equals(type)){
- color = 0x000000ff;
- }
-
- for (int x = 0; x < width; x++) {
- for (int y = 0; y < height; y++) {
- image.setRGB(x, y, bitMatrix.get(x, y) ? color : 0xFFFFFFFF);
- }
- }
- return image;
- }
好了,到底了