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();

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Why not save the bytes directly, doing via an image is surely a big overhead?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.