title: Download Image from Url and covert into byte array - android
body: <p>I'm receiving URL of images and other data from API and showing images into recyclerview, I want to store images in room database in a byte array format, but I'm getting an error while converting image URL to a byte array. My app is crashing at url.openstream();.</p>
  
  <pre><code>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)) &gt; 0) {
              outputStream.write(chunk, 0, bytesRead);
          }
  
          url.openStream().close();
  
      } catch (IOException e) {
          e.printStackTrace();
          return null;
      }
  
      return outputStream.toByteArray();
  }
  </code></pre>