<span style="white-space:pre"> </span>/** * @author luoguohui * @date 2015年7月16日 * Description: 通过HTTP请求获取网上或公司内网服务器图片 * @params urlStr 如http://creatim.allyes.com.cn/imedia/csdn/20150715/15_39_00_5A1E2C1E.jpg * @return Base64String */ public String getImageBase64OnService(String urlStr){ <span style="white-space:pre"> </span>InputStream bis = null; HttpURLConnection httpUrl = null; URL url = null; try { <span style="white-space:pre"> </span> url = new URL(<span style="font-family: Arial, Helvetica, sans-serif;">urlStr</span><span style="font-family: Arial, Helvetica, sans-serif;">); </span> <span style="white-space:pre"> </span> httpUrl = (HttpURLConnection) url.openConnection(); <span style="white-space:pre"> </span> httpUrl.connect(); <span style="white-space:pre"> </span> bis = httpUrl.getInputStream(); <span style="white-space:pre"> </span> ByteArrayOutputStream output = new ByteArrayOutputStream(); <span style="white-space:pre"> </span> byte[] buffer = new byte[4096]; <span style="white-space:pre"> </span> int n = 0; <span style="white-space:pre"> </span> while (-1 != (n = bis.read(buffer))) { <span style="white-space:pre"> </span> output.write(buffer, 0, n); <span style="white-space:pre"> </span> } <span style="white-space:pre"> </span> output.toByteArray(); <span style="white-space:pre"> </span> String imageBase64 = Base64.byteArrayToBase64(output.toByteArray()); <span style="white-space:pre"> </span> return imageBase64; } catch (IOException e) { } catch (ClassCastException e) { } finally { <span style="white-space:pre"> </span> try { <span style="white-space:pre"> </span> bis.close(); <span style="white-space:pre"> </span> httpUrl.disconnect(); <span style="white-space:pre"> </span> } catch (IOException e) { <span style="white-space:pre"> </span> } catch (NullPointerException e) { <span style="white-space:pre"> </span> } } return null; }
//以下是前端页面显示方式 <img id="pic" width="95" height="128" src = "data:image/png;base64,${imageBase64}">
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u013142781/article/details/46908949