1. 图片中存在中文时,可能会造成无法正确获取网络图片的问题,便需要进行转码。

String picNameUrlEncode = URLEncoder.encode(pictureUrl, "UTF-8");

 2.  具体实现

/**
     * 将网络图片编码为base64
     *
     * @param url 网络图片url
     * @return
     * @throws
     */
    public static String encodeImageToBase64(URL url) throws Exception {

//打开链接 HttpURLConnection conn = null; InputStream inStream = null; ByteArrayOutputStream out = null; try { conn = (HttpURLConnection) url.openConnection(); //设置请求方式为"GET" conn.setRequestMethod("GET"); //超时响应时间为5秒 conn.setConnectTimeout(5 * 1000); //通过输入流获取图片数据 inStream = conn.getInputStream(); //得到图片的二进制数据,以二进制封装得到数据,具有通用性 // ByteArrayOutputStream outStream = new ByteArrayOutputStream(); out = new ByteArrayOutputStream(); //创建一个Buffer字符串 byte[] buffer = new byte[1024]; //每次读取的字符串长度,如果为-1,代表全部读取完毕 int len = 0; //使用一个输入流从buffer里把数据读取出来 while ((len = inStream.read(buffer)) != -1) { //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度 out.write(buffer, 0, len); } byte[] data = out.toByteArray(); //对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder(); String base64 = encoder.encode(data); return base64;//返回Base64编码过的字节数组字符串 } catch (IOException e) { e.printStackTrace(); throw new Exception("========图片上传失败,请确定图片是否存在=========", e); } finally {//关闭输入流 if (out != null) { out.close(); } if (inStream != null) { inStream.close(); } } }

 

posted on 2022-02-12 16:56  CccccDi  阅读(695)  评论(0编辑  收藏  举报