最近项目里有一个需求:把kedit里的html内容和事先设定好的背景颜色转为图片,嵌入到一张事先准备好的图片里先看下效果
图1
图2
图3 (合成后背景颜色设为蓝色)
上面这个需求要分为两步来完成:
1、把html转为图片
2、在图片2上画图片1
先说步骤1:
网上有个开源的jar包html2image-0.9.jar (http://download.csdn.net/detail/jishuisanqianli/9633608)
能将html转为图片,底层使用java swing中提供的JEditorPane类
打开html2image-0.9.jar包的HtmlImageGenerator类里可以看到几个关键的方法我想你应该就理解的差不多了:
protected JEditorPane createJEditorPane() { JEditorPane editorPane = new JEditorPane(); editorPane.setSize(getDefaultSize()); editorPane.setEditable(false); SynchronousHTMLEditorKit kit = new SynchronousHTMLEditorKit(); editorPane.setEditorKitForContentType("text/html", kit); editorPane.setContentType("text/html"); editorPane.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("page")) HtmlImageGenerator.this.onDocumentLoad(); } }); return editorPane; } public void loadUrl(String url) { try { this.editorPane.setPage(url); } catch (IOException e) { throw new RuntimeException(String.format( "Exception while loading %s", new Object[] { url }), e); } } public BufferedImage getBufferedImage() { //注意这个原来的jar包里没有,加了这句话避免生成的图片存在内边距 editorPane.setMargin(new Insets(0, 0, 0, 0)); Dimension prefSize = this.editorPane.getPreferredSize(); BufferedImage img = new BufferedImage(prefSize.width, this.editorPane.getPreferredSize().height, 2); Graphics2D graphics = img.createGraphics(); this.editorPane.setSize(prefSize); this.editorPane.paint(graphics); return img; } public void saveAsImage(File file) { BufferedImage img = getBufferedImage(); try { String formatName = FormatNameUtil .formatForFilename(file.getName()); ImageIO.write(img, formatName, file); } catch (IOException e) { throw new RuntimeException( String.format("Exception while saving '%s' image", new Object[] { file }), e); } }
详细代码
说完了原理现在上步骤1的实现代码:
String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; String html = Content.htmlTemplate.replace("backgroundcolor",carDesignModel1.getCarcorlor()); html=html.replace("baseurl",basePath); html=html.replace("content",carDesignModel1.getContent()); //把html转为图片,得到图1 imageKedit HtmlImageGenerator imageGenerator = new HtmlImageGenerator();imageGenerator.loadHtml(html); BufferedImage imageKedit = imageGenerator.getBufferedImage(); //根据url读取图片,得到图2 imageOrigin URL u = new URL(Property.getProperty("FILESERVER_PATH")+"id="+carDesignModel1.getPicid()); BufferedImage imageOrigin = ImageIO.read(u);
下面说步骤2:
通过Graphics里的drawImage重新绘图并且生成新的图片
//合成新的图片 Graphics g=imageOrigin.getGraphics(); //四个参数分别是:图1横坐标,图1纵坐标,图1上绘制的图2的长,图1上绘制的图2的宽 g.drawImage(imageKedit,imageOrigin.getWidth()-imageKedit.getWidth(),imageOrigin.getHeight()-imageKedit.getHeight(),imageKedit.getWidth(),imageKedit.getHeight(),null); OutputStream outImage=new FileOutputStream("D:\\test2.png"); //合成的图片必须为png否则会导致颜色有所偏差 ImageIO.write(imageOrigin, "png", outImage); outImage.close();
对图片操作的一些代码: