java将富文本编辑器中html(含多张图片)转换成图片,并上传到oss中

将富文本编辑器中html(含多张图片)转换成图片,并上传到oss中

一.pom文件

		<dependency>
            <groupId>gui.ava</groupId>
            <artifactId>html2image</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.github.xuwei-k</groupId>
            <artifactId>html2image</artifactId>
            <version>0.1.0</version>
        </dependency>
        <dependency>
		    <groupId>org.jsoup</groupId>
		    <artifactId>jsoup</artifactId>
	   		<version>1.13.1</version>
		</dependency>

二.HTML转成图片

public class Html2Img {

    public String firstKey = 你的oss firstKey ;
    public String bucketName = 你的oss bucketName ;
    public String endpoint = 你的oss endpoint ;
    /**
     * @param htmText HTML文本字符串
     * @param name  图片名称
     *@param localPath @return 希望生成的Image Location
     * @Description HTML转Image
     */
    public  String html2Img(String htmText, String name, String localPath) throws Exception {
        String saveImageLocation = localPath + name+".png";
        HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
        try {
            imageGenerator.loadHtml(htmText);
            imageGenerator.getBufferedImage();
            imageGenerator.saveAsImage(saveImageLocation);
            //获取HTML中的图片链接并保存到项目class文件夹中,
            List<String> imgList = localImg(htmText,localPath);
            if (imgList != null && imgList.size() > 0) {
                imgList.forEach(imgPath -> {
                    imageGenerator.saveAsHtmlWithMap(imgPath,saveImageLocation);
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("将HTML文件转换成图片异常");
        }
        //将图片上传到oss中
        UploadUtil.uploadImgOss(saveImageLocation, name + ".png" , bucketName, firstKey);
        String imgOss = "https://" + bucketName + "." + endpoint.substring(endpoint.indexOf
                ("://") + 3) + "/" + firstKey + name + ".png" ;
        //删除已下载的文件
        File deleteFile = new File(localPath);
        deleteFile.delete();
        return imgOss;
    }


    //获取content中img标签中的图片链接
    public  List<String> localImg(String content, String localPath) throws UnsupportedEncodingException {
        List<String> imgList = new ArrayList<>();
        Document document = Jsoup.parseBodyFragment(content);
        if (ObjectUtils.isEmpty(document)) return imgList;
        Elements elements = document.body().getElementsByTag("img");
        
        elements.forEach(el -> {
            try {
                //下载图片到本地
                String src = el.attr("src");
                String fileUrl = downloadImg(src, SnowflakeGenerator.generate(),localPath);
                System.out.println("fileUrl:" + fileUrl);
                imgList.add(fileUrl);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return imgList;
    }


    //下载图片到本地
    public  String downloadImg(String url, String name,String localPath) throws Exception {
        //下载到文件夹
        createImg(url,name,localPath);
        String fileUrl = localPath + name + ".png";
        return fileUrl;
    }

	 

    private  void createImg(String content, String name, String localPath) throws Exception {
        String fileUrl = localPath + name + ".png";
        //初始化文件对象
        PrintStream printStream =null;
        try{
            //打开文件
            printStream = new PrintStream(fileUrl);
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }

        try{
            //将HTML文件内容写入文件中
            printStream.println(content);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

}

以下是HtmlImageGenerator源码


class HtmlImageGenerator {
    private JEditorPane editorPane;
    static final Dimension DEFAULT_SIZE = new Dimension(800, 800);

    public HtmlImageGenerator() {
        editorPane = createJEditorPane();
    }
	。。。。。。
	
	//将HTML转成图片
   	public void saveAsHtmlWithMap(File file, String imageUrl) {
		FileWriter writer = null;
		try {
			writer = new FileWriter(file);
			writer.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
			writer.append("<html>\n<head></head>\n");
			writer.append("<body style=\"margin: 0; padding: 0; text-align: center;\">\n");
			final String htmlMap = getLinksMapMarkup("map");
			writer.write(htmlMap);
			writer.append("<img border=\"0\" usemap=\"#map\" src=\"");
			writer.append(imageUrl);
			writer.append("\"/>\n");
			writer.append("</body>\n</html>");
		} catch (IOException e) {
			throw new RuntimeException(String.format("Exception while saving '%s' html file", file), e);
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException ignore) {
				}
			}
		}
	}
	。。。。。。
}

三.测试

 	@PostMapping(value = {"/html2img"},
        produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public String html2img() throws Exception {
   		 //html文本内容
        String content = html文本内容;
      	//设置文件生成目录
        String name = SnowflakeGenerator.generate();
        String localPath=TestHtml2Img.class.getClassLoader().getResource("").getPath() + name+"/";

        File file = new File(localPath);
        // 判断原文件是否存在(防止文件名冲突)
        if (!file.exists()) file.mkdirs();
        Html2Img html2Img = new Html2Img();
        String ossUrl = html2Img.html2Img(content, name,localPath);
        return ossUrl;
     }
		

四.展示:上传到oss上的图片展示
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值