日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

若依生成二维码图片

發布時間:2024/1/1 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 若依生成二维码图片 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

配置文件

# 二維碼生成設置 QR:Image:charset: utf-8width: 40height: 40

依賴

<!--Java 生成二維碼 --><dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.3.3</version></dependency><dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>3.3.3</version></dependency>

代碼

/*** 二維碼上傳服務器 且返回路徑* @param bufferedImage* @return*/private String uploadServer(BufferedImage bufferedImage){//將BufferedImage 轉換為 MultipartFile 進行文件上傳try{ByteArrayOutputStream out = new ByteArrayOutputStream();ImageIO.write(bufferedImage,"jpg",out);byte[] imageByte = out.toByteArray();MultipartFile file = new ConvertToMultipartFile(imageByte, IdUtils.simpleUUID(),IdUtils.fastSimpleUUID(),MimeTypeUtils.IMAGE_JPG,imageByte.length);// 上傳文件路徑String filePath = RuoYiConfig.getUploadPath();// 上傳并返回新文件名稱//file.getContentType() image/jpgString fileName = FileUploadUtils.upload(filePath, file);return fileName;}catch (IOException e){throw new ServiceException("二維碼創建失敗,請聯系管理員");}}/*** 活動創建簽到二維碼* @param civiTeamActivity 活動* @return 二維碼上傳之后返回的Url*/private String createQRImage(CiviTeamActivity civiTeamActivity){String qrContent =civiTeamActivity.getActivityTitle();BufferedImage bufferedImage = QRCodeUtil.createImage(charset, qrContent, qrWidth, qrHeight);//上傳服務器return uploadServer(bufferedImage);}

工具類

package com.civilization.common.utils;import com.google.zxing.*; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import sun.font.FontDesignMetrics;import javax.imageio.ImageIO; import java.awt.*; import java.awt.font.FontRenderContext; import java.awt.font.LineMetrics; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Hashtable;/*** FileName: QRCodeUtil* Date: 2022/6/15 11:00* Description: 二維碼生成工具類*/public class QRCodeUtil {/*** 創建二維碼* @param charSet 編碼方式* @param content 二維碼內容* @param qrWidth 二維碼長度* @param qrHeight 二維碼高度* @return*/public static BufferedImage createImage(String charSet, String content, int qrWidth, int qrHeight){Hashtable hints = new Hashtable();hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);hints.put(EncodeHintType.CHARACTER_SET, charSet);hints.put( EncodeHintType.MARGIN, 1);BitMatrix bitMatrix = null;try {bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,qrWidth , qrHeight, // 修改二維碼底部高度hints);} catch (WriterException e) {e.printStackTrace();}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;}/*** 對已經生成好的二維碼設置logo* @param source 二維碼* @param logo logo圖片* @param logoWidth logo寬度* @param logoHeight logo高度*/public static void insertLogoImage(BufferedImage source,Image logo,int logoWidth,int logoHeight){Graphics2D graph = source.createGraphics();int qrWidth = source.getWidth();int qrHeight = source.getHeight();int x = (qrWidth - logoWidth) / 2;int y = (qrHeight - logoHeight) / 2;graph.drawImage(logo, x, y, logoWidth, logoHeight, null);Shape shape = new RoundRectangle2D.Float(x, y, logoWidth, logoHeight, 6, 6);graph.setStroke(new BasicStroke(3f));graph.draw(shape);graph.dispose();}/*** 縮小logo圖片* @param logoPath* @param logoWidth* @param logoHeight* @return*/public static Image compressLogo(String logoPath, int logoWidth, int logoHeight){File file = new File(logoPath);if (!file.exists()) {System.err.println("" + logoPath + " 該文件不存在!");return null;}Image original = null;try {original = ImageIO.read(new File(logoPath));} catch (IOException e) {e.printStackTrace();}int width = original.getWidth(null);int height = original.getHeight(null);if (width > logoWidth) {width = logoWidth;}if (height > logoHeight) {height = logoHeight;}Image image = original.getScaledInstance(width, height, Image.SCALE_SMOOTH);BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics g = tag.getGraphics();g.drawImage(image, 0, 0, null); // 繪制縮小后的圖g.dispose();return image;}/*** 增加底部的說明文字* @param source 二維碼* @param text 說明內容* @param step*/public static BufferedImage addBottomFont(BufferedImage source, String text,int step) {int qrWidth = source.getWidth();System.out.println("二維碼的寬度"+qrWidth);int qrHeight = source.getHeight();System.out.println("二維碼的高度"+qrHeight);BufferedImage textImage = textToImage(text, qrWidth, 20,16);Graphics2D graph = source.createGraphics();//開啟文字抗鋸齒graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);int width = textImage.getWidth(null);int height = textImage.getHeight(null);Image src = textImage;graph.drawImage(src, 0, qrHeight - (20 * step) - 10, width, height, null);graph.dispose();return source;}/*** 將文明說明增加到二維碼上* @param str 文字* @param width 寬* @param height 高* @param fontSize 字體大小* @return*/public static BufferedImage textToImage(String str, int width, int height,int fontSize) {BufferedImage textImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);Graphics2D g2 = (Graphics2D)textImage.getGraphics();//開啟文字抗鋸齒g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);g2.setBackground(Color.WHITE);g2.clearRect(0, 0, width, height);g2.setPaint(Color.BLACK);FontRenderContext context = g2.getFontRenderContext();Font font = new Font("微軟雅黑", Font.PLAIN, fontSize);g2.setFont(font);LineMetrics lineMetrics = font.getLineMetrics(str, context);FontMetrics fontMetrics = FontDesignMetrics.getMetrics(font);float offset = (width - fontMetrics.stringWidth(str)) / 2;float y = (height + lineMetrics.getAscent() - lineMetrics.getDescent() - lineMetrics.getLeading()) / 2;g2.drawString(str, (int)offset, (int)y);return textImage;}/*** 頂部增加說明文字* @param source* @param text*/public static void addUpFont(BufferedImage source, String text) {int qrWidth = source.getWidth();int qrHeight = source.getHeight();BufferedImage textImage = textToImage(text, qrWidth, 10,10);Graphics2D graph = source.createGraphics();//開啟文字抗鋸齒graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);int width = textImage.getWidth(null);int height = textImage.getHeight(null);Image src = textImage;graph.drawImage(src, 0, 4, width, height, null);graph.dispose();}/*** 生成二維碼圖片* @param charSet 二維碼編碼方式* @param content 內容* @param qrWidth 寬度* @param qrHeight 長度* @param formatName jpg等圖片格式* @param imgPath 二維碼存放路徑*/public static void encode(String charSet,String content,int qrWidth,int qrHeight,String formatName,String imgPath){BufferedImage image = QRCodeUtil.createImage(charSet,content,qrWidth,qrHeight);try {ImageIO.write(image, formatName, new File(imgPath));} catch (IOException e) {e.printStackTrace();}}/*** 生成二維碼圖片流* @param charSet 二維碼編碼方式* @param content 內容* @param qrWidth 寬度* @param qrHeight 長度* @return*/public static BufferedImage encode(String charSet,String content,int qrWidth,int qrHeight) {BufferedImage image = QRCodeUtil.createImage(charSet,content,qrWidth,qrHeight);return image;}public static void encode( BufferedImage image,String formatName,String imgPath){try {ImageIO.write(image, formatName, new File(imgPath));} catch (IOException e) {e.printStackTrace();}}public static void mkdirs(String destPath) {File file = new File(destPath);// 當文件夾不存在時,mkdirs會自動創建多層目錄,區別于mkdir.(mkdir如果父目錄不存在則會拋出異常)if (!file.exists() && !file.isDirectory()) {file.mkdirs();}}/** 解析二維碼*/public static String decode(File file, String cherSet) throws Exception {BufferedImage image;image = ImageIO.read(file);if (image == null) {return null;}BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));Result result;Hashtable hints = new Hashtable();hints.put(DecodeHintType.CHARACTER_SET, cherSet);result = new MultiFormatReader().decode(bitmap, hints);String resultStr = result.getText();return resultStr;} }

將BufferedImage 轉化為MultipartFile 實現方式

package com.civilization.common.utils.file;import org.springframework.web.multipart.MultipartFile;import java.io.*;/*** @Author:Yanzeng* @Date:2022/10/27 14:34* @Email:YanYRzeng@aliyun.com* */ public class ConvertToMultipartFile implements MultipartFile {private byte[] fileBytes;String name;String originalFilename;String contentType;boolean isEmpty;long size;public ConvertToMultipartFile(byte[] fileBytes, String name, String originalFilename, String contentType,long size) {this.fileBytes = fileBytes;this.name = name;this.originalFilename = originalFilename;this.contentType = contentType;this.size = size;this.isEmpty = false;}@Overridepublic String getName() {return name;}@Overridepublic String getOriginalFilename() {return originalFilename;}@Overridepublic String getContentType() {return contentType;}@Overridepublic boolean isEmpty() {return isEmpty;}@Overridepublic long getSize() {return size;}@Overridepublic byte[] getBytes() throws IOException {return fileBytes;}@Overridepublic InputStream getInputStream() throws IOException {return new ByteArrayInputStream(fileBytes);}@Overridepublic void transferTo(File dest) throws IOException, IllegalStateException {new FileOutputStream(dest).write(fileBytes);}}

總結

以上是生活随笔為你收集整理的若依生成二维码图片的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。