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;
        }
  • 相关阅读:
    Mac 卸载MySql的方法
    关于mysql的wait_timeout参数 设置不生效的问题
    linux下利用nohup后台运行jar文件包程序
    MySql创建视图
    spring mvc获取header
    Spring Data Jpa 查询返回自定义对象
    Caused by: org.xml.sax.SAXParseException: The reference to entity "characterEncoding" must end with the ';' delimiter.
    eclipse Reference 功能之——项目之间的引用
    Mac 在启动eclipse时 Failed to load JavaHL Library解决方法
    MySQL Workbench update语句错误Error Code: 1175.
  • 原文地址:https://www.cnblogs.com/lizuoqi/p/5703163.html
Copyright © 2011-2022 走看看