【问题标题】:Get image with given url and convert it to byte array获取具有给定 url 的图像并将其转换为字节数组
【发布时间】:2013-10-28 08:14:36
【问题描述】:

我有一个图像 url (http://example.com/myimage.jpg) 并想将其转换为字节数组并将其保存在我的数据库中。

我执行了以下操作,但收到此消息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();

【问题讨论】:

    标签: java arrays image file uri


    【解决方案1】:

    File(URI) 构造函数的 Javadoc 指定 uri 必须是“文件”URI。换句话说,它应该以“文件:”开头

    uri 一个绝对的、分层的 URI,其方案等于“文件”,a 非空路径组件,以及未定义的权限、查询和分片 组件

    但是你可以通过使用 URL 而不是 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();
    

    【讨论】:

    • 为什么不直接保存字节,通过图像做肯定是一个很大的开销?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    • 2017-08-25
    • 2021-07-21
    相关资源
    最近更新 更多