zoukankan      html  css  js  c++  java
  • base64转码以及网络图片下载

    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;
        }
  • 相关阅读:
    NFC学习一个记录
    谈话《百度搜索引擎的网页质量白皮书》
    EBS OAF 发展 URL商标、加密和编码
    绘制一个简单的实现接口盘
    [AngularFire2] Pagination
    [TypeScript] The Basics of Generics in TypeScript
    [TypeScript] Using Assertion to Convert Types in TypeScript
    [TypeScript] Sharing Class Behavior with Inheritance in TypeScript
    [TypeScript] Creating a Class in TypeScript
    [Angular2 Router] Preload lzay loading modules
  • 原文地址:https://www.cnblogs.com/lizuoqi/p/5703163.html
Copyright © 2011-2022 走看看