java--实现将文字生成二维码图片,并在中间附上logo,下方附上文字

前段时间因为工作需要,要实现将一段文字或者url生成二维码,然后中间附上logo,下方正中间附上文字的功能。

上网找了几篇教程学习了下,由于没有保存借鉴的博文链接,所以就没po上参考文章的链接啦,感谢几位博主的分享~

大概的实现效果如下图所示:

java--实现将文字生成二维码图片,并在中间附上logo,下方附上文字

 

实现步骤:

(1)导入java_ZXing_jar包,点此下载jar包

 

(2)编写画二维码代码

 1 package QRCode;

 2 

 3 import com.google.zxing.common.BitMatrix;

 4 import javax.imageio.ImageIO;

 5 import java.io.File;

 6 import java.io.OutputStream;

 7 import java.io.IOException;

 8 import java.awt.image.BufferedImage;

 9 

10 public final class MatrixToImageWriter {

11 

12     private static final int BLACK = 0xFF000000;

13     private static final int WHITE = 0xFFFFFFFF;

14 

15     private MatrixToImageWriter() {}

16 

17 

18     public static BufferedImage toBufferedImage(BitMatrix matrix) {

19         int width = matrix.getWidth();

20         int height = matrix.getHeight();

21         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

22         for (int x = 0; x < width; x++) {

23             for (int y = 0; y < height; y++) {

24                 image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);

25             }

26         }

27         return image;

28     }

29 

30 

31     public static void writeToFile(BitMatrix matrix, String format, File file)

32             throws IOException {

33         BufferedImage image = toBufferedImage(matrix);

34         if (!ImageIO.write(image, format, file)) {

35             throw new IOException("Could not write an image of format " + format + " to " + file);

36         }

37     }

38 

39 

40     public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)

41             throws IOException {

42         BufferedImage image = toBufferedImage(matrix);

43         if (!ImageIO.write(image, format, stream)) {

44             throw new IOException("Could not write an image of format " + format);

45         }

46     }

47 

48 }
MatrixToImageWriter

 

(3)编写一个类,用来设置中间logo的属性(注:代码中“照片的1/6”,应该是“二维码图片的1/6”,懒得重新上传代码,特此注释下)

 1 package QRCode;

 2 

 3 import java.awt.Color;

 4 

 5 public class LogoConfig {

 6     // logo默认边框颜色

 7     public static final Color DEFAULT_BORDERCOLOR = Color.WHITE;

 8     // logo默认边框宽度

 9     public static final int DEFAULT_BORDER = 2;

10     // logo大小默认为照片的1/6

11     public static final int DEFAULT_LOGOPART = 6;

12  

13     private final int border = DEFAULT_BORDER;

14     private final Color borderColor;

15     private final int logoPart;

16  

17     /**

18      * Creates a default config with on color {@link #BLACK} and off color

19      * {@link #WHITE}, generating normal black-on-white barcodes.

20      */

21     public LogoConfig()

22     {

23         this(DEFAULT_BORDERCOLOR, DEFAULT_LOGOPART);

24     }

25  

26     public LogoConfig(Color borderColor, int logoPart)

27     {

28         this.borderColor = borderColor;

29         this.logoPart = logoPart;

30     }

31  

32     public Color getBorderColor()

33     {

34         return borderColor;

35     }

36  

37     public int getBorder()

38     {

39         return border;

40     }

41  

42     public int getLogoPart()

43     {

44         return logoPart;

45     }

46 }
LogoConfig

 

(4)为二维码图片添加logo

 1 /**

 2      * 给二维码图片添加Logo

 3      * 

 4      * @param qrPic

 5      * @param logoPic

 6      */

 7     public static void addLogo_QRCode(File qrPic, File logoPic, LogoConfig logoConfig)

 8     {

 9         try

10         {

11             if (!qrPic.isFile() || !logoPic.isFile())

12             {

13                 System.out.print("file not find !");

14                 System.exit(0);

15             }

16 

17             /**

18              * 读取二维码图片,并构建绘图对象

19              */

20             BufferedImage image = ImageIO.read(qrPic);

21             Graphics2D g = image.createGraphics();

22 

23             /**

24              * 读取Logo图片

25              */

26             BufferedImage logo = ImageIO.read(logoPic);

27 

28             int widthLogo = image.getWidth()/logoConfig.getLogoPart(); 

29         //    int    heightLogo = image.getHeight()/logoConfig.getLogoPart();

30             int    heightLogo = image.getWidth()/logoConfig.getLogoPart(); //保持二维码是正方形的

31 

32             // 计算图片放置位置

33             int x = (image.getWidth() - widthLogo) / 2;

34             int y = (image.getHeight() - heightLogo) / 2 ;        

35 

36 

37             //开始绘制图片

38             g.drawImage(logo, x, y, widthLogo, heightLogo, null);

39             g.drawRoundRect(x, y, widthLogo, heightLogo, 10, 10);

40             g.setStroke(new BasicStroke(logoConfig.getBorder()));

41             g.setColor(logoConfig.getBorderColor());

42             g.drawRect(x, y, widthLogo, heightLogo);

43 

44             g.dispose();

45 

46             ImageIO.write(image, "jpeg", new File("D:/newPic.jpg"));

47         }

48         catch (Exception e)

49         {

50             e.printStackTrace();

51         }

52     }
addLogo_QRCode

 

(5)为添加好logo的二维码图片添加文字

 1 /**

 2      * @为图片添加文字

 3      * @param pressText 文字

 4      * @param newImg    带文字的图片

 5      * @param targetImg 需要添加文字的图片

 6      * @param fontStyle 

 7      * @param color

 8      * @param fontSize

 9      * @param width

10      * @param heigh

11      */

12     public static void pressText(String pressText, String newImg, String targetImg, int fontStyle, Color color, int fontSize, int width, int height) {

13         

14         //计算文字开始的位置

15         //x开始的位置:(图片宽度-字体大小*字的个数)/2

16         int startX = (width-(fontSize*pressText.length()))/2;

17         //y开始的位置:图片高度-(图片高度-图片宽度)/2

18         int startY = height-(height-width)/2;        

19         

20         try {

21             File file = new File(targetImg);

22             Image src = ImageIO.read(file);

23             int imageW = src.getWidth(null);

24             int imageH = src.getHeight(null);

25             BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);

26             Graphics g = image.createGraphics();

27             g.drawImage(src, 0, 0, imageW, imageH, null);

28             g.setColor(color);

29             g.setFont(new Font(null, fontStyle, fontSize));

30             g.drawString(pressText, startX, startY);

31             g.dispose();

32 

33             FileOutputStream out = new FileOutputStream(newImg);

34             ImageIO.write(image, "JPEG", out);

35             JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

36             encoder.encode(image);

37             out.close();

38             System.out.println("image press success");

39         } catch (Exception e) {

40             System.out.println(e);

41         }

42     }
pressText

 

(6)上面功能写好后,可以综合一下进行测试

 1 public static void main(String args[]) {

 2         try {

 3             //二维码表示的内容

 4             String content = "http://www.cnblogs.com/";

 5             

 6             //存放logo的文件夹

 7             String path = "E:/QRCodeImage";

 8 

 9             MultiFormatWriter multiFormatWriter = new MultiFormatWriter();

10 

11             @SuppressWarnings("rawtypes")

12             Map hints = new HashMap();

13             

14             //设置UTF-8, 防止中文乱码

15             hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

16             //设置二维码四周白色区域的大小

17             hints.put(EncodeHintType.MARGIN,1);

18             //设置二维码的容错性

19             hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); 

20             

21             //width:图片完整的宽;height:图片完整的高

22             //因为要在二维码下方附上文字,所以把图片设置为长方形(高大于宽)

23             int width = 400;

24             int height = 450;

25             

26             //画二维码,记得调用multiFormatWriter.encode()时最后要带上hints参数,不然上面设置无效

27             BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);

28             

29             //qrcFile用来存放生成的二维码图片(无logo,无文字)

30             File qrcFile = new File(path,"myPicture.jpg");

31             //logoFile用来存放带有logo的二维码图片(二维码+logo,无文字)

32             File logoFile = new File(path,"logo.jpg");

33             

34             //开始画二维码

35             MatrixToImageWriter.writeToFile(bitMatrix, "jpg", qrcFile);

36 

37             //在二维码中加入图片

38             LogoConfig logoConfig = new LogoConfig(); //LogoConfig中设置Logo的属性

39             addLogo_QRCode(qrcFile, logoFile, logoConfig);

40             

41     

42             int font = 18; //字体大小

43             int fontStyle = 1; //字体风格

44             

45             //用来存放带有logo+文字的二维码图片

46             String newImageWithText = "D:/imageWithText.jpg"; 

47             //带有logo的二维码图片

48             String targetImage = "D:/newPic.jpg";

49             //附加在图片上的文字信息

50             String text = "文字测试一二三四五六123";

51 

52             //在二维码下方添加文字(文字居中)

53             pressText(text, newImageWithText, targetImage, fontStyle, Color.BLUE, font,  width,  height) ;

54 

55         } catch (Exception e) {

56             e.printStackTrace();

57         }

58     }
main

注意:部分ZXing的jar包导入后,配置EncodeHintType.MARGIN会报错

使用上面附上的java_ZXing_jar包即可。

分享就到此结束啦~~

 

你可能感兴趣的:(java)