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

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

一.pom文件

		
            gui.ava
            html2image
            2.0.1
        
        
            com.github.xuwei-k
            html2image
            0.1.0
        
        
		    org.jsoup
		    jsoup
	   		1.13.1
		

二.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 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 localImg(String content, String localPath) throws UnsupportedEncodingException {
        List 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("\n");
			writer.append("\n\n");
			writer.append("\n");
			final String htmlMap = getLinksMapMarkup("map");
			writer.write(htmlMap);
			writer.append("\n");
			writer.append("\n");
		} 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上的图片展示
java将富文本编辑器中html(含多张图片)转换成图片,并上传到oss中_第1张图片

你可能感兴趣的:(java)