java写html缩略图

12 篇文章 0 订阅

本人这几天想了好多方式!第一种:就是改html中所有的长度高度,等比例: 第二种:就是将html从后台转成图片: 第一种方法一定是可行的,不过实现起了通用性不大 第二种方法也是可行的:我现在就说说第二种方法吧!如下

/**
*
*/
package htmlToJpg;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;

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

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import struts.action.IoBooks;

// import com.cxsoft.rap.ed.util.ManualUtil;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class GraphUtils {

private final static Log log = LogFactory.getLog(GraphUtils.class);
/***************************************************************************
* 图片的高
*/
public static int DEFAULT_IMAGE_WIDTH = (int) (1280 / 1.5);
/***************************************************************************
* 默认值最好设置大点,因为我们再导之前,不知道这个流有多大,如果过小,则生成的图片后面的为黑色,因为流没有读取完整
*/
public static int DEFAULT_IMAGE_HEIGHT = (int) (720 / 1.5);

/**
* 将BufferedImage转换为图片的信息
*
* @param image
* @return
*/
public static String toJpeg(BufferedImage image, String nsrlsh, String year) {
   // 获取图片文件的在服务器的路径
   // String imgPath = ManualUtil.getImgPath(nsrlsh, year);
   // String imageName = imgPath+UUID.randomUUID().toString() + ".jpg";
   String imageName = "E:\\" + 1 + ".jpg";
   System.out.println(imageName);
   try {
    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[] buff = baos.toByteArray();
    baos.close();
    // 将字节流写入文件保存为图�?
    FileUtils.writeByteArrayToFile(new File(imageName), buff);
    System.out.println("保存成功!....");
   } catch (Exception ex) {
    log.error("保存删除图片失败:" + ex.getMessage());
   }
   return imageName;
}

/**
* html转换为jpeg文
*
* @param bgColor
*            图片的背景色
* @param html
*            html的文本信
* @param width
*            显示图片的Text容器的宽度
* @param height
*            显示图片的Text容器的高度
* @param eb
*            設置容器的边
* @return
* @throws Exception
*/
private static ArrayList<String> html2jpeg(Color bgColor, String html,
    int width, int height, EmptyBorder eb, String nsrlsh, String year)
    throws Exception {
   ArrayList<String> ret = new ArrayList<String>();
   try {
    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);
    Dimension d = ((BasicEditorPaneUI) tp.getUI()).getPreferredSize(tp);
    // 此处是将个页面生成一张图片,如果要人为控制图片大小进行分页生成,则再自行进行高度设置,但是分页之后可能出现的情况就是分页的时候字体被截断的可能,因为在截断的之后,他不知道流是否刚好将一行字显示完成
    if (d.height > DEFAULT_IMAGE_HEIGHT) {
     height = d.height;
    }
    PrintView m_printView = new PrintView(tp);
    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 = m_printView.paintPage(g, height, pageIndex);
     g.dispose();
     String path = toJpeg(image, nsrlsh, year);
     ret.add(path);
     pageIndex++;
    }
   } catch (Exception ex) {
    throw ex;
   }
   return ret;
}

/***************************************************************************
* 将一個html转换为图 <hr/>
*
* @param htmls
* @return
* @throws Exception
*/
public static ArrayList<String> toImages(String html, String nsrlsh,
    String year) throws Exception {
   return html2jpeg(null, html, DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT,
     new EmptyBorder(0, 0, 0, 0), nsrlsh, year);
}

public static void main(String[] args) {
   // try {
   // String htmlstr = "<html><head></head><body><img
   // src='C:\fakepath\1.jpg'></img></body></html>";
   // String nextLine = null;
   // System.out.println(htmlstr);
   // GraphUtils.toImages(htmlstr, "000000003126754", "2009");
   // } catch (Exception e) {
   // e.printStackTrace();
   // }
   String htmlstr = IoBooks
     .readFile("E:/.metadata/.plugins/com.genuitec.eclipse.easie.tomcat.myeclipse/tomcat/webapps/CreateBooks/zazhi/001.htm");

   System.out.print(htmlstr);
   GraphUtils gs = new GraphUtils();
   try {
    gs.toImages(htmlstr, "000000003126754", "2009");
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

}
}
package htmlToJpg;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JTextPane;
import javax.swing.plaf.basic.BasicEditorPaneUI;

