您的位置:首页 > 理论基础 > 计算机网络

base64转码以及网络图片下载

2016-07-25 13:29 471 查看
import sun.misc.BASE64Encoder;

import java.io.File;

import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.URL;import java.net.URLConnection;

/**

* @Title: imgMakeBase64 * @Description: 图片转base64码 * @param filePath 网络路径全名 * @param fName 文件名

* @return String 返回类型 * @author: Konanconan * Create at: 2015年11月13日 下午4:54:29 */ private String imgMakeBase64(String filePath,String fName){ Properties props = null; try { props = PropertiesLoaderUtils.loadAllProperties("configs.properties"); } catch (IOException e) { LoggerUtils.hr11LogInfo("配置文件configs.properties读取失败", e); } String path = (String) props.get("filepath"); String filePath1=""; try { filePath1 = download(filePath,fName,path+fName.substring(fName.lastIndexOf("/")+1,fName.length())); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } File imgFile = new File(filePath1);// 待处理的图片 InputStream in = null; byte[] data = null; // 读取图片字节数组 try { in = new FileInputStream(imgFile); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } File f = new File(filePath1); f.delete(); // 对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data);// 返回Base64编码过的字节数组字符串 } public String download(String urlString, String filename,String savePath) throws Exception { //根据String形式创建一个URL对象, URL url = new URL(urlString); //实列一个URLconnection对象,用来读取和写入此 URL 引用的资源 URLConnection con = url.openConnection(); //获取一个输入流 InputStream is = con.getInputStream(); //实列一个输出对象 FileOutputStream fos = new FileOutputStream(savePath); //一个byte[]数组,一次读取多个字节 byte[] bt = new byte[200]; //用来接收每次读取的字节个数 int b = 0; //循环判断,如果读取的个数b为空了,则is.read()方法返回-1,具体请参考InputStream的read(); while ((b = is.read(bt)) != -1) { //将对象写入到对应的文件中 fos.write(bt, 0, b); } //刷新流 fos.flush(); //关闭流 fos.close(); is.close(); return savePath; }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: