Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to generate a shared poster tool class with Java

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this article "Java how to generate and share poster tools", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "Java how to generate a sharing poster tool class" article.

First, use step 1. Import pom dependencies and upload pictures to the project

The code is as follows (example): import coordinates in your general tool class module! (this needs to be done according to your own project.)

Net.coobird thumbnailator com.google.guava guava cn.hutool hutool-extra 5.4.3 com.google.zxing core 3.3.3 2. Create a build interface

The code is as follows (example):

@ LoginUser: user id for custom annotations to obtain jwt (according to their own needs and projects)

@ NoLogin: it is a whitelist of project species and does not need to be annotated with token.

/ * generate an invitation QR code for the user * * @ param userId user id * / @ GetMapping ("qRCode") @ NoLogin public Object qRCode (@ LoginUser Integer userId) {/ / determine whether the user id is empty if (userId = = null) {return ResponseUtil.fail ("Please select user") } / / get the image path String filePath = wxUserService.qRCode (userId); return ResponseUtil.ok (filePath);} 3. Create a service layer

The code is as follows (example):

This is an interface! You need to implement the interface yourself! The implementation interface code is below!

/ * * generate a sharing poster according to the user's invitation code * * @ param userId * @ return * / String qRCode (Integer userId)

The code is as follows (example):

The implementation class of the above interface

/ * * generate a sharing poster based on the user's invitation code * * @ param userId * @ return * / @ Override public String qRCode (Integer userId) {try {/ / query the verification code UserInfo userInfo = userService.selectById (userId) according to the user's id / / determine whether the poster address if (! StringUtils.isEmpty (userInfo.getPoster () {return userInfo.getPoster () exists in the library. } / / the template to generate the poster (usually under the resources of springboot project, my project path: templates/poster/xjcq.png can be changed to the path needed by your own project) File hbPath = ResourceUtils.getFile ("classpath:templates/poster/xjcq.png") / / to generate the logo of the QR code (usually my project path under the resources of the springboot project: templates/poster/xjcqLogo.png can be changed to the path needed by the project) File logoPath = ResourceUtils.getFile ("classpath:templates/poster/xjcqLogo.png") / / get the uploaded path String filePath = imageUtil.drawString (qRCodeInviteScheme + userInfo.getInviteCode (), hbPath, logoPath); / / File to MultipartFile (because our oss is to MultipartFile) File file = new File (filePath); InputStream inputStream = new FileInputStream (file) MultipartFile multipartFile = new MockMultipartFile (file.getName (), file.getName (), ContentType.APPLICATION_OCTET_STREAM.toString (), inputStream); / / go to Aliyun String s = storageUtil.uploadOssFile (multipartFile); / / change the database UserInfo updateUserInfo = new UserInfo (); updateUserInfo.setId (userInfo.getId ()) UpdateUserInfo.setPoster (s); userService.updateById (updateUserInfo); return updateUserInfo.getPoster ();} catch (FileNotFoundException e) {log.error ("File not found: {}", e);} catch (IOException e) {log.error ("io exception: {}", e);} return null;} 4. Tool class for generating posters

The code is as follows (example):

WordPath class code, you can refer to java to get the contents of the yml configuration file

Package com.legend.core.config;import lombok.Data;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;/** * get global configuration path * @ author admin * / @ Component@Datapublic class WordPath {/ / path to generate electronic contract @ Value ("${word.path}") private String wordPath; / / path to generate poster @ Value ("${poster.path}") private String posterPath;}

The code is as follows (example):

WordPath: this is where I configured the path to generate the pictorial address in yml, because the test uses winodows and the linux server is used in production. So it is configured in yml.

Package com.legend.core.util;import cn.hutool.extra.qrcode.QrCodeUtil;import cn.hutool.extra.qrcode.QrConfig;import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;import com.legend.core.config.WordPath;import lombok.extern.slf4j.Slf4j;import org.apache.commons.io.IOUtils;import org.springframework.core.io.DefaultResourceLoader;import org.springframework.core.io.ResourceLoader;import org.springframework.stereotype.Service;import javax.annotation.Resource;import javax.imageio.ImageIO;import javax.imageio.stream.ImageOutputStream Import java.awt.*;import java.awt.image.BufferedImage;import java.io.*;/** * generate sharing Friends * * @ author generate sharing Friends * / @ Service@Slf4jpublic class ImageUtil {/ / I configured the path to generate poster addresses in springboot's yml configuration file @ Resource private WordPath wordPath / * * generate poster * * @ param content QR code content * @ param written text content * @ param filePath save file example: 1.png (d:/1.png) * @ param hbPath poster picture address example: 1.png (d:/1.png) * @ param logoPath QR code logo * @ Return * @ author Uncle * @ Description add the QR code * @ Date 2020-09-28 23:59 * / public String drawString (String content) to a background image String written, String filePath, File hbPath, File logoPath) {try {BufferedImage image = addWater (content, hbPath, logoPath) Graphics2D gd = image.createGraphics (); / / 3. Set jagged edge processing gd.setRenderingHint (RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR) for line segments; / / 5, set watermark text color gd.setColor (Color.darkGray) / / 6. Set the watermark text Font gd.setFont (new Font ("Apple", Font.PLAIN, 32)); / / 8, the first parameter-> the content set, and the last two parameters-> the coordinate position of the text on the picture (xQuery y) gd.drawString (written, 440,1122); gd.dispose (); ByteArrayOutputStream bs = new ByteArrayOutputStream () ImageOutputStream imOut = ImageIO.createImageOutputStream (bs); ImageIO.write (image, "png", imOut); InputStream inputStream = new ByteArrayInputStream (bs.toByteArray ()); / / get the configuration of yml poster String file = wordPath.getPosterPath () + filePath + ".png" If (! new File (wordPath.getPosterPath ()). Exists ()) {new File (wordPath.getPosterPath ()) .mkdirs ();} OutputStream outStream = new FileOutputStream (file); IOUtils.copy (inputStream, outStream); inputStream.close (); outStream.close (); / / return file address return file } catch (Exception e) {log.error ("poster generation failed:", e);} return null } / * add a QR code to a background image * / public BufferedImage addWater (String content, File hbPath, File logoPath) throws Exception {/ / read the original picture information / / get the file / / File file = new File (hbPath); / / convert the file to image Image srcImg = ImageIO.read (hbPath) / / get the width of the image int srcImgWidth = srcImg.getWidth (null); / / get the high int srcImgHeight of the image = srcImg.getHeight (null); / / watermark BufferedImage bufImg = new BufferedImage (srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g = bufImg.createGraphics (); g.drawImage (srcImg, 0,0, srcImgWidth, srcImgHeight, null) / / use the tool class to generate the QR code Image image = createQrCode (content, 230,230, logoPath); / / draw a small picture on a big picture, 500300. Indicates the position of your small picture on the big picture. G.drawImage (image, 25, 1070, null); / / sets the color. G.setColor (Color.WHITE); g.dispose (); return bufImg;} private BufferedImage createQrCode (String content, int width, int height, File logoPath) throws IOException {QrConfig config = new QrConfig (width, height); if (logoPath! = null) {Image image = ImageIO.read (new FileInputStream (logoPath)); config.setImg (image);} config.setErrorCorrection (ErrorCorrectionLevel.H) Return QrCodeUtil.generate (content, config);} public InputStream resourceLoader (String fileFullPath) throws IOException {ResourceLoader resourceLoader = new DefaultResourceLoader (); return resourceLoader.getResource (fileFullPath). GetInputStream () }} the above is about the content of this article on "how to generate and share poster tools for Java". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report