保存网络图片到本地

2022-06-16 15:39
262
0
public static void savePicUrlToFile(String picUrl,String saveFilePath)
{
    try
    { 
        URL http;
        if (picUrl.trim().startsWith("https")) {
            http = new URL(picUrl);
            HttpsURLConnection conn = (HttpsURLConnection) http.openConnection();
            conn.setRequestMethod("GET");
        } else if (picUrl.trim().startsWith("http")) {
            http = new URL(picUrl);
            HttpURLConnection conn = (HttpURLConnection) http.openConnection();
            conn.setRequestMethod("GET");
        } else {
            http = new File(picUrl).toURI().toURL();
        }
        BufferedImage bi = ImageIO.read(http.openStream());
        File f = new File(saveFilePath);
        ImageOutputStream ios = ImageIO.createImageOutputStream(f);
        Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName("png");
        ImageWriter writer = it.next();
        writer.setOutput(ios);
        writer.write(bi);
        bi.flush();
        ios.flush();
        ios.close(); 
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

全部评论