Java 从Url下载图像并转换为字节数组-android

Java 从Url下载图像并转换为字节数组-android,java,android,api,android-room,Java,Android,Api,Android Room,我从API接收图像和其他数据的URL,并将图像显示到recyclerview中,我想以字节数组格式将图像存储在room数据库中,但在将图像URL转换为字节数组时出错。我的应用程序在url.openstream()处崩溃 我建议使用以下伪代码从URL读取数据: Thread t = new Thread(new Runnable() { @Override public void run() { try

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


我建议使用以下伪代码从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();

我建议使用以下伪代码从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();

您的代码有几个问题:

  • 正如在注释中已经提到的,您调用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();
    }
私有静态字节[]getImageBytes(字符串imageUrl)引发IOException
{
URL URL=新URL(imageUrl);
ByteArrayOutputStream输出=新建ByteArrayOutputStream();
试试(InputStream=url.openStream())
{
字节[]缓冲区=新字节[4096];
while(true)
{
int bytesRead=stream.read(缓冲区);
if(bytesRead<0){break;}
输出写入(缓冲区,0,字节读取);
}
}
返回output.toByteArray();
}

您的代码有几个问题:

  • 正如在注释中已经提到的,您调用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();
    }
私有静态字节[]getImageBytes(字符串imageUrl)引发IOException
{
URL URL=新URL(imageUrl);
ByteArrayOutputStream输出=新建ByteArrayOutputStream();
试试(InputStream=url.openStream())
{
字节[]缓冲区=新字节[4096];
while(true)
{
int bytesRead=stream.read(缓冲区);
if(bytesRead<0){break;}
输出写入(缓冲区,0,字节读取);
}
}
返回output.toByteArray();
}

您正在调用openStream()两次。您正在调用openStream()两次。它不起作用,相同的问题在url处崩溃。openStream()这是我的示例url=“”。
getImageBytes(“https://live.staticflickr.com/65535/49490420043_1f38e0eac0_m.jpg")
对我有效。此操作是否需要任何特定的依赖项或清单文件?它不起作用,相同的问题在url处崩溃。openStream()这是我的示例url=“”。
getImageBytes(“https://live.staticflickr.com/65535/49490420043_1f38e0eac0_m.jpg")
对我有效。此操作是否需要任何特定的依赖项或清单文件?它不起作用,应用程序正在InputStreamReader isr=new InputStreamReader(connection.getInputStream())处崩溃;E/AndroidRuntime:致命异常:主。。。。java.net.URL.openStream(URL.java:1057)com.example.flickeapi.ui.home.HomeFragment.getByteArrayImage(HomeFragment.java:195)com.example.flickeapi.ui.home.home.HomeFragment.convertobytearray(HomeFragment.java:179)com.example.flickeapi.ui.home.home.HomeFragment.access$000(HomeFragment.java:59)在com.example.flickapi.ui.home.HomeFragment$1.onResponse(HomeFragment.java:120)上,这是我的示例URL=“live.staticflickr.com/65535/4949040402043_1f38e0eac0_m.jpg”。@ParagRane当我使用Your的URL来尝试我的代码时,我得到这个异常:live.staticflickr.com不允许IOException明文HTTP流量。也许URl是错的。请在postmanI中测试URL。我正在使用Flicker Api获取图像和数据。它不工作,应用程序在InputStreamReader isr=new InputStreamReader(connection.getInputStream())处崩溃;E/AndroidRuntime:致命异常:主。。。。java.net.URL.openStream(URL.java:1057)com.example.flickeapi.ui.home.HomeFragment.getByteArrayImage(HomeFragment.java:195)com.example.flickeapi.ui.home.home.HomeFragment.convertobytearray(HomeFragment.java:179)com.example.flickeapi.ui.home.home.HomeFragment.access$000(HomeFragment.java:59)在com.example.flickapi.ui.home.HomeFragment$1.onResponse(HomeFragment.java:120)上,这是我的示例URL=“live.staticflickr.com/65535/4949040402043_1f38e0eac0_m.jpg”。@ParagRane当我使用Your的URL来尝试我的代码时,我得到这个异常:live.staticflickr.com不允许IOException明文HTTP流量。也许URl是错的。请在postmanI中测试URL,我使用闪烁Api获取图像和数据