7.8生成长图
作者:互联网
生成长图的手段,服务端通过工具读取HTML模板中的内容生成长图。
官网https://wkhtmltopdf.org,下载安装,把安装目录添加到环境变量。
新建data\wk-images和D:\javing\workspace\data\wk-pdfs目录,打开命令窗口,输入
C:\Users\hp>wkhtmltopdf http://www.nowcoder.com d:/WorkPlace/data/wk-pdf/1.pdf
生成图片,以压缩的形式:
wkhtmltoimage --quality 75 https://www.nowcoder.com d:/WorkPlace/data/wk-pdfs/2.png
测试类:
public class WkTests {
public static void main(String[] args) {
String cmd = "d:/WorkPlace/wkhtmltopdf/bin/wkhtmltoimage --quality 75 https://www.nowcoder.com d:/WorkPlace/data/wk-image/1.png";
try {
Runtime.getRuntime().exec(cmd);//执行上面的cmd命令
System.out.println("ok.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
模拟分享功能
系统上线之后,Linux的路径不一样,所以上面测试类中的路径地址要更换。
所以配置类中新增:
# wk
wk.image.command=d:/WorkPlace/wkhtmltopdf/bin/wkhtmltoimage
wk.image.storage=d:/WorkPlace/data/wk-images
Config配置
@Configuration
public class WKConfig {
private static final Logger logger = LoggerFactory.getLogger(WKConfig.class);
@Value("${wk.image.storage}")
private String wkImageStorage;
//服务启动的时候创建目录
@PostConstruct
public void init(){
//创建目录
File file = new File(wkImageStorage);
if (!file.exists()){
file.mkdir();
logger.info("创建wk目录图片:"+wkImageStorage);
}
}
}
EventConsumer中新增消费分享事件,后面controller才能发送事件到es服务器中:
//消费分享事件
@KafkaListener(topics = {TOPIC_SHARE})
public void handleShareMessage(ConsumerRecord record){
if (record == null || record.value() == null){
logger.error("消息的内容为空");
return;
}
Event event = JSONObject.parseObject(record.value().toString(),Event.class);
if (event == null){
logger.error("消息的格式错误");
return;
}
String htmlUrl = (String) event.getData().get("htmlUrl");
String fileName = (String) event.getData().get("fileName");
String suffix = (String) event.getData().get("suffix");
//取到值之后,拼出命令执行
String cmd = wkImageCommand + " --quality 75 "+htmlUrl+" "+wkImageStorage+"/"+fileName+suffix;
try {
Runtime.getRuntime().exec(cmd);
logger.info("生成长图成功,命令是:"+cmd);
} catch (IOException e) {
logger.error("生成长图失败:"+e.getMessage());
}
}
ShareController
@Controller
public class ShareController implements CommunityConstant {
private static final Logger logger = LoggerFactory.getLogger(WKConfig.class);
//前端一访问就生成一个图片,异步最好,丢给kafka就中,
@Autowired
private EventProducer eventProducer;
@Value("${community.path.domain}")
private String domain;
@Value("${server.servlet.context-path}")
private String contextPath;
@Value("${wk.image.storage}")
private String wkImageStorage;
@RequestMapping(path = "/share",method = RequestMethod.GET)
@ResponseBody
public String share(String htmlUrl){
//随机文件名,不然容易重名
String fileName = CommunityUtil.generateUUID();
Event event = new Event()
.setTopic(TOPIC_SHARE)
.setData("htmlUrl",htmlUrl)
.setData("fileName",fileName)
.setData("suffix",".png");
eventProducer.fireEvent(event); //异步生成长图
//返回访问路径
Map<String,Object> map = new HashMap<>();
map.put("shareUrl",domain+contextPath+"/share/image/"+fileName);
return CommunityUtil.getJSONString(0,null,map);
}
//获取长图
@RequestMapping(path = "/share/image/{fileName}",method = RequestMethod.GET)
public void getShareImage(@PathVariable("fileName") String fileName, HttpServletResponse response){
if (StringUtils.isBlank(fileName)){
throw new IllegalArgumentException("文件名不能为空");
}
response.setContentType("image/png");
File file = new File(wkImageStorage+"/"+fileName+".png");
try {
ServletOutputStream os = response.getOutputStream();
FileInputStream fis = new FileInputStream(file);
//缓冲区
byte[] buffer = new byte[1024];
//游标
int b = 0 ;
while ((b = fis.read(buffer) )!= -1){
//不等于-1,表示确实读到数据了
//把游标b读到的fis数据读给os
os.write(buffer,0,b);//防止最后一次每到1024,所以这有个范围
}
} catch (IOException e) {
logger.error("获取长图失败:"+e.getMessage());
}
}
}
测试地址:
http://localhost:8080/community/share?htmlUrl=http://www.nowcoder.com
本地有文件,输入http://localhost:8080/community/share/image/4a945261819b477fa02de82fa7aa6c27 可以访问到生成的图片,OK。
标签:String,image,wk,成长,fileName,public,7.8,logger 来源: https://blog.csdn.net/weixin_44114392/article/details/112811398