使用给定的URL获取图像并将其转换为字节数组 [英] Get image with given url and convert it to byte array

查看:738
本文介绍了使用给定的URL获取图像并将其转换为字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图片网址( http://example.com/myimage.jpg ),并希望将其转换为字节数组并将其保存在我的数据库中。请帮助我一些例子。

我做了以下,但得到这个消息 URI方案不是文件

  URI uri = new URI(profileImgUrl); 
档案fnew =新档案(uri);
BufferedImage originalImage = ImageIO.read(fnew);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(originalImage,jpg,baos);
byte [] imageInByte = baos.toByteArray();


解决方案

Javadoc for (URI)构造函数指定uri必须是FileURI。换句话说,它应该以file:开始。


uri 等于文件,
非空路径组件,以及未定义的权限,查询和片段
组件

但是,您可以通过使用URL而不是File / URI来实现您正在尝试执行的操作:

  URL imageURL =新的URL(profileImgUrl); 
BufferedImage originalImage = ImageIO.read(imageURL);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(originalImage,jpg,baos);

//坚持 - 在这种情况下是文件

FileOutputStream fos = new FileOutputStream(outputImageName.jpg);
baos.writeTo(fos);
fos.close();


I have an image url (http://example.com/myimage.jpg) and want to convert it to byte array and save it in my DB. Pls help me with some example.

I did the following, but getting this message URI scheme is not "file"

URI uri = new URI(profileImgUrl);
File fnew = new File(uri);
BufferedImage originalImage=ImageIO.read(fnew);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ImageIO.write(originalImage, "jpg", baos );
byte[] imageInByte=baos.toByteArray();

解决方案

The Javadoc for File(URI) constructor specifies that the uri has to be a "File" URI. In other words, it should start with "file:"

uri An absolute, hierarchical URI with a scheme equal to "file", a non-empty path component, and undefined authority, query, and fragment components

But you can achieve what you are trying to do by using an URL, instead of a File/URI:

URL imageURL = new URL(profileImgUrl);
BufferedImage originalImage=ImageIO.read(imageURL);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ImageIO.write(originalImage, "jpg", baos );

//Persist - in this case to a file

FileOutputStream fos = new FileOutputStream("outputImageName.jpg");
baos.writeTo(fos);
fos.close();

这篇关于使用给定的URL获取图像并将其转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