Android : Big error while downloading images - android

I have tried three ways of downloading images. All suggest by members of Stackoverflow .
All the three methods fail to download all the images from the server. Few are downloaded and few are not.
I noticed a thing that each of the method fail to download image from particular position.
That is method 3 always fails to download the first three images. I changed the images but even then , the first three images are not downloaded.
Method 1:
public Bitmap downloadFromUrl( String imageurl )
{
Bitmap bm=null;
String imageUrl = imageurl;
try {
URL url = new URL(imageUrl); //you can write here any link
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
bm= BitmapFactory.decodeByteArray(baf.toByteArray(), 0, baf.toByteArray().length);
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
return bm;
}
Here the error i get for missed images is :SKIimagedecoder , the factory returned null.
Method: 2
public static Bitmap loadBitmap(String url)
{
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), 4*1024);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, 4 * 1024);
int byte_;
while ((byte_ = in.read()) != -1)
out.write(byte_);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
System.out.println(e);
Log.e("","Could not load Bitmap from: " + url);
} finally {
try{
in.close();
out.close();
}catch( IOException e )
{
System.out.println(e);
}
}
return bitmap;
}
The error i get here is same as above.
Method 3:
private Bitmap downloadFile(String fileUrl){
URL bitmapUrl =null;
Bitmap bmImg = null;
try {
bitmapUrl= new URL(fileUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpGet httpRequest = null;
try {
httpRequest = new HttpGet(bitmapUrl.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient
.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream instream = bufHttpEntity.getContent();
bmImg = BitmapFactory.decodeStream(instream);
} catch (Exception e) {
System.out.println(e);
}
return bmImg;
}
The error i get here is : org.apache.http.NoHttpResponseException: The target server failed to respond.
please help. It is the only thing stopping me from completing the project.

Take a look at this.. Clearly explained about image download from the Server..Image from Server....

I'm assuming you are downloading the images to display rather than just save on the device. If this is the case, I recommend looking into using Droid-Fu, more specifically WebImageView. You can just pass the URL to the WebImageView and it will load the image as it can, which will avoid having an image fail to load because of the connection timing out, which I'm guessing is the problem you are having.
In XML:
<com.github.droidfu.widgets.WebImageView
android:id="#+id/image"
android:layout_width="70dip"
android:layout_height="70dip"
droidfu:autoLoad="true"
droidfu:progressDrawable="..."
/>
In Code:
WebImageView image = (WebImageView) convertView.findViewById(R.id.image);
image.setImageUrl(image_url);
image.loadImage();

It's possible that your creation of bitmaps takes time and therefore the connection times out. You could possibly get references to all the inputstreams and then download and create. This is a rough-cut answer, but if the reasoning is right, you can improve on it:
public Bitmap[] downloadFromUrl(String[] imageUrls)
{
Bitmap[] bm = new Bitmap[imageUrls.length];
BufferedInputStream[] bis = new BufferedInputStream[imageUrls.length];
for (int i = 0; i < imageUrls.length; i++)
{
try
{
URL url = new URL(imageUrls[i]); // you can write here any link
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
bis[i] = new BufferedInputStream(is);
}
catch (IOException e)
{
e.printStackTrace();
}
}
for (int i = 0; i < bis.length; i++)
{
try
{
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis[i].read()) != -1)
{
baf.append((byte) current);
}
bm[i] = BitmapFactory.decodeByteArray(baf.toByteArray(), 0, baf.toByteArray().length);
}
catch (IOException e)
{
e.printStackTrace();
}
}
return bm;
}

Related

How to get String type in setImageResource method?

My code: holder.icon.setImageResource(current.imageUrl); here the imageUrl is been declared in String. But setImageResource takes only int. Can anyone provide me a solution how to get a string or is there anyother method available for it?
I think u are fetch the image from internet.
private Bitmap getBitMapFromUrl( String imageuri){
HttpURLConnection connection=null;
try {
URL url=new URL(imageuri);
connection= (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream is=connection.getInputStream();
Bitmap mybitmap=BitmapFactory.decodeStream(is);
return mybitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}}
pass the string value and return the bitmap.
holder.icon.setImageBitmap(getBitmapFromUrl());
you are using the "setImageResource" !
it expects a Resource (usually a drawable resource), hence the int requirement.
the download solution suggested by #Mayuri Joshi might fit your needs, if not, please provide more information regarding what it is you are trying to accomplish :)
You have to download the image firstly
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
Then use the Imageview.setImageBitmap to set bitmap into the ImageView

BitmapFactory decode issue

url="http://www.nasa.gov/sites/default/files/styles/946xvariable_height/public/ladee_spin_2_in_motion_0_0.jpg?itok=yNhf69rE";
try {
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
input.close();
return bitmap;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
I was tryning to retreive image from the url but no matter what it always returns null. In debugging mode I have observed that it happens when it tries input.close(); .
How can I possibly get the Image.
This is a proper way to load Bitmap:
InputStream is;
Bitmap bitmap;
is = context.getResources().openRawResource(DRAW_SOURCE);
bitmap = BitmapFactory.decodeStream(is);
try {
is.close();
is = null;
} catch (IOException e) {
}
However, as I see you close stream before finish to decoding it.
If so, use other way:
Bitmap bitmap;
InputStream input = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(input, 8192);
ByteArrayBuffer buff = new ByteArrayBuffer(64);
int current = 0;
while ((current = bis.read()) != -1) {
buff.append((byte)current);
}
byte[] imageData = buff.toByteArray();
bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
try {
is.close();
is = null;
} catch (IOException e) {
}
BTW, see this post, it should work also

Set button background image from url

I was wondering how i set a buttons background image from a URL on android.
The buttons id is blue if you need to know that.
I tried this but it didn't work.
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
I used the next code for obtain the bitmap, one important thing is sometimes you can't obtain the InputStream, and that is null, I make 3 attemps if that happens.
public Bitmap generateBitmap(String url){
bitmap_picture = null;
int intentos = 0;
boolean exception = true;
while((exception) && (intentos < 3)){
try {
URL imageURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageURL.openConnection();
conn.connect();
InputStream bitIs = conn.getInputStream();
if(bitIs != null){
bitmap_picture = BitmapFactory.decodeStream(bitIs);
exception = false;
}else{
Log.e("InputStream", "Viene null");
}
} catch (MalformedURLException e) {
e.printStackTrace();
exception = true;
} catch (IOException e) {
e.printStackTrace();
exception = true;
}
intentos++;
}
return bitmap_picture;
}
Don't load the image directly in the UI (main) thread, for it will make the UI freeze while the image is being loaded. Do it in a separate thread instead, for example using an AsyncTask. The AsyncTask will let the image load in its doInBackground() method and then it can be set as the button background image in the onPostExecute() method. See this answer: https://stackoverflow.com/a/10868126/2241463
Try this code:
Bitmap bmpbtn = loadBitmap(yoururl);
button1.setImageBitmap(bmpbtn);

android picture download

I return a Bitmap object according to a url, and the code for download picture:
URL url = new URL(imageUrlStr);
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream in = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
in.close
Then I save it to sdcard. It is ok to save picture.
Now the problem is it download the picture A when use this url to access. But it now shows another B picture in SDCARD. How to solve this problem?
You can identify images by hash-code. Not a perfect solution, good for the demo
private Bitmap getBitmap(String url) {
String filename = String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
// from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;
// from web
try {
Bitmap bitmap = null;
InputStream is = new URL(url).openStream();
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
private void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
/** decodes image and scales it to reduce memory consumption*/
private Bitmap decodeFile(File f) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
return BitmapFactory.decodeStream(new FileInputStream(f));
} catch (FileNotFoundException e) {
}
return null;
}
Use you just need to use method "getBitmap(String)" with your desired url as String

bitmapfactory fails to load images

I have a android app to load multiple images from mysql database onto a ImageButton.
imageButton.setImageBitmap(fetchBitmap("http://www...~.jpg"));
I was once able to load png successfully but it also fails now (No success with jpg images ever). Here is the code I use for downloading images:-
public static Bitmap fetchBitmap(String urlstr) {
InputStream is= null;
Bitmap bm= null;
try{
HttpGet httpRequest = new HttpGet(urlstr);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
is = bufHttpEntity.getContent();
BitmapFactory.Options factoryOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeStream(is);
}catch ( MalformedURLException e ){
Log.d( "RemoteImageHandler", "Invalid URL: " + urlstr );
}catch ( IOException e ){
Log.d( "RemoteImageHandler", "IO exception: " + e );
}finally{
if(is!=null)try{
is.close();
}catch(IOException e){}
}
return bm;
}
I get this error:-
D/skia(4965): --- SkImageDecoder::Factory returned null
I have already tried various combinations as suggested here, here and several other solutions, but it doesnt work for me. Am I missing something? Image is definitely present in the web address I enter.
Thank you.
Use below code for download image and store into bitmap, it may help you.
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
The problem was that the images could not be downloaded because the directory in which the images were kept did not have "execute" permission. As soon as the permission was added, the app works smoothly :)

Categories

Resources