转化为base64的好处不用存图片删除图片,查询富文本内容直接转化在页面显示,但是好模糊!
有兴趣的友友们可以一起探讨怎么解决这个问题!!!!
先看效果
直接分享代码
pom添加
<!-- Html2Image将html转图片 -->
<dependency>
<groupId>gui.ava</groupId>
<artifactId>html2image</artifactId>
<version>0.9</version>
</dependency>
代码:
public String HtmlToImage(String richText) {
if (richText.indexOf("table") != -1) {
// 增加table的边框样式
richText = richText.replaceAll("<td", "<td style='border: 1px solid black;'");
}
HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
imageGenerator.loadHtml(richText);
BufferedImage bufferedImage = getPicture(imageGenerator.getBufferedImage());
// 我有想过用Graphics2D,但是好像没效果 请高人指点一下
// // 获取 Graphics2D 对象
// Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
// // 设置渲染质量
// graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
// // 设置背景颜色
// graphics.setColor(Color.WHITE);
// // 设置文体 style
// graphics.setFont(new Font("Arial",Font.PLAIN ,18));
// // 设置文字颜色
// graphics.setColor(Color.BLACK);
// graphics.dispose();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
String base64Str = null;
try {
ImageIO.write(bufferedImage, "jpg", outputStream);
String base64Img = Base64.encodeBase64String(outputStream.toByteArray());
base64Str = "data:image/jpg;base64," + base64Img.toString();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static BufferedImage getPicture(BufferedImage originalImage) {
int imageWidth = originalImage.getWidth();
int imageHeight = originalImage.getHeight();
BufferedImage grayPicture;
grayPicture = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
ColorConvertOp cco = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB), null);
cco.filter(originalImage, grayPicture);
return grayPicture;
}
有很好的解决方案欢迎留言哦~