Why is BitmapFactory.decodeStream returning null? - android

Basically I am parsing some JSON that has an image with it and trying to load it into a ImageView. However mBitmap is returning null. I have no idea why and further research has not helped..
Here is an example url I am working with:
http://b.thumbs.redditmedia.com/ivBAJzLMJEkEy9jgTy3z4n-mO7gIGt5mQFU1Al5kJ-I.jpg
Here is all relevant code:
public static Bitmap LoadImageFromUrl(String url){
try {
mBitmap = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
return mBitmap;
}catch (Exception e){
Log.d(TAG,"Error getting image");
return null;
}
}
Here is where the method is called:
mListingModel.setmImageView(LoadImageFromUrl(data.getString(JSON_THUMBNAIL)));
Here is where I set the ImageView:
if(mItem.getmImageView() != null) {
holder.imageView.setImageBitmap(mItem.getmImageView());
}
Note: I am calling the method in an AsyncTask so that is not the problem.

The javadoc for Bitmap.decodeStream() states that:
If the input stream is null, or cannot be used to decode a bitmap, the
function returns null
You're passing it the results of URL.getContent(), which states in its javadoc:
By default this returns an InputStream, or null if the content type of
the response is unknown.
So maybe you should check to see if getContent() returns null before passing it on to the decoder.

i had in the past stupid problems like having my stream reached the end before i decoded it, so ensure to set it's position to 0 before decoding the stream
eg.
stream.Position = 0;
var bmp = BitmapFactory.DecodeStream(stream);

Can you check if this works for you:
InputStream in = new java.net.URL(downloadURL).openStream();
Bitmap avatarBmp = BitmapFactory.decodeStream(in);
in.close();
Also a reminder to add this in your Manifest
<uses-permission android:name="android.permission.INTERNET" />

I had the same problem.
I tried to find decode fail reason.. but I couldn't find.
I just confirmed that InputStream and BufferedInputStream are not null.
After restarting my AVD.. the problem was resolved even though I didn't change any code.

Related

Importing image from internet into Bitmap

I have problem with Bitmap.
I call method:
mStickerListener.onStickerClick(
BitmapFactory.decodeResource(getResources(),
Integer.parseInt(stickerList.get(getLayoutPosition()))));
But the problem is my stickerList.get(getLayoutPosition()))) returns String value(link), because I show images with Picasso, so I get exception:
java.lang.NumberFormatException: For input string: "https://firebasestorage.googleapis.com/v0/b/templatestest-38e3f.appspot.com/o/templates%2Fanimals_templates%2Fdog.png?alt=media&token=3e31962f-df24-493a-91c9-273f3496fa89"
Please, help me solve it!
First of all the exception you are getting says that you are trying to convert a string "https://firebasestorage.googleapis.com/v0/b/templatestest-38e3f.appspot.com/o/templates%2Fanimals_templates%2Fdog.png?alt=media&token=3e31962f-df24-493a-91c9-273f3496fa89" to Integer
The method you are using BitmapFactory.decodeResource takes id of the resource as an input not an url.
You need to use the following code to get bitmap from the url:
try {
URL url = new URL("https://firebasestorage.googleapis.com/v0/b/templatestest-38e3f.appspot.com/o/templates%2Fanimals_templates%2Fdog.png?alt=media&token=3e31962f-df24-493a-91c9-273f3496fa89");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch(IOException e) {
System.out.println(e);
}
Also, add the Internet permission in AndroidManifest.xml as you will be accessing internet for getting stream from an url.
<uses-permission android:name="android.permission.INTERNET" />

BitmapFactory.decodeStream always returning null value

Here I am fetching value from Cursor :
if (mProfileCursor.moveToFirst()) {
byte[] blob = mProfileCursor.getBlob(
mProfileCursor.getColumnIndex(ContactsContract.Profile.PHOTO_URI));
ByteArrayInputStream inputStream = new ByteArrayInputStream(blob);
BufferedInputStream bis = new BufferedInputStream(inputStream,1024);
bitmap = BitmapFactory.decodeStream(bis);
}
} finally {
if (mProfileCursor != null) {
mProfileCursor.close();
}
}
I am trying to change byte[] into a bitmap but I am getting always null, according to answers in following post Android: bitmapfactory.decodestream returns null I tried BufferedInputStream but it is not working for me.
Also Romain Guy here said that this is a known defect in android but answer is very old, please let me know if there is way for getting bitmap correct.
public static final String PHOTO_URI
Added in API level 11
A URI that can be used to retrieve the contact's full-size photo. If PHOTO_FILE_ID is not null, this will be populated with a URI based off CONTENT_URI. Otherwise, this will be populated with the same value as PHOTO_THUMBNAIL_URI. A photo can be referred to either by a URI (this field) or by ID (see PHOTO_ID). If either PHOTO_FILE_ID or PHOTO_ID is not null, PHOTO_URI and PHOTO_THUMBNAIL_URI shall not be null (but not necessarily vice versa). Thus using PHOTO_URI is a more robust method of retrieving contact photos.
Type: TEXT
Constant Value: "photo_uri"
This is what the doc says, pskink is right, it returns a String. Also to add decodeStream returns null if it is not able to decode the image data and it would not generate any exception as well, so be carefull, check the values before using this.

