java

Java通过图片url地址转图片base64位字符串

rzk · 6月18日 · 2022年本文共4122个字 · 预计阅读14分钟804次已读

Java通过图片url地址转图片base64位字符串


/**
 * @PackageName : com.rzk
 * @FileName : Base64Util
 * @Description :
 * @Author : rzk
 * @CreateTime : 2022/6/17 13:44
 * @Version : 1.0.0
 */
import sun.misc.BASE64Encoder;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Base64Util {

    /**
     * 图片URL转Base64编码
     * @param imgUrl 图片URL
     * @return Base64编码
     */
    public static String imageUrlToBase64(String imgUrl) {
        URL url = null;
        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        HttpURLConnection httpUrl = null;

        try {
            url = new URL(imgUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();

            is = httpUrl.getInputStream();
            outStream = new ByteArrayOutputStream();

            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度,如果为-1,代表全部读取完毕
            int len = 0;
            //使用输入流从buffer里把数据读取出来
            while( (len = is.read(buffer)) != -1 ){
                //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
                outStream.write(buffer, 0, len);
            }

            // 对字节数组Base64编码
            return encode(outStream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(is != null) {
                    is.close();
                }
                if(outStream != null) {
                    outStream.close();
                }
                if(httpUrl != null) {
                    httpUrl.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    /**
     * 图片转字符串
     * @param image 图片Buffer
     * @return Base64编码
     */
    public static String encode(byte[] image){
        BASE64Encoder decoder = new BASE64Encoder();
        return replaceEnter(decoder.encode(image));
    }

    /**
     * 字符替换
     * @param str 字符串
     * @return 替换后的字符串
     */
    public static String replaceEnter(String str){
        String reg ="[n-r]";
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(str);
        return m.replaceAll("");
    }

    public static void main(String[] args) {
        System.out.println(Base64Util.imageUrlToBase64("https://www.baidu.com/img/PCfb_5bf082d29588c07f842ccde3f97243ea.png"));
    }

}

java接口读取流返回给前端(一)

    @RequestMapping(value = "/downloadUrl", method = RequestMethod.POST)
    @ResponseBody
    public String downloadAttachment(HttpServletResponse response) {

        String downLoadPath = "这里做数据处理获取url";
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {

            //响应二进制流
            response.setContentType("application/octet-stream");
            response.reset();//清除response中的缓存
            //根据网络文件地址创建URL  
            URL url = new URL(downLoadPath);
            //获取此路径的连接  
            URLConnection conn = url.openConnection();
            Long fileLength = conn.getContentLengthLong();//获取文件大小  
            //设置reponse响应头,真实文件名重命名,就是在这里设置,设置编码  
            //response.setHeader("Content-Disposition","attachment; filename=" + fileName);
            response.setHeader("Content-Length", String.valueOf(fileLength));

            bis = new BufferedInputStream(conn.getInputStream());//构造读取流  
            bos = new BufferedOutputStream(response.getOutputStream());//构造输出流  
            byte[] buff = new byte[1024];
            int bytesRead;
            //每次读取缓存大小的流,写到输出流  
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            response.flushBuffer();//将所有的读取的流返回给客户端  
        } catch (IOException e) {
            logger.error("文件下载失败!", e);
            throw new CommonException("文件下载失败!");
        }finally{
            try{
                if(null != bis){
                    bis.close();
                }
                if(null != bos){
                    bos.close();
                }
            }catch(IOException e){
                logger.error("文件下载失败!", e);
                throw new CommonException("文件下载失败!");
            }
        }
        return null;
    }

java接口读取流返回给前端(二)

 @RequestMapping(value = "/downloadUrl", method = RequestMethod.POST)
    @ResponseBody
    public String downloadAttachment(HttpServletResponse response) {

        String downLoadPath = "这里做数据处理获取url";
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {

            //响应二进制流
            response.setContentType("application/octet-stream");
            response.reset();//清除response中的缓存
            //根据网络文件地址创建URL
            URL url = new URL(downLoadPath);
            //获取此路径的连接
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(3*1000);//设置连接超时时间
            InputStream inputStream = conn.getInputStream();//通过输入流获取图片数据

            byte[] byteImg = readInputStream(inputStream);
            return byteImg;
        } catch (IOException e) {
            logger.error("文件下载失败!", e);
            throw new CommonException("文件下载失败!");
        }finally{
            try{
                if(null != bis){
                    bis.close();
                }
                if(null != bos){
                    bos.close();
                }
            }catch(IOException e){
                logger.error("文件下载失败!", e);
                throw new CommonException("文件下载失败!");
            }
        }
        return null;
    }

    private static byte[] readInputStream(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        //每次读取缓存大小的流,写到输出流
        while ((len = inputStream.read(buffer))!=-1) {
            outputStream.write(buffer, 0, len);
        }
        inputStream.close();
        return outputStream.toByteArray();
    }
0 条回应