Java或其他技术 将html转化成图片?

12 篇文章 0 订阅

如何使用Java或其他技术将html转换为图片呢?知道的朋友交流一下~

网上找了一下,发现几种方法。

1、html2image【java】

转自:http://my.oschina.net/longniao/blog/84236

html2image:http://code.google.com/p/java-html2image/

jar包下载地址:http://code.google.com/p/java-html2image/downloads/list

 

HtmlImageGenerator imageGenerator = new HtmlImageGenerator();

imageGenerator.loadHtml("<b>Hello World!</b> Please goto <a title=\"Goto Google\" href=\"http://www.google.com\">Google</a>.");

imageGenerator.saveAsImage("hello-world.png");

imageGenerator.saveAsHtmlWithMap("hello-world.html", "hello-world.png");

 

HtmlImageGenerator Methods
loadUrl(url) - Loads HTML from URL object or URL string. (从url载入html)
loadHtml(html) - Loads HTML source. (载入本地html)
saveAsImage(file) - Save loaded HTML as image. (以图片形式保存html)
saveAsHtmlWithMap(file, imageUrl) - Creates an HTML file containing client-side image-map <map> generated from HTML's links. (创建一个HTML文件包含客户端image-map)
getLinks() - List all links in the HTML document and their corresponding href, target, title, position and dimension. (列出所有在HTML文档的链接和相应href、目标、头衔、位置和尺寸)
getBufferedImage() - Get AWT buffered image of the HTML. (获得awt,html缓冲后的图片)
getLinksMapMarkup(mapName) - Get HTML snippet of the client-side image-map <map> generated from the links. (HTML代码段里获得的客户端image-map <地图>产生的链接)
get/setOrientation(orientation) - Get/Set document orientation (left-to-right or right-to-left). (get/set文本定位)
get/setSize(dimension) - Get/Set size of the generated image. (设置生成图片大小)

 

测试结果:不支持相对路径链接图片,排版错乱。

 

2、纯Java  http://www.tuicool.com/articles/2yAryy

 

Java中江HTML片段转换为图片,不需要调用额外的jar包,支持css,但写在style之间的css和外置的css文件不受支持,只能写在标签上。   

知道不支持外置css文件就没测试了。

示例代码:  

 

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

import javax.swing.JTextPane;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.basic.BasicEditorPaneUI;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.xxx.util.FileUtil;

/**
 * HTML转换图片的方式
 *
 * 
 */
public class HTML2Picture {

    public static int DEFAULT_IMAGE_WIDTH = 730;
    public static int DEFAULT_IMAGE_HEIGHT = 700;

    public static boolean paintPage(Graphics g, int hPage, int pageIndex,
            JTextPane panel) {
        Graphics2D g2 = (Graphics2D) g;
        Dimension d = ((BasicEditorPaneUI) panel.getUI())
                .getPreferredSize(panel);
        double panelHeight = d.height;
        double pageHeight = hPage;
        int totalNumPages = (int) Math.ceil(panelHeight / pageHeight);
        g2.translate(0f, -(pageIndex - 1) * pageHeight);
        panel.paint(g2);
        boolean ret = true;

        if (pageIndex >= totalNumPages) {
            ret = false;
            return ret;
        }
        return ret;
    }

