How to convert an HtmlImage object to a RenderedImage?

I have a method like this, it is trying to load images:

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);
                }
            }  
        }

How can I convert it HtmlImage img=> RenderedImage img?

+3
source share
2 answers

Based on your comment in which you mentioned you are just trying to save HtmlImageto a file, then the easiest way is to use a saveAs(File file)class HtmlImage.

Your code will look something like this:

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

Remember what this method can call IOException.

+1
source

You can get RenderedImagedirectly, without saving to a file:

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

Here is a working example:

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);
    }
}
+1
source

All Articles