File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes get image from URL using inputstream Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "get image from URL using inputstream" Watch "get image from URL using inputstream" New topic

get image from URL using inputstream

Sam Venkata
Ranch Hand

Joined: Mar 06, 2006
Posts: 68
I am trying to get images from a url using a inputstream. The following is the sample code.
int length=connection.getContentLength();
//System.out.println("Content length : "+length);
if (inputStream!=null)
blob=new byte[length];;

I am able to get the image but only part of the image is good and the other part is damaged(Some thing like a mosaic type).
Is there anything that I am missing.
Can anybody please help me.

Anupam Bhatt
Ranch Hand

Joined: Mar 12, 2004
Posts: 81
Hi Samanth,

Could you please post the writing part of the code too ?
My guess is the during the write, you are not closing the outputstream or flushing it explicitly.

Having the code here would make it easy to help you !

Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I've never used content length. Do you think the numbers you get back are always reliable? I just read bytes until read returns -1.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Sam Venkata
Ranch Hand

Joined: Mar 06, 2006
Posts: 68
My code looks something like this:

The class that I use to store it in the database is below:

It would be really helpful if anybody could help me with this.

[ June 25, 2007: Message edited by: Jim Yingst ]
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Please use code tags to make your code more readable by preserving indentation. I have added them to your last post above. I would have added them to the first post, but the indentation there was very strange, and did not help readability for me.

Looking just at your code to read the array, I would say that the problem is you're not checking the return value of the read(). It's always possible for a single read() to be incomplete, and you need to put the method inside a loop if you want to ensure that it reads all of the bytes you want. E.g.

Or as Stan suggests, it's probably better to not trust the getContentLength(), and instead just read until the end:

"I'm not back." - Bill Harding, Twister
Sam Venkata
Ranch Hand

Joined: Mar 06, 2006
Posts: 68
Thanks a million that worked. I am really sorry about the indentation, I was not aware of it. I would make sure I use code tags next time.

I agree. Here's the link:
subject: get image from URL using inputstream
It's not a secret anymore!