1

I have an image url (http://example.com/myimage.jpg) and want to convert it to byte array and save it in my DB.

I did the following, but getting this message 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();
halfer
  • 19,824
  • 17
  • 99
  • 186
emilan
  • 12,825
  • 11
  • 32
  • 37

1 Answers1

4

The Javadoc for File(URI) constructor specifies that the uri has to be a "File" URI. In other words, it should start with "file:"

uri An absolute, hierarchical URI with a scheme equal to "file", a non-empty path component, and undefined authority, query, and fragment components

But you can achieve what you are trying to do by using an URL, instead of a 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();
Laurel
  • 5,965
  • 14
  • 31
  • 57