微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

文件与byte[]互转

        前段时间写一个供android程序调用的webservice,之中一个接口要根据传来的图片地址转换成byte[]返回,现记录下来以备再用。代码如下:

/*
 * 根据图片的网络地址,将图片转化成byte[]
 */
public byte[] getimageToBytes(String imgPath) {

	byte[] bytes = null;

	imgPath = "http://127.0.0.1:8080/upload/"+ imgPath;
	System.out.println(imgPath);

	ByteArrayOutputStream out = new ByteArrayOutputStream();

	try {
		//创建URL
		URL url = new URL(imgPath);
		//得到连接
		HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
		//得到连接地址的输入流
		InputStream in = urlConn.getInputStream();

		int size;
		//缓冲值
		bytes = new byte[1024];
		if(in != null){
			//循环读输入流至read返回-1为止,并写到缓存中
			while((size=in.read(bytes)) != -1){
				out.write(bytes,size);
			}
		}
		out.close();//关闭输出流
		in.close();//关闭输入流
		urlConn.disconnect();//断开连接

		} catch (Exception e) {
			e.printstacktrace();
		}

		return out.toByteArray();
}
/*
 * 将byte[]数组转成image存到本地
 */
public void bytesToImgSave(byte[] b,String imgFileType) throws Exception{
	//UUID序列号作为保存图片名称
	String name = UUID.randomUUID().toString();

	File f = new File("E:\\upload");

	//是否存在该目录,如果不存在则创建
	if(!f.isDirectory()){
		f.mkdirs();
	}

	OutputStream os = new FileOutputStream(new File(f.getAbsolutePath()+"\\"+name+"."+imgFileType));
	os.write(b);
	os.flush();
	os.close();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