Java怎么实现生成分享海报工具类
这篇“Java怎么实现生成分享海报工具类”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Java怎么实现生成分享海报工具类”文章吧。
一、使用步骤1.导入pom依赖和上传图片到工程代码如下(示例):在自己得通用工具类模块中导入坐标!(这需要根据自己得工程来)
<!--谷歌图片压缩--><dependency><groupId>net.coobird</groupId><artifactId>thumbnailator</artifactId></dependency><!--谷歌图片压缩--><dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId></dependency><!--生成二维码--><dependency><groupId>cn.hutool</groupId><artifactId>hutool-extra</artifactId><version>5.4.3</version></dependency><dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.3.3</version></dependency><!--生成二维码-->2.创建生成接口
代码如下(示例):
@LoginUser:是自定义注解获取jwt的用户id(根据自己的需求和工程来)
@NoLogin:是项目种的白名单,不需要携带token的注解
/***生成用户的邀请二维码**@paramuserId用户id*/@GetMapping("qRCode")@NoLoginpublicObjectqRCode(@LoginUserIntegeruserId){//判断用户id是否为空if(userId==null){returnResponseUtil.fail("请选择用户");}//获取生成海报的图片路径StringfilePath=wxUserService.qRCode(userId);returnResponseUtil.ok(filePath);}3.创建service层
代码如下(示例):
这是一个接口!需要自己实现该接口!实现接口代码在下面!
/***根据用户的邀请码生成分享海报**@paramuserId*@return*/StringqRCode(IntegeruserId);
代码如下(示例):
上面接口的实现类
/***根据用户的邀请码生成分享海报**@paramuserId*@return*/@OverridepublicStringqRCode(IntegeruserId){try{//根据用户id查询验证码UserInfouserInfo=userService.selectById(userId);//判断是否库是否存在海报地址if(!StringUtils.isEmpty(userInfo.getPoster())){returnuserInfo.getPoster();}//要生成海报的模板(一般在springboot工程的resources下我的工程路径:templates/poster/xjcq.png可以改成自己工程需要的路径)FilehbPath=ResourceUtils.getFile("classpath:templates/poster/xjcq.png");//要生成二维码的logo(一般在springboot工程的resources下我的工程路径:templates/poster/xjcqLogo.png可以改成自己工程需要的路径)FilelogoPath=ResourceUtils.getFile("classpath:templates/poster/xjcqLogo.png");//获取上传后的路径StringfilePath=imageUtil.drawString(qRCodeInviteScheme+userInfo.getInviteCode(),userInfo.getInviteCode(),userInfo.getInviteCode(),hbPath,logoPath);//File转MultipartFile(因为我们的oss是转MultipartFile)Filefile=newFile(filePath);InputStreaminputStream=newFileInputStream(file);MultipartFilemultipartFile=newMockMultipartFile(file.getName(),file.getName(),ContentType.APPLICATION_OCTET_STREAM.toString(),inputStream);//上转至阿里云Strings=storageUtil.uploadOssFile(multipartFile);//更改数据库UserInfoupdateUserInfo=newUserInfo();updateUserInfo.setId(userInfo.getId());updateUserInfo.setPoster(s);userService.updateById(updateUserInfo);returnupdateUserInfo.getPoster();}catch(FileNotFoundExceptione){log.error("文件找不到:{}",e);}catch(IOExceptione){log.error("io异常:{}",e);}returnnull;}4.生成海报的工具类
代码如下(示例):
wordPath类的代码,可以参考一下java获取yml配置文件内容
packagecom.legend.core.config;importlombok.Data;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.stereotype.Component;/***获取全局配置path*@authoradmin*/@Component@DatapublicclassWordPath{//生成电子合同的路径@Value("${word.path}")privateStringwordPath;//生成海报的路径@Value("${poster.path}")privateStringposterPath;}
代码如下(示例):
wordPath: 这个是我把要生成画报地址的路径配置到了yml中了,因为测试的使用用的是winodows,上了生产就用linux服务器了。所以配置到了yml中了
packagecom.legend.core.util;importcn.hutool.extra.qrcode.QrCodeUtil;importcn.hutool.extra.qrcode.QrConfig;importcom.google.zxing.qrcode.decoder.ErrorCorrectionLevel;importcom.legend.core.config.WordPath;importlombok.extern.slf4j.Slf4j;importorg.apache.commons.io.IOUtils;importorg.springframework.core.io.DefaultResourceLoader;importorg.springframework.core.io.ResourceLoader;importorg.springframework.stereotype.Service;importjavax.annotation.Resource;importjavax.imageio.ImageIO;importjavax.imageio.stream.ImageOutputStream;importjava.awt.*;importjava.awt.image.BufferedImage;importjava.io.*;/***生成分享好友**@author生成分享好友*/@Service@Slf4jpublicclassImageUtil{//我把生成海报地址的路径配置到了springboot的yml配置文件中了@ResourceprivateWordPathwordPath;/***生成海报**@paramcontent二维码内容*@paramwritten文字内容*@paramfilePath保存文件例:1.png(d:/1.png)*@paramhbPath海报图片地址例:1.png(d:/1.png)*@paramlogoPath二维码logo*@return*@authorUncle*@Description在一张背景图上添加二维码*@Date2020-09-2823:59*/publicStringdrawString(Stringcontent,Stringwritten,StringfilePath,FilehbPath,FilelogoPath){try{BufferedImageimage=addWater(content,hbPath,logoPath);Graphics2Dgd=image.createGraphics();//3、设置对线段的锯齿状边缘处理gd.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);//5、设置水印文字颜色gd.setColor(Color.darkGray);//6、设置水印文字Fontgd.setFont(newFont("苹方",Font.PLAIN,32));//8、第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)gd.drawString(written,440,1122);gd.dispose();ByteArrayOutputStreambs=newByteArrayOutputStream();ImageOutputStreamimOut=ImageIO.createImageOutputStream(bs);ImageIO.write(image,"png",imOut);InputStreaminputStream=newByteArrayInputStream(bs.toByteArray());//获取yml海报的配置Stringfile=wordPath.getPosterPath()+filePath+".png";if(!newFile(wordPath.getPosterPath()).exists()){newFile(wordPath.getPosterPath()).mkdirs();}OutputStreamoutStream=newFileOutputStream(file);IOUtils.copy(inputStream,outStream);inputStream.close();outStream.close();//返回文件地址returnfile;}catch(Exceptione){log.error("海报生成失败:",e);}returnnull;}/****在一张背景图上添加二维码*/publicBufferedImageaddWater(Stringcontent,FilehbPath,FilelogoPath)throwsException{//读取原图片信息//得到文件//Filefile=newFile(hbPath);//文件转化为图片ImagesrcImg=ImageIO.read(hbPath);//获取图片的宽intsrcImgWidth=srcImg.getWidth(null);//获取图片的高intsrcImgHeight=srcImg.getHeight(null);//加水印BufferedImagebufImg=newBufferedImage(srcImgWidth,srcImgHeight,BufferedImage.TYPE_INT_RGB);Graphics2Dg=bufImg.createGraphics();g.drawImage(srcImg,0,0,srcImgWidth,srcImgHeight,null);//使用工具类生成二维码Imageimage=createQrCode(content,230,230,logoPath);//将小图片绘到大图片上,500,300.表示你的小图片在大图片上的位置。g.drawImage(image,25,1070,null);//设置颜色。g.setColor(Color.WHITE);g.dispose();returnbufImg;}privateBufferedImagecreateQrCode(Stringcontent,intwidth,intheight,FilelogoPath)throwsIOException{QrConfigconfig=newQrConfig(width,height);if(logoPath!=null){Imageimage=ImageIO.read(newFileInputStream(logoPath));config.setImg(image);}config.setErrorCorrection(ErrorCorrectionLevel.H);returnQrCodeUtil.generate(content,config);}publicInputStreamresourceLoader(StringfileFullPath)throwsIOException{ResourceLoaderresourceLoader=newDefaultResourceLoader();returnresourceLoader.getResource(fileFullPath).getInputStream();}}
以上就是关于“Java怎么实现生成分享海报工具类”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。