get image from a url using InputStream issues
Hi,
I am trying to an image from an URL. I am able to get the image but the image is damaged.
my code looks as follows.
public static byte[] getImage(String imageURL)
{
byte[] blob=null;
if (imageURL!=null&&(imageURL=imageURL.trim()).length()>0)
{
InputStream inputStream=null;
HttpURLConnection connection = null;
try
{
connection = (HttpURLConnection)new URL(imageURL.replace("&","&").replace(" ","%20")).openConnection();
connection.setRequestProperty("User-agent", Constant.USER_AGENT);
connection.setReadTimeout(36*Constant.CONNECTION_TIMEOUT);
connection.setConnectTimeout(Constant.CONNECTION_TIMEOUT);
connection.connect();
int length=connection.getContentLength();
//System.out.println("Content length : "+length);
inputStream=connection.getInputStream();
if (inputStream!=null)
{
blob=new byte[length];
inputStream.read(blob);
inputStream.close();
inputStream=null;
}
}
catch(MalformedURLException err)
{
inputStream=null;
Functions.log("MalformedURLException: "+imageURL+" -- "+err+" -- "+err.getMessage(), "EX_getImage");//DEBUG
}
catch(Exception err)
{
inputStream=null;
Functions.log("Exception: "+imageURL+" -- "+err+" -- "+err.getMessage(), "EX_getImage");//DEBUG
}
finally
{
try
{
if (inputStream!=null)
{
inputStream.close();
inputStream=null;
}
}
catch(Exception err)
{
inputStream=null;
Functions.log("InputStreamException: "+err+" -- "+err.getMessage(), "EX_getImage");//DEBUG
}
try
{
if (connection!=null)
{
connection.disconnect();
connection=null;
}
}
catch(Exception err)
{
inputStream=null;
Functions.log("ConncetionException: "+err+" -- "+err.getMessage(), "EX_getImage");//DEBUG
}
}
}
try
{
BufferedImage image = ImageIO.read ( new ByteArrayInputStream ( blob ) );
ImageIO.write(image, "jpg" /* format desired */, new File("C:\\test\\test4.jpg") /* target */ );
}
catch(Exception e)
{
}
return blob;
}//getImage()
Can some body help me with this, what is it that I am doing wrong. It would be really helpful to me.
Thanks,
Samanth.