/**
* 通过JTextPane目的显示html信息并绘制图片信息
*
* @author longgangbai
*
*/
public class PrintView {
public JTextPane panel = null;

public PrintView(JTextPane panel) {
   this.panel = panel;
}

/**
* 绘制图片的方法
*
* @param g
* @param hPage
* @param pageIndex
* @return
*/
public boolean paintPage(Graphics g, int hPage, int pageIndex) {
   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;
}
}

--------------------------------这样也可以--------------------------------

package htmlToJpg;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;

/**
* HTML2JPG,HTML页面转图片的实现方法。
*/
public class Test extends JFrame {
public Test(String url, File file) throws Exception {
   JEditorPane editorPane = new JEditorPane();
   editorPane.setEditable(false);
   editorPane.setPage(url);
   JScrollPane jsp = new JScrollPane(editorPane);
   getContentPane().add(jsp);
   this.setLocation(0, 0);
   Thread.sleep(5* 1000);
   setSize(100000, 100000);
   pack();
   // BufferedImage image = new BufferedImage(editorPane.getWidth(),
   // editorPane.getHeight(), BufferedImage.TYPE_INT_RGB);
   BufferedImage image = new BufferedImage(editorPane.getWidth(),
     editorPane.getHeight(), BufferedImage.TYPE_INT_RGB);
   Graphics2D graphics2D = image.createGraphics();
   editorPane.paint(graphics2D);
   BufferedImage image1 = resize(image,1280, 720);
   ImageIO.write(image1, "jpg", file);
   dispose();
}

public static void main(String[] args) throws Exception {
   new Test("file:///E:/.metadata/.plugins/com.genuitec.eclipse.easie.tomcat.myeclipse/tomcat/webapps/CreateBooks/zazhi/104_0.htm", new File("E:/file.jpg"));
}

public static BufferedImage resize(BufferedImage source, int targetW,
    int targetH) {
   // targetW,targetH分别表示目标长和宽
   int type = source.getType();
   BufferedImage target = null;
   double sx = (double) targetW;
   double sy = (double) targetH;
   // 这里想实现在targetW,targetH范围内实现等比缩放。如果不需要等比缩放
   // 则将下面的if else语句注释即可
//   if (sx > sy) {
//    sx = sy;
//    targetW = (int) (sx * source.getWidth());
//    } else {
//    sy = sx;
//    targetH = (int) (sy * source.getHeight());
//   }
   if (type == BufferedImage.TYPE_CUSTOM) { // handmade
    ColorModel cm = source.getColorModel();
    WritableRaster raster = cm.createCompatibleWritableRaster(targetW,
      targetH);
    boolean alphaPremultiplied = cm.isAlphaPremultiplied();
    target = new BufferedImage(cm, raster, alphaPremultiplied, null);
   } else
    target = new BufferedImage(targetW, targetH, type);
   Graphics2D g = target.createGraphics();
   // smoother than exlax:
   g.setRenderingHint(RenderingHints.KEY_RENDERING,
     RenderingHints.VALUE_RENDER_QUALITY);
   g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
   g.dispose();
   return target;
}
}

-----------------------------------------------------------------------------------

package htmlToJpg;

/***
*
*/
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

public class CreateImageDemo {
public void CreateImage() {
   Toolkit toolkit = Toolkit.getDefaultToolkit();
   Dimension screenSize = toolkit.getScreenSize();
   Rectangle screenRect = new Rectangle(screenSize);
   Robot robot;
   try {
    robot = new Robot();
    BufferedImage image = robot.createScreenCapture(screenRect);
    ImageIO.write(image, "jpg", new File("E:\\图片名称.jpg"));
   } catch (Exception e) {
    e.printStackTrace();
   }
}

public static void main(String[] args) {
   CreateImageDemo image = new CreateImageDemo();
   image.CreateImage();
}
}

哈哈!这几种方法同行不通的

生成的图片都不太清楚!有时还生成不了,不过一个html页面img内容不多的是可以生成的!呵呵!

如果生成的是黑色!是流没写好,如果是白色,那你就去掉一下<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
看看行不!

 

 

转自:http://hi.baidu.com/sarah_ziven/item/74409491529e7ffb2816470c

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值