<dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.2.0</version> </dependency>
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(); } }
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);
感謝:http://www.javashuo.com/article/p-frwqwzbp-ck.htmljava
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(); }