随笔 - 93,  文章 - 0,  评论 - 40,  阅读 - 54500

 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   CccccDi  阅读(700)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2020-02-12 HashTable与LinkedHashMap
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示