【问题标题】:Download Image from Url and covert into byte array - android从 Url 下载图像并转换为字节数组 - android
【发布时间】:2020-02-05 14:50:38
【问题描述】:

我从 API 接收图像和其他数据的 URL 并将图像显示到 recyclerview,我想以字节数组格式将图像存储在房间数据库中,但是在将图像 URL 转换为字节数组时出现错误.我的应用程序在 url.openstream(); 处崩溃。

private byte[] getByteArrayImage(String imageUrl) {

    URL url = null;
    try {
        url = new URL(imageUrl);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    try {
        byte[] chunk = new byte[4096];
        int bytesRead;
        InputStream stream = url.openStream();

        while ((bytesRead = stream.read(chunk)) > 0) {
            outputStream.write(chunk, 0, bytesRead);
        }

        url.openStream().close();

    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    return outputStream.toByteArray();
}

【问题讨论】:

  • 你调用 openStream() 两次。

标签: java android api android-room


【解决方案1】:

您的代码有几个问题:

  • 正如评论中已经指出的那样,您调用了两次 openStream()。
  • 如果发生异常,将不会在您的代码中调用 close()。请改用 try-with-resources。
  • 向调用者传播异常。调用者通常会想知道异常消息。
  • 永远不要使用 printStackTrace()。这是最糟糕的错误报告方式。
  • 在第一个 printStackTrace() 之后,您继续使用空 URI,这将导致 NullPointerException。
  • 方法应该是静态的。

我会这样写:

    private static byte[] getImageBytes(String imageUrl) throws IOException
    {
        URL url = new URL(imageUrl);

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try (InputStream stream = url.openStream())
        {
            byte[] buffer = new byte[4096];

            while (true)
            {
                int bytesRead = stream.read(buffer);
                if (bytesRead < 0) { break; }
                output.write(buffer, 0, bytesRead);
            }
        }

        return output.toByteArray();
    }

【讨论】:

  • 它不工作,同样的问题在 url.openStream() 崩溃
  • getImageBytes("https://live.staticflickr.com/65535/49490420043_1f38e0eac0_m.jpg") 为我工作。
  • 此操作是否需要任何特定的依赖项或清单文件?
【解决方案2】:

我推荐下面的伪代码从 URL 读取数据:

Thread t = new Thread(new Runnable()
    {
        @Override
        public void run()
        {
            try
            {
                URL url = new URL("you'r address");
                URLConnection connection = url.openConnection();
                InputStream is = connection.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                StringBuffer sb = new StringBuffer();
                int r;
                while((r = isr.read()) != -1)
                {
                    sb.append(r);
                }

                byte buffer[] = sb.toString().getBytes();

            }
            catch (MalformedURLException e)
            {
                e.printStackTrace();
                Log.i("tag" , "MalformedURLException"+e.getMessage());
            }
            catch (IOException e)
            {
                e.printStackTrace();
                Log.i("tag" , "IOException"+e.getMessage());
            }
        }
    });

    t.start();

【讨论】:

  • 它不起作用,应用程序在 InputStreamReader isr = new InputStreamReader(connection.getInputStream());
  • E/AndroidRuntime: FATAL EXCEPTION: main .... at java.net.URL.openStream(URL.java:1057) at com.example.flickerapi.ui.home.HomeFragment.getByteArrayImage( HomeFragment.java:195) 在 com.example.flickerapi.ui.home.HomeFragment.convertToBytearray(HomeFragment.java:179) 在 com.example.flickerapi.ui.home.HomeFragment.access$000(HomeFragment.java:59) 在com.example.flickerapi.ui.home.HomeFragment$1.onResponse(HomeFragment.java:120)
  • 这是我的示例 URL = "live.staticflickr.com/65535/49490420043_1f38e0eac0_m.jpg"。
  • @ParagRane 当我使用你的 URL 来尝试我的代码时,我得到了这个异常:IOException Cleartext HTTP traffic to live.staticflickr.com not allowed。也许 URl 是错误的。请在邮递员中测试网址
  • 我正在使用 Flicker Api 获取图像和数据
猜你喜欢
  • 2017-08-25
  • 2011-05-17
  • 1970-01-01
  • 1970-01-01
  • 2013-08-07
  • 2019-04-16
  • 2015-05-19
  • 1970-01-01
  • 2016-11-02
相关资源
最近更新 更多