java根据网络地址保存图片 java根据网络地址保存图片的方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

java根据网络地址保存图片 java根据网络地址保存图片的方法

小爷胡汉三   2021-03-31 我要评论


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

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们