Android: Get bitmap/drawable from HTTPS

I want to get an image from a server (HTTPS) and show it in an ImageView.
Images are from Facebook Events (example: https://fbcdn-photos-f-a.akamaihd.net/hphotos-ak-prn1/c17.0.50.50/1016204_538791999501573_1791760778_t.jpg )
Drawable.createFromStream((InputStream)new URL("https://fbcdn-photos-f-a.akamaihd.net/hphotos-ak-prn1/c17.0.50.50/1016204_538791999501573_1791760778_t.jpg").getContent(), "src");
throws NullPointer Exception
Or maybe is there any way to get the image via Facebook SDK?
In Facebook SDK I only know the ProfilePictureView (which may only be for profile pictures???)
Thanks so far!
Check <uses-permission android:name="android.permission.INTERNET" />
And I recommend look his:
Android - Loading Image Url and Displaying in ImageView
i recommend you to implement this into your project. It's the best solution.
https://github.com/thest1/LazyList
have You check internet permission?
<uses-permission android:name="android.permission.INTERNET" />
or user LazyLoading. so you can have cache stored in sdcard and next time you can get image quickly. so use example of this
http://www.androidhive.info/2012/07/android-loading-image-from-url-http/
or use another method
public static Bitmap getBitmapFromURL(String src) {
try {
Log.e("src",src);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap","returned");
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception",e.getMessage());
return null;
}
}
I'm such a dumbass :D
Everything of your answers were right!!!
I displayed the ImageView in a dialog.
I used the following to point to the ImageView
ImageView image = (ImageView)findViewById(R.id.imageView_event_picture);
but for sure this is NULL in a dialog!
It has to be
( final Dialog dialog = new Dialog(EventActivity.this); )
ImageView image = (ImageView)dialog.findViewById(R.id.imageView_event_picture);
I didn't mention that I'm running it out of a dialog - Sorry!!

BitmapFactory.decodeFileDescriptor returning null with a valid file descriptor

I've got a problem where BitmapFactory.decodeFileDescriptor is returning a null bitmap.
The file descriptor provided is coming from:
AssetManager.openFd("test.png").getFileDescriptor();
The paths are correct, the file exists,no exceptions are being thrown, and FileDescriptor.Valid() returns true.
Other code samples that I've looked at do not seem to have this problem.
This has me stumped, I don't know how I should proceed from here.
Any ideas?
I had the same problem. First,I put FileInputStream.getFD and BitmapFactory.decodeFileDescriptor in different threads,it returns null.
PhotoDecodeTask task = new PhotoDecodeTask();
task.execute(new FileInputStream(filePath).getFD());
private class PhotoDecodeTask extends AsyncTask<FileDescriptor,Integer,Bitmap>{
#Override
protected Bitmap doInBackground(FileDescriptor... params) {
...
return BitmapFactory.decodeFileDescriptor(params[0],null, opts);
}
}
I try to put them in the same thread,i works.But i don't know why.
PhotoDecodeTask task = new PhotoDecodeTask();
task.execute(filePath);
private class PhotoDecodeTask extends AsyncTask<String,Integer,Bitmap>{
#Override
protected Bitmap doInBackground(String... params) {
...
FileDescriptor fd = new FileInputStream(params[0]);
return BitmapFactory.decodeFileDescriptor(fd,null, opts);
}
}
I had the same problem. I had to change my code as follows:
InputStream imgFile = context.getAssets().open(imagePath);
BitmapFactory.decodeStream(imgFile);
So instead of using BitmapFactory.decodeFileDescriptor, I used decodeStream.
I have encountered such issue recently. After some search, finally this works for me:
FileDescriptor fd = AssetManager.openFd("test.png").createInputStream().getFD();
As a side note, this only works for my new phone (Android 5.0+), but still returns null from decodeFileDescriptor for old phone (Android 4.1.2).

Loading remote images

In Android, what is the simplest approach to the following:
Load an image from a remote server.
Display it in an ImageView.
Here's a method that I actually used in an application and I know it works:
try {
URL thumb_u = new URL("http://www.example.com/image.jpg");
Drawable thumb_d = Drawable.createFromStream(thumb_u.openStream(), "src");
myImageView.setImageDrawable(thumb_d);
}
catch (Exception e) {
// handle it
}
I have no idea what the second parameter to Drawable.createFromStream is, but passing "src" seems to work. If anyone knows, please shed some light, as the docs don't really say anything about it.
The easiest way so far is build a simple image retriver:
public Bitmap getRemoteImage(final URL aURL) {
try {
final URLConnection conn = aURL.openConnection();
conn.connect();
final BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
final Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
return bm;
} catch (IOException e) {}
return null;
}
Then, you just have to supply a URL to the method and it will returns a Bitmap. Then, you will just have to use the setImageBitmap method from ImageView to show the image.
Be careful with both of the answers here - they both run the chance of an OutOfMemoryException. Test your application by attempting to download a large image, such as a desktop wallpaper. To be clear, the offending lines are :
final Bitmap bm = BitmapFactory.decodeStream(bis);
and
Drawable thumb_d = Drawable.createFromStream(thumb_u.openStream(), "src");
Felix's answer will catch it in the catch{} statement, and you could do something about it there.
Here is how to work around the OutOfMemoryException error:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(is, null, options);
} catch (OutOfMemoryError ome) {
// TODO - return default image or put this in a loop,
// and continue increasing the inSampleSize until we don't
// run out of memory
}
And here are my comments on this in my code
/**
* Showing a full-resolution preview is a fast-track to an
* OutOfMemoryException. Therefore, we downsample the preview image. Android
* docs recommend using a power of 2 to downsample
*
* #see <a
* href="https://stackoverflow.com/questions/477572/android-strange-out-of-memory-issue/823966#823966">StackOverflow
* post discussing OutOfMemoryException</a>
* #see <a
* href="http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize">Android
* docs explaining BitmapFactory.Options#inSampleSize</a>
*
*/
Links from above comments:
Link 1
Link 2
You can also try this lib:
https://github.com/codingfingers/fastimage
When we had few projects with the same pattern, and the lib came up ;) so why not to share with others...
This is simple:
Add this dependency in you gradle script:
implementation 'com.squareup.picasso:picasso:2.71828'
*2.71828 is current version
Then do this for the image view:
Picasso.get().load(pictureURL).into(imageView);

Categories

Resources