java根据网络地址保存图片的方法
程序员文章站
2024-02-18 09:10:34
本文实例为大家分享了java根据网络地址保存图片的具体代码,供大家参考,具体内容如下
import java.io.bufferedinputstream;...
本文实例为大家分享了java根据网络地址保存图片的具体代码,供大家参考,具体内容如下
import java.io.bufferedinputstream; import java.io.file; import java.io.fileoutputstream; import java.io.ioexception; import java.net.httpurlconnection; import java.net.url; import java.util.random; import sun.misc.base64decoder; /** * 常用工具类 * @author 胡汉三 * * 2014-11-21 上午10:16:10 */ public class tools { public static void main(string[] args) throws exception { string str = "http://api.map.baidu.com/staticimage?center=106.720568,26.585137&width=697&height=550&markers=106.729443,26.593795&markerstyles=-1,http://api.map.baidu.com/images/marker_red.png,-1,23,25&zoom=15&labels=106.730143,26.594695&labelstyles=师大某小区包子铺,1,14,0xffffff,0xec624d,1"; tools dw=new tools(); dw.savetofile(str,"e:\\"+anguofileutils.getrandomfilename()+".png"); } /** * 根据网络地址保存图片 * @param desturl 网络地址 * @param filepath 图片存储路径 */ public void savetofile(string desturl,string filepath) { fileoutputstream fos = null; bufferedinputstream bis = null; httpurlconnection httpurl = null; url url = null; int buffer_size = 1024; byte[] buf = new byte[buffer_size]; int size = 0; try { url = new url(desturl); httpurl = (httpurlconnection) url.openconnection(); httpurl.connect(); bis = new bufferedinputstream(httpurl.getinputstream()); fos = new fileoutputstream(filepath); while ((size = bis.read(buf)) != -1) { fos.write(buf, 0, size); } fos.flush(); } catch (ioexception e) { } catch (classcastexception e) { } finally { try { fos.close(); bis.close(); httpurl.disconnect(); } catch (ioexception e) { } catch (nullpointerexception e) { } } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。