Html2Image (JAVA)

一 . 背景介绍

  • 最近公司业务有个小小的修改,需要我将一个简单的HTML静态页面,转换成BMP图片方便打印机打印
  • 运行环境:Windows 10
  • 上网查了资料,也踩过几个坑,在这里与大家分享

二. 大致过程

  1. 引入Html2Image的Maven依赖

    <dependency>
    <groupId>com.github.xuwei-k</groupId>
    <artifactId>html2image</artifactId>
    <version>0.1.0</version>
    </dependency>
  2. 写个工具类

    • IO流读取HTML文件为字符串

      /**
       * 
       * @Description 读取HTML文件,获取字符内容
       * @param filePath
       * @param charset
       * @return
       */
      public static String getHtmlContent(String filePath, String charset){
      
          String line = null;   
          StringBuilder sb = new StringBuilder(); 
          BufferedReader reader = null;
      
          try {  
              reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath)),charset));
              while ((line = reader.readLine()) != null) {   
                  sb.append(line + "\n");
              } 
          } catch (IOException e) {   
              e.printStackTrace();
              throw new RuntimeException("读取HTML文件,获取字符内容异常");
          } finally {   
              try {   
                  reader.close();   
              } catch (IOException e) {  
                  e.printStackTrace();
                  throw new RuntimeException("关闭流异常");
              }   
          }   
          return sb.toString();
      }
    • HTML转Image

      /**
       * 
       * @Description HTML转Image
       * @param htmText HTML文本字符串
       * @return 希望生成的Image Location
       */
      public static String html2Img(String htmText, String saveImageLocation){
      
          HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
          try {
              imageGenerator.loadHtml(htmText);
              Thread.sleep(100);
              imageGenerator.getBufferedImage();
              Thread.sleep(200);
              imageGenerator.saveAsImage(saveImageLocation);
              //imageGenerator.saveAsHtmlWithMap("hello-world.html", saveImageLocation);
              //不需要转换位图的,下面三行可以不要
              BufferedImage sourceImg = ImageIO.read(new File(saveImageLocation));
              sourceImg = transform_Gray24BitMap(sourceImg);
              ImageIO.write(sourceImg, "BMP", new File(saveImageLocation));
          } catch (Exception e) {
              e.printStackTrace();
              throw new RuntimeException("将HTML文件转换成图片异常");
          }
          return saveImageLocation;
      }
    • 可能有些特殊要求,需要转换位图,这里就要用到一个位图转换工具类

      /**
       * 
       * @Description 转换成24位图的BMP
       * @param image
       * @return
       */
      public static BufferedImage transform_Gray24BitMap(BufferedImage image){
      
          int h = image.getHeight();
          int w = image.getWidth();
          int[] pixels = new int[w * h]; // 定义数组,用来存储图片的像素
          int gray;
          PixelGrabber pg = new PixelGrabber(image, 0, 0, w, h, pixels, 0, w);
          try {
              pg.grabPixels(); // 读取像素值
          } catch (InterruptedException e) {
              throw new RuntimeException("转换成24位图的BMP时,处理像素值异常");
          }
      
          for (int j = 0; j < h; j++){ // 扫描列  
              for (int i = 0; i < w; i++) { // 扫描行
                  // 由红,绿,蓝值得到灰度值
                  gray = (int) (((pixels[w * j + i] >> 16) & 0xff) * 0.8);
                  gray += (int) (((pixels[w * j + i] >> 8) & 0xff) * 0.1);
                  gray += (int) (((pixels[w * j + i]) & 0xff) * 0.1);
                  pixels[w * j + i] = (255 << 24) | (gray << 16) | (gray << 8) | gray;
              }
          }
      
          MemoryImageSource s= new MemoryImageSource(w,h,pixels,0,w);
          Image img =Toolkit.getDefaultToolkit().createImage(s);
          BufferedImage buf = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);//如果要转换成别的位图,改这个常量即可
          buf.createGraphics().drawImage(img, 0, 0, null);
          return buf;
      }
    • 测试方法

      //测试方法
      public static void main(String[] args) {
          String charset = "GBK";
          String saveImageLocation = "E:\\save.png";
          String htmlFilePath = "C:\\Users\\xusanduo\\Desktop\\test.html";
      
          String htmText = getHtmlContent(htmlFilePath, charset);
          html2Img(htmText, saveImageLocation);
      }
    • 下面附上test.html的内容

      <html>
      <body>
          <div class="logImg" style="margin:0px;left:0px;top:2px;text-align: center;width: 350px;">
              <!-- 注:图片src不支持相对路径,必须加上file:/// 或者直接写http的url。最好写jpg格式,亲测过bmp和png格式不行-->
              <img align="middle" src="file:///E:/1name.jpg">
          </div>
          <div class="contentText" style="margin:20px 0px 0px 0px">
              <table border="0" style="width: 350px;">
                  <tbody>
                      <tr>
                          <td align="middle" style="font-size:20px">9-6-图片测试</td>
                      </tr>
                  </tbody>
              </table>
          </div>
      </body>
      </html>                                                                         

    三. 碰到的坑

    • 图片格式最好jpg,反正我试过bmp和png的不行
    • 图片路径必须加上file:/// 或者直接写http的url,不支持相对路径写法
    • 转换成功后,可能需要再做位图转换
  • 8
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 23
    评论
Java提供了一种将HTML转换为图片的工具类-Java HTMLImage工具类。这个工具类的作用是将HTML代码转换为图片格式,方便在其他场景中使用,例如生成链接、缩略图、截图等。 Java HTMLImage工具类的实现原理是使用了Java的相关技术,如JavaFX或者AWT/Swing。具体实现步骤如下: 1. 解析HTML代码:首先需要将HTML代码解析为DOM树,可以使用Java HTML解析器(如Jsoup)来完成这一步骤。 2. 创建JavaFX或AWT/Swing画布:接下来,需要创建一个JavaFX或AWT/Swing的画布,用于渲染HTML内容。 3. 渲染HTML内容:将解析得到的DOM树渲染到画布上,可以使用JavaFX WebView(对应JavaFX画布)或者JEditorPane(对应AWT/Swing画布)来实现。 4. 截取画布内容:然后,根据需要,可以使用Java图形库提供的截图功能来截取画布上的内容。 5. 保存为图片:最后,将截取的内容保存为图片格式,可以使用Java图形库提供的图片处理功能来实现,例如ImageIO。 在实际应用中,可以将上述步骤封装为一个工具类,方便在其他地方使用。这样,只需要调用这个工具类的方法,传入HTML代码和图片保存路径,就可以将HTML转换为图片。 需要注意的是,Java HTMLImage工具类的实现原理和具体实现方式可能因不同的需求而有所差异。此外,HTML中的一些特殊功能(例如JavaScript、CSS动画等)可能在转换为图片时无法完全保留,需要根据具体情况进行处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 23
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值