@RequestMapping(value = "pic/image", method = {RequestMethod.GET, RequestMethod.POST})
@ApiOperation(value = "生成图片", notes = "生成图片", response = String.class)
public BaseResult<Object> Image(HttpServletRequest request, HttpServletResponse response) throws Exception {
BaseResult<Object> br = new BaseResult<>();
List<HashMap<String, Object>> retList = Lists.newArrayList();
List<Box> paramList = boxDao.findByNamedParamList(null);
for (Box param : paramList) {
String id = String.valueOf(param.getId());
String boxNo = param.getBoxNo();
BufferedImage image = QrCodeUtil.createImage(id, 300, 300);
BufferedImage bi = new BufferedImage(400, 500, BufferedImage.TYPE_INT_ARGB);
Graphics2D gh = (Graphics2D) bi.getGraphics();
gh.setColor(Color.WHITE);
gh.fillRect(0, 0, 400, 500);
gh.setColor(Color.BLACK);
gh.drawRect(0, 0, 400 - 1, 500 - 1);
gh.setFont(new Font(boxNo, Font.PLAIN, 50));
gh.drawString(boxNo, 60, 90);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image, "png", os);
BufferedImage bimg = null;
bimg = javax.imageio.ImageIO.read(new ByteArrayInputStream(os.toByteArray()));
if (bimg != null) {
gh.drawImage(bimg, 50, 150, 300, 300, null);
gh.dispose();
}
gh.setColor(Color.BLACK);
Base64.Encoder encoder = Base64.getEncoder();
String base64Str = encoder.encodeToString(os.toByteArray());
HashMap<String, Object> dataMap = new HashMap();
dataMap.put("img", base64Str);
retList.add(dataMap);
}
br.setData(retList);
return br;
}
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.awt.image.BufferedImage;
import java.util.Hashtable;
public class QrCodeUtil {
public static BufferedImage createImage(String content, int imgWidth, int imgHeight) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, imgWidth, imgHeight, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.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, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
return image;
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20201221171834942.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM3NTU1NTE0,size_16,color_FFFFFF,t_70)