    /**
     * html转换为jpeg文件
     * 
     * @param bgColor
     *            图片的背景色
     * @param html
     *            html的文本信息
     * @param width
     *            显示图片的Text容器的宽度
     * @param height
     *            显示图片的Text容器的高度
     * @param eb
     *            設置容器的边框
     * @return
     * @throws Exception
     */
    private static void html2jpeg(Color bgColor, String html, int width,
            int height, EmptyBorder eb) throws Exception {

        JTextPane tp = new JTextPane();
        tp.setSize(width, height);
        if (eb == null) {
            eb = new EmptyBorder(0, 50, 0, 50);
        }
        if (bgColor != null) {
            tp.setBackground(bgColor);
        }
        if (width <= 0) {
            width = DEFAULT_IMAGE_WIDTH;
        }
        if (height <= 0) {
            height = DEFAULT_IMAGE_HEIGHT;
        }
        tp.setBorder(eb);
        tp.setContentType("text/html");
        tp.setText(html);

        int pageIndex = 1;
        boolean bcontinue = true;
        while (bcontinue) {
            BufferedImage image = new java.awt.image.BufferedImage(width,
                    height, java.awt.image.BufferedImage.TYPE_INT_RGB);
            Graphics g = image.getGraphics();
            g.setClip(0, 0, width, height);
            bcontinue = paintPage(g, height, pageIndex, tp);
            g.dispose();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(baos);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
            param.setQuality(1.0f, false);
            encoder.setJPEGEncodeParam(param);
            encoder.encode(image);
            byte[] bytes = baos.toByteArray();
            baos.close();

            FileUtil.writeBinFile("C:\123.jpg", bytes);
            pageIndex++;
        }
    }

    public static void main(String[] args) throws Exception {
        html2jpeg(Color.white, FileUtil.readAscFile("C:\table.html"),
                DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_WIDTH, new EmptyBorder(0, 0,
                        0, 0));
        System.out.println("over!");

    }
}


3、html2canvas 【JS截图技术】

官网:http://html2canvas.hertzen.com/

测试结果:相对前面2种较好,支持图片、css外链等样式。缺点是有些还是不能正常排版。

api文档:http://html2canvas.hertzen.com/documentation.html

 

 4、DJNativeSwing  模拟浏览器截图  【待研究 】

 

 5、在windows环境下,可以考虑这个工具软件来抓页面截图:
IECapt.exe 

测试结果:还可以,就是功能比较少,可以完成网页截图,缺点:不能控制图片大小

在linux环境下,可以考虑这个工具软件来抓页面截图:
HTML2Image

http://kennychen.iteye.com/blog/807832

 

6、JS生成缩略图

①、 <script   language="JavaScript">  
  <!--  
  var   flag=false;  
  function   DrawImage(ImgD){  
        var   image=new   Image();  
        image.src=ImgD.src;  
        if(image.width>0   &&   image.height>0){  
          flag=true;  
          if(image.width/image.height>=   360/270){  
            if(image.width>360){      
            ImgD.width=360;  
            ImgD.height=(image.height*360)/image.width;  
            }else{  
            ImgD.width=image.width;      
            ImgD.height=image.height;  
            }  
            ImgD.alt=image.width+"×"+image.height;  
            }  
          else{  
            if(image.height>270){      
            ImgD.height=270;  
            ImgD.width=(image.width*270)/image.height;            
            }else{  
            ImgD.width=image.width;      
            ImgD.height=image.height;  
            }  
            ImgD.alt=image.width+"×"+image.height;  
            }  
          }  
  }    
  //-->  
  </script>  
<img src="1.png"   onload="javascript:DrawImage(this);"  />

②、    <script type="text/javascript" language="javascript">
        var flag = false;
        function DrawImage(ImgD) {            
            var image = new Image();
            image.src = ImgD.src;
            if (image.width > 0 && image.height > 0) {
                flag = true;
                if (image.width / image.height >= 164 / 112) {
                    if (image.width > 164) {
                        ImgD.width = 164;
                        ImgD.height = (image.height * 164) / image.width;
                    } else {
                        ImgD.width = image.width;
                        ImgD.height = image.height;
                    }
                    ImgD.alt = image.width + "×" + image.height;
                }
                else {
                    if (image.height > 35) {
                        ImgD.height = 35;
                        ImgD.width = (image.width * 35) / image.height;
                    } else {
                        ImgD.width = image.width;
                        ImgD.height = image.height;
                    }
                    ImgD.alt = image.width + "×" + image.height;
                }
            }
        }
    </script>

<input type="button" value="生成缩略图" onclick="DrawImage(this.nextSibling)" /><img src="1.png" border="0" >


 7、待研究icepdf  xhtmlrenderer  http://download.csdn.net/detail/Altered/3094060#comment


 

 

 

 

 

 

 

 

 

 

 

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值