I'm writing an app that stores a String in an SQLite database, which represents the filepath of an image on the /sdcard/. I have this code in the onCreate() one of my activities:
final Intent receivedIntent = getIntent();
String imageStr = receivedIntent.getExtras().getString("picture");
ImageView imageView = (ImageView) findViewById(R.id.pPicture);
File file = new File (imageStr);
if (file.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(imageStr);
imageView.setImageBitmap(bitmap);
}
The code works when I'm first loading the activity, but when I switch between screen orientations, it crashes my application. Any ideas on what I can do to fix this? I'd like to bee able to continue switching between orientations, but I don't need to refresh each time.
Also, I'm somewhat new, so please try to keep your answers not too complicated if possible.
Note that the file does exist in all cases.
I think your app crashes because of OutOfMemoryException. Try recylcing the bitmap in onDestroy():
#Override
public void onDestroy() {
super.onDestroy();
ImageView imageView = (ImageView) findViewById(R.id.pPicture);
Drawable drawable = imageView.getDrawable();
imageView.setImageDrawable(null);
if (drawable instanceof BitmapDrawable) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
bitmap.recycle();
bitmap = null;
}
}
Related
I have some jpeg file stored into application private storage. I'm showing them in an ImageView and everything works properly.
But for some jpeg, with sizes similar to the others, BitmapFactory.decodeFile returns null.
This happens with all jpegs generated by Microsoft Paint: just by taking a jpeg that works well, loading into msPaint and saving it unmodified, to get a not working jpeg.
This is the code (the filepath and filename are properly set because it works for many files):
...
public class MainActivity extends ActionBarActivity {
...
private ImageView myImage;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myImage = (ImageView) findViewById(R.id.imageView1);
File f=new File(basedir, list.get(imageIndex).getFile());
Bitmap b = BitmapFactory.decodeFile(f.getPath());
if (b != null){
myImage.setImageBitmap(b);
} else {
myImage.setImageResource(R.drawable.default);
}
...
}
...
}
I've also tried FileInputStream, as suggested somewhere else but with the same result:
...
File f=new File(basedir, list.get(imageIndex).getFile());
FileInputStream fis = new FileInputStream(f);
Bitmap b = BitmapFactory.decodeStream(fis);
if (b != null){
myImage.setImageBitmap(b);
} else {
myImage.setImageResource(R.drawable.default);
}
...
Does BitmapFactory have any known limitation? Is there any way to check jpeg characteristics??
I have been trying with no avail to set my facebooks profile picture as a Linearlayout background in my application.
here are the two ways I tried to do this:
first way: got the uri from the profile picture and converted it to drawable
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
LinearLayout banner = (LinearLayout)findViewById(R.id.banner);
Profile profile = Profile.getCurrentProfile();
if(profile != null){
// profile_pic_id.setProfileId((profile.getId()));
Drawable d;
Uri uri = profile.getLinkUri();
//also tried profile.getProfilePictureUri(random_num,random_num)
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
d = Drawable.createFromStream(inputStream, uri.toString());
} catch (FileNotFoundException e) {
d = getResources().getDrawable(R.drawable.blue_material);
}
banner.setBackgroundDrawable(d);
}
}
now this always threw an exception so the Drawable i get is the blue_material one (the Drawable set in the catch block), so if anyone knows why its throwing an exception all the time I'd be grateful.
second way: converted the ProfilePictureView to ImageView and then used getDrawable() on the ImageView.
ProfilePictureView profilePictureFB=(ProfilePictureView)findViewById(R.id.pic);
profilePictureFB.setProfileId((profile.getId()));
ImageView fbImage = ( ( ImageView)profilePictureFB.getChildAt( 0));
banner.setBackgroundDrawable(fbImage.getDrawable());
now this resulted in having a background with the default picture facebook puts when someone has no profile pic.
AND whenever I use decodeStream an exception gets thrown.(example below)
URL img_url =new URL("https://graph.facebook.com/"+profile.getId()+"/picture?type=normal");
Bitmap bmp =BitmapFactory.decodeStream(img_url.openConnection().getInputStream());//bmp a bitmap
I didnt want to resort to asking this question on stackoverflow because I wanted to solve it myself, but I tried for so very long, so I had to get some help.
Thanks for anyone who answers :)
I solved it!!
i used imageLoader, and for some reason the url works with it, here is the code:
imageView = (ImageView) findViewById(R.id.pic);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageLoader = ImageLoader.getInstance();
Profile profile = Profile.getCurrentProfile();
if(profile != null){
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true).build();
imageLoader.displayImage("http://graph.facebook.com/" + profile.getId() + "/picture?width=400&height=400", imageView, options);
// banner.setBackgroundDrawable(imageView.getDrawable());
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
the method setScaleType stretches my imageview across all myLinearLayout.
for more information about the universal image loader visit this link:
https://github.com/nostra13/Android-Universal-Image-Loader
I m not sure but this what i used to do
img_url =new URL("https://graph.facebook.com/"+uname+"/picture?type=normal");
bmp =BitmapFactory.decodeStream(img_url.openConnection().getInputStream());//bmp a bitmap
linearlayout.setImageBitmap(bmp);//your linear layout
I am trying to take a Bitmap and display it in an ImageView.
ImageView iv = new ImageView(this);
Bitmap bMap = BitmapFactory.decodeFile("/res/drawable/" + imageFileName);
iv.setImageBitmap(bMap);
That's my code for it. I create an ImageView and a Bitmap. I want to display my Bitmap in my ImageView. But I always get these two errors on the iv.setImageBitmap(bMap); statment
Syntax error on token "bMap", VariableDeclaratorId expected after this token
Syntax error on token(s), misplaced construct(s)
Does anybody has an idea why this happens and what i have to change?
In OP's pastebin code I've found the following snippet:
String imageFileName =getIntent().getStringExtra("imageFileName");
//String bildquelle = "R.drawable." + imageFileName;
public class ImageChange extends Activity {
ImageView iv = new ImageView(this);
String bildquelle = "R.drawable." + imageFileName;
int id = getResources().getIdentifier(bildquelle, "drawable", getPackageName());
Bitmap bMap = BitmapFactory.decodeResource(getResources(), id);
//Bitmap bMap = BitmapFactory.decodeFile("/res/drawable/" + imageFileName);
iv.setImageBitmap(bMap);
}
There are a couple of problems with this including:
The code is not inside a method body.
The code is a Activity subclass.
The code improperly calls getResources().getIdentifier(...).
Instead of the above code I suggest MERGING the rest of activity with the following:
public class BildAnzeigen extends ActionBarActivity {
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bild_anzeigen);
iv = (ImageView) findViewById(R.id.my_image_view); // replace the id with the one from layout definition
handleIntent(getIntent());
}
private void handleIntent(Intent intent) {
String imageFileName = intent.getStringExtra("imageFileName");
int id = getResources().getIdentifier(imageFileName, "drawable", null);
Bitmap bMap = BitmapFactory.decodeResource(getResources(), id);
iv.setImageBitmap(bMap);
}
}
Note: This will not work if the images are not compiled within your apk. There's no way to add anything to drawables after building. It just doesn't work that way.
I want to create a dynamic image view where every image in my gallery will going to use bitmapfactory and not image drawable that binds in the image view. Is there some sites that has bitmapfactory tutorial for this? i believe that using bitmapfactory uses less memory that binding the image into image view? Is this right? I want also to minimize the risk of memory leaks thats why I want to use bitmapfactory. Please help. I cant find basic examples that teaches bitmapfactory.
Building Bitmap Objects
1) From a File
Use the adb tool with push option to copy test2.png onto the sdcard
This is the easiest way to load bitmaps from the sdcard. Simply pass the path to the image to BitmapFactory.decodeFile() and let the Android SDK do the rest.
public class TestImages extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.test_image);
Bitmap bMap = BitmapFactory.decodeFile("/sdcard/test2.png");
image.setImageBitmap(bMap);
}
}
All this code does is load the image test2.png that we previously copied to the sdcard. The BitmapFactory creates a bitmap object with this image and we use the ImageView.setImageBitmap() method to update the ImageView component.
2) From an Input stream
Use BitmapFactory.decodeStream() to convert a BufferedInputStream into a bitmap object.
public class TestImages extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.test_image);
FileInputStream in;
BufferedInputStream buf;
try {
in = new FileInputStream("/sdcard/test2.png");
buf = new BufferedInputStream(in);
Bitmap bMap = BitmapFactory.decodeStream(buf);
image.setImageBitmap(bMap);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
}
}
This code uses the basic Java FileInputStream and BufferedInputStream to create the input stream for BitmapFactory.decodeStream(). The file access code should be surrounded by a try/catch block to catch any exceptions thrown by FileInputStream or BufferedInputStream. Also when you're finished with the stream handles they should be closed.
3) From your Android project's resources
Use BitmapFactory.decodeResource(res, id) to get a bitmap from an Android resource.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.test_image);
Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
image.setImageBitmap(bMap);
}
I have saved a image in internal memory. For example I saved it as test.jpg. Now I want to show it in a imageview. I have tried this:
ImageView img = (ImageView)findViewById(R.id.imageView1);
try {
img.setImageDrawable(Drawable.createFromPath("test.jpg"));
} catch (Exception e) {
Log.e(e.toString());
}
And get the following message in LogCat:
SD Card is available for read and write truetrue
Any help or reference please?
public class AndroidBitmap extends Activity {
private final String imageInSD = "/sdcard/er.PNG";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);
ImageView myImageView = (ImageView)findViewById(R.id.imageview);
myImageView.setImageBitmap(bitmap);
}
}
or
final Bitmap bm = BitmapFactory.decodeStream( ..some image.. );
// The openfileOutput() method creates a file on the phone/internal storage in the context of your application
final FileOutputStream fos = openFileOutput("my_new_image.jpg", Context.MODE_PRIVATE); // Use the compress method on the BitMap object to write image to the OutputStream
bm.compress(CompressFormat.JPEG, 90, fos);
hope it works...
Take a look at the doc..
You don't need to "know" where the image is stored. You just need to hold on to what you saved it as, and then you can read it back again.
The question is... did you save the file there? Or are you confusing this with images that you have compiled into the application? If it's the latter, the documentation also talks about how to read those, they are not the same as files that you have written to the device, they're part of the app package.
Welcome to Stack! If you find answers useful don't forget to upvote them and mark them as "correct" if they solve your problems.
Cheers.