前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >通过http URL 获取图片流 转为字节数组

通过http URL 获取图片流 转为字节数组

作者头像
botkenni
发布2021-10-12 10:53:47
1.4K0
发布2021-10-12 10:53:47
举报
文章被收录于专栏:IT码农

一、通过http URL 获取图片流 转为字节数组

/** * 获取 文件 流 * @param url * @return * @throws IOException */ private byte[] getFile(String url) throws IOException{ URL urlConet = new URL(url); HttpURLConnection con = (HttpURLConnection)urlConet.openConnection(); con.setRequestMethod("GET"); con.setConnectTimeout(4 * 1000); InputStream inStream = con .getInputStream(); //通过输入流获取图片数据 ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int len = 0; while( (len=inStream.read(buffer)) != -1 ){ outStream.write(buffer, 0, len); } inStream.close(); byte[] data = outStream.toByteArray(); return data; }

二、读取本地文件转为数组

/** * 读取 本地文件,转为字节数组 * @param url 本地文件路径 * @return * @throws IOException */ private byte[] getImage(String url) throws IOException{ BufferedInputStream in = new BufferedInputStream(new FileInputStream(url)); ByteArrayOutputStream out = new ByteArrayOutputStream(1024); byte[] temp = new byte[2048]; int size = 0; while ((size = in.read(temp)) != -1) { out.write(temp, 0, size); } in.close(); byte[] content = out.toByteArray(); return content; }

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档