Zxing使用方式
jar包导入
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.2.0</version>
</dependency>
java代码
生成二维码代码
public static BitMatrix createMatrix(int width, int height, String content) throws WriterException {
Map<EncodeHintType, Object> config = new HashMap<>(3);
config.put(EncodeHintType.CHARACTER_SET, "UTF-8");
config.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
config.put(EncodeHintType.MARGIN, 0);
return new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, config);
}
//通过获取二维码的每一个元素,的黑白点来 绘制二维码图片
public static void main(String[] args) {
try {
int height = 200;
int width = 200;
BitMatrix bitMatrix = createMatrix(width, height, "www.baidu.com");
BufferedImage bufferedImage = new BufferedImage(bitMatrix.getWidth(), bitMatrix.getHeight(), BufferedImage.TYPE_INT_RGB);
for (int i = 0; i< bitMatrix.getHeight(); i++){
for (int j = 0; j<bitMatrix.getWidth(); j++){
bufferedImage.setRGB(i,j, bitMatrix.get(i, j) ? 0X00000000 : 0XFFFFFFFF);
}
}
ImageIO.write(bufferedImage, "png", new File("e:\\tt.png"));
} catch (Exception e) {
e.printStackTrace();
}
}
对图片进行压缩 进行变换体积的方式 可以考虑google的(thumbnailator)
BufferedImage image = ImageIO.read(new File("e:\\logo.jpg"));
Image i = image.getScaledInstance(60, 60, Image.SCALE_SMOOTH);
BufferedImage b = new BufferedImage(60, 60, BufferedImage.TYPE_INT_RGB);
Graphics graphics = b.getGraphics();
graphics.drawImage(i, 0, 0, null);
graphics.dispose();
ImageIO.write(b, "png", new File("e:\\tt.png"));
把图片画到另一个图片上
Graphics2D graphics2D = bufferedImage.createGraphics();
graphics2D.drawImage(i, 20, 20, 60,60, null);
图片的尺寸不变,压缩大小(亲测试 图片 800k 转换成90k)
感谢:https://blog.csdn.net/qq_25158359/article/details/81143180
public void zipImagePic(BufferedImage bufferedImage, File file) throws IOException {
ImageWriter imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
ImageWriteParam imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(
null);
imgWriteParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
imgWriteParams.setCompressionQuality((float)0.5);
imgWriteParams.setProgressiveMode(ImageWriteParam.MODE_DISABLED);
ColorModel colorModel = bufferedImage.getColorModel();
imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(
colorModel, colorModel.createCompatibleSampleModel(16, 16)));
// File file = new File("e:\\new.png");
FileOutputStream out = new FileOutputStream(file);
imgWrier.reset();
imgWrier.setOutput(ImageIO.createImageOutputStream(out));
imgWrier.write(null, new IIOImage(bufferedImage, null, null),
imgWriteParams);
out.flush();
out.close();
}