Java 使用给定的 url 获取图像并将其转换为字节数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19467386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get image with given url and convert it to byte array
提问by emilan
I have an image url (http://example.com/myimage.jpg) and want to convert it to byte array and save it in my DB.
我有一个图像 url ( http://example.com/myimage.jpg) 并希望将其转换为字节数组并将其保存在我的数据库中。
I did the following, but getting this message URI scheme is not "file"
我做了以下,但收到这条消息 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();
采纳答案by Srikanth Reddy Lingala
The Javadocfor File(URI)
constructor specifies that the uri has to be a "File" URI. In other words, it should start with "file:"
该的Javadoc用于File(URI)
该URI具有构造函数指定为“文件” URI。换句话说,它应该以“file:”开头
uriAn absolute, hierarchical URI with a scheme equal to "file", a non-empty path component, and undefined authority, query, and fragment components
uri一个绝对的分层 URI,其方案等于“文件”、一个非空路径组件以及未定义的权限、查询和片段组件
But you can achieve what you are trying to do by using an URL, instead of a File/URI:
但是您可以通过使用 URL 而不是文件/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();