-1

How can I convert an image(with url) to base 64:

I tried following, but it did not work

InputStream inputStream = null;
try {
    inputStream = new BufferedInputStream(
            new FileInputStream("https://blahblah/xyz.png"));
} catch (IOException e) {
    e.printStackTrace();
}

byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();

try {
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        output.write(buffer, 0, bytesRead);
    }
} catch (IOException e) {
    e.printStackTrace();
}
bytes = output.toByteArray();
String encodedImage = Base64.encodeToString(bytes, Base64.DEFAULT);

Got error at first try and catch. Can anyone suggest, what can be done?

Using new URL("https://blahblah/xyz.png").openStream(), it crashes with following error:

android.os.NetworkOnMainThreadException
clint
  • 1,786
  • 4
  • 34
  • 60

1 Answers1

0

First download the image from that given url, then using Bitmap convert it into byte array, then do the Base64 encoding.

Manoj Perumarath
  • 9,337
  • 8
  • 56
  • 77