2014-02-15 53 views
3

我有這樣的方法,它嘗試下載圖片:如何將HtmlImage對象轉換爲RenderedImage?

private static void downloadImage() throws IOException { 
      int imgSrc = 0; 
      for(HtmlImage img : urlList){ 
       String imageFormat = img.toString().substring(img.toString().lastIndexOf(".") + 1); 
       String imgPath = "C:\\" + imgSrc + ""; 
       imgSrc++; 
       if (img != null) { 
        File file = new File(imgPath); 
        //In the next method i need img in RenderedImage type 
        ImageIO.write(img, imageFormat, file); 
       } 
      } 
     } 

我怎樣才能把它轉換HtmlImage img =>RenderedImage img

+0

你只是想挽回的HtmlImage到一個文件? –

+0

是的,正是如此) –

回答

1

根據您的評論,您提到的只是試圖將HtmlImage保存到文件中,那麼最簡單的方法是使用HtmlImage類的saveAs(File file)方法。

您的代碼將是這個樣子:

if (img != null) { 
    File file = new File(imgPath); 
    img.saveAs(file); 
} 

請記住,這個方法可能會拋出IOException

+1

謝謝,那正是我需要的 –

1

您可以直接獲得一個RenderedImage,而不保存到一個文件:

private RenderedImage getImage(HtmlImage image) throws IOException { 
    ImageReader reader = image.getImageReader(); 
    int minIndex = reader.getMinIndex(); 
    return reader.read(minIndex); 
} 

這裏是一個工作示例:

package org.human.joecoder.htmlunit; 

import java.awt.image.RenderedImage; 
import java.io.File; 
import java.io.IOException; 
import java.net.URL; 
import java.util.List; 

import javax.imageio.ImageIO; 
import javax.imageio.ImageReader; 

import com.gargoylesoftware.htmlunit.WebClient; 
import com.gargoylesoftware.htmlunit.html.HtmlImage; 
import com.gargoylesoftware.htmlunit.html.HtmlPage; 

public class HtmlUnitImageScraper { 

    public static void main(String[] args) throws Exception { 
     WebClient webClient = new WebClient(); 
     HtmlPage currentPage = (HtmlPage) webClient.getPage(new URL(
       "http://www.google.com")); 
     final List<?> images = currentPage.getByXPath("//img"); 
     for (int i = 0; i < images.size(); i++) { 
      Object imageObject = images.get(i); 
      HtmlImage image = (HtmlImage) imageObject; 
      RenderedImage buf = getImage(image); 
      ImageIO.write(buf, "png", new File("image_"+i+".png")); 
     } 
     webClient.closeAllWindows(); 
    } 

    private static RenderedImage getImage(HtmlImage image) throws IOException { 
     ImageReader reader = image.getImageReader(); 
     int minIndex = reader.getMinIndex(); 
     return reader.read(minIndex); 
    } 
}