I have tried to get the bitmap image from the path of the image. But BitmapFactory.decodeStream
returns null
value.
Code:
U
using the following code iam able to download an image from the url
String IMAGE_URL = "http://www.kolkatabirds.com/rainquail8vt.jpg";
//where we want to download it from
URL url;
try {
url = new URL(IMAGE_URL);
//open the connection
URLConnection ucon = url.openConnection();
//buffer the download
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is,1024);
//get the bytes one by one
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
//convert it back to an image
ByteArrayInputStream imageStream = new ByteArrayInputStream(baf.toByteArray());
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
img.setImageBitmap(theImage);
Got a Solution :
HttpGet httpRequest = new HttpGet(URI.create(path) );
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
bmp = BitmapFactory.decodeStream(bufHttpEntity.getContent());
httpRequest.abort();
The problem was that once you've used an InputStream
from a HttpUrlConnection
, you can't rewind and use the same InputStream
again. Therefore you have to create a new InputStream
for the actual sampling of the image. Otherwise we have to abort the HTTP
request.
public Bitmap getBitmapFromUrl(String url)
{
Bitmap bm = null;
InputStream is = null;
BufferedInputStream bis = null;
try
{
URLConnection conn = new URL(url).openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream(is, 8192);
bm = BitmapFactory.decodeStream(bis);
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
if (bis != null)
{
try
{
bis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
if (is != null)
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return bm;
}
Dont forget to call this within a thread (not Main thread)
I had the same problem but in my case the problem was the resource (image). Be sure the image is not in CMYK color mode since Android does not support CMYK images. See this question for more details
Good luck ;)
BufferedInputStream is necessary before decodestream....
Try this it works perfect for me use;
BufferedInputStream buf = new BufferedInputStream(inputsteam, 1024);
Pass buf to decode stream it will work perfectly.
Bitmap theImage = BitmapFactory.decodeStream(buf);
Finally set your bitmap.