本地和网络图片读取返回base64编码串

直接上代码


package com.pax.busi.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by 2810010108@qq.com on 2016/7/21.
 */
public class ImageUtils {
    private static final Logger logger = LoggerFactory.getLogger(ImageUtils.class);

    /**
     * 将本地图片编码为base64
     *
     * @param file
     * @return
     * @throws BusinessException
     */
    public static String encodeImageToBase64(File file) throws BusinessException {
        //将图片文件转化为字节数组字符串,并对其进行Base64编码处理
        logger.info("图片的路径为:" + file.getAbsolutePath());
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(file);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("图片上传失败,请联系客服!");
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        String base64 = encoder.encode(data);
        logger.info("本地文件[{}]编码成base64字符串:[{}]", file.getAbsolutePath(), base64);
        return base64;//返回Base64编码过的字节数组字符串
    }

    /**
     * 将网络图片编码为base64
     *
     * @param url
     * @return
     * @throws BusinessException
     */
    public static String encodeImageToBase64(URL url) throws BusinessException {
        //将图片文件转化为字节数组字符串,并对其进行Base64编码处理
        logger.info("图片的路径为:" + url.toString());
        //打开链接
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
            //设置请求方式为"GET"
            conn.setRequestMethod("GET");
            //超时响应时间为5秒
            conn.setConnectTimeout(5 * 1000);
            //通过输入流获取图片数据
            InputStream inStream = conn.getInputStream();
            //得到图片的二进制数据,以二进制封装得到数据,具有通用性
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度,如果为-1,代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            //关闭输入流
            inStream.close();
            byte[] data = outStream.toByteArray();
            //对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            String base64 = encoder.encode(data);
            logger.info("网络文件[{}]编码成base64字符串:[{}]", url.toString(), base64);
            return base64;//返回Base64编码过的字节数组字符串
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("图片上传失败,请联系客服!");
        }
    }

    public static void main(String[] args) throws MalformedURLException {
        String str1 = encodeImageToBase64(new URL("https://dl.django.t.taobao" +
                ".com/rest/1.0/image?fileIds=-8F7pMDLTWK9OkMAC4R-iwAAACMAAQED&zoom=original"));
        // String str2 = encodeImageToBase64(new File("C:\\Users\\PAX\\Desktop\\images\\test\\123456789.jpg"));
        // System.out.println(str2);
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

羽轩GM

您的鼓励是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值