JAVA实现把网页的图片下载下来

/ java / 没有评论 / 3510浏览
import java.net.URL;
 
import java.net.MalformedURLException;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.File;
 
public class TestGetImageFromUrl {
 	/**
	* @param args
	*/
	 public static void main(String[] args) {

		String httpUrl = "http://www.a3gs.com/关于我们.files/image002.gif";
		URL url;
		BufferedInputStream in;
		FileOutputStream file;
		try {
			System.out.println("获取网络图片");
			String fileName = httpUrl.substring(httpUrl.lastIndexOf("/") + 1);
			String filePath = "C:\\";
			url = new URL(httpUrl);
			in = new BufferedInputStream(url.openStream());
			file = new FileOutputStream(new File(filePath + fileName));
			int t;
			while ((t = in.read()) != -1) {
				file.write(t);
			}
			file.close();
			in.close();
			System.out.println("图片获取成功");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	} 
}

获取所有图片工具类

public static List<String> getImageSrc(String htmlCode) {
    List<String> imageSrcList = new ArrayList<String>();
    Pattern p = Pattern.compile("<img\\b[^>]*\\bsrc\\b\\s*=\\s*('|\")?([^'\"\n\r\f>]+(\\.jpg|\\.bmp|\\.eps|\\.gif|\\.mif|\\.miff|\\.png|\\.tif|\\.tiff|\\.svg|\\.wmf|\\.jpe|\\.jpeg|\\.dib|\\.ico|\\.tga|\\.cut|\\.pic)\\b)[^>]*>", 
            Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(htmlCode);
    String quote = null;
    String src = null;
    while (m.find()) {
        quote = m.group(1);
 
        // src=https://sms.reyo.cn:443/temp/screenshot/zY9Ur-KcyY6-2fVB1-1FSH4.png
        src = (quote == null || quote.trim().length() == 0) ? m.group(2).split("\\s+")[0] : m.group(2);
        imageSrcList.add(src);
 
    }
    return imageSrcList;
}