Display big image from SD card in Android - android

In Android, how do you display an image (of any size) from the SD card, without getting an out of memory error?
Is it necessary to put the image in the Media Store first?
A pseudo-code example would be greatly appreciated. Extra points if the displayed image is as big as the memory level of the device allows.

Edit: this question has actually been already answered at Strange out of memory issue while loading an image to a Bitmap object (the two highest voted answers). It does also use the inSampleSize option, but with a small method to automatically get the appropriate value.
My original answer:
The inSampleSize of the BitmapFactory.Options class can solve your issue (http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize). It works by making a bitmap with the resulting width and height 1/inSampleSize than the original, thus reducing memory consumption (by inSampleSize^2?). You should read the doc before using it.
Example:
BitmapFactory.Options options = new BitmapFactory.Options();
// will results in a much smaller image than the original
options.inSampleSize = 8;
// don't ever use a path to /sdcard like this, but I'm sure you have a sane way to do that
// in this case nebulae.jpg is a 19MB 8000x3874px image
final Bitmap b = BitmapFactory.decodeFile("/sdcard/nebulae.jpg", options);
final ImageView iv = (ImageView)findViewById(R.id.image_id);
iv.setImageBitmap(b);
Log.d("ExampleImage", "decoded bitmap dimensions:" + b.getWidth() + "x" + b.getHeight()); // 1000x485
However here it will only work for images up to, I guess, inSampleSize^2 times the size of the allowed memory and will reduce the quality of small images.
The trick would be to find the appropriate inSampleSize.

I'm displaying any sized images using code:
ImageView imageView=new ImageView(this);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setAdjustViewBounds(true);
FileInputStream fis=new FileInputStream(file);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=2; //try to decrease decoded image
options.inPurgeable=true; //if necessary purge pixels into disk
options.inScaled=true; //scale down image to actual device density
Bitmap bm=BitmapFactory.decodeStream(is, null, options);
imageView.setImageBitmap(bm);
fis.close();

For example:
yourImgView.setImageBitmap(BitmapFactory.decodeFile("/sdcard/1.jpg"));

http://www.developer.com/ws/other/article.php/3748281/Working-with-Images-in-Googles-Android.htm covers all you'll ever need to know on the subject of images, including getting them from an SD card. You'll notice the code to do so there, copied below:
try {
FileOutputStream fos = super.openFileOutput("output.jpg",
MODE_WORLD_READABLE);
mBitmap.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
} catch (Exception e) {
Log.e("MyLog", e.toString());
}

Related

Reduce Bitmap size

So, I'm updating an old e-book reader. The problem I'm facing is the size of the bitmaps (the pages). The way it works is: the app downloads a file, extract it, decode it with our DRM then I can access all pages. The thing is, each page its a 35mb bitmap.
I need to reduce this by a lot. I can't convert the file to any other format.
I tried this:
byte[] rawBytes = intToByteArray(b.getByteCount());
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bit = BitmapFactory.decodeByteArray(rawBytes, 0,rawBytes.length, options);
But the Bitmap keeps returning null, and for what I gathered its when the Bitmap facorty can't decode the bitmap.
So, there is any other way to reduce the impact of this big bitmaps ?

How to speed up loading images as small previews?

I have 3 or 4 image paths that I use to load an image so I set it to an imageview. Why does it take long? Or better asking is there a way to make it faster? At the end of the day I am loading to fit an imageview of less than 60 dp hight and width
Uri mainImgeUri = Uri.parse(imagePath);
InputStream imageStream;
try {
imageStream = mActiviy.getContentResolver().openInputStream(mainImgeUri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream, null, options);
mainImageIV.setImageBitmap(yourSelectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
USE CASE:
What happens is that a user will add 5 images (and he get to choose them from Gallery which is mostly taken by phone camera). He hit save and my app stores the path to them in an sqlite database. Then when the user opens the app again to see them, my app query the db to get the paths to all the images and executes the code above x number of times so all the image views are loaded with the intended images
Take a look at http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
It explains how to calculate the correct inSampleSize based on the required dimensions of the output image. It also explains how to reference large bitmaps without having to load all their pixel data into memory.
The idea is that you resample bigger images and only load the smaller ones into memory making the whole process much more efficient. The example code is accessing a bitmap from resources, but this can easily be modified for your needs.
The important things to look out for in the example are inJustDecodeBounds and calculateInSampleSize.

Unable to retrieve the image from SDCard

Drawable image = Drawable.createFromPath(newImagepath);
defective_image.setBackgroundDrawable(image);
The image is stored in the newImagePath variable which is a String. The above throws an outOfMemory Exception.
I also tried retrieving the image into a Bitmap object.
Bitmap bitmapImg= BitmapFactory.decodeFile(newImagepath);
In the above case the bitmapImg is Null. (Without any exception)
However if it is retrieved as a file, it's successful. This doesn't serve my purpose because I want this image to be the background of a RelativeLayout.
File imageFile = new File(newImagepath);
String imgPath = imageFile.getAbsolutePath();
The imgPath is the same as the newImagePath, concluding the path is not wrong. I also verified the image's existence in the SDCard.
This image was captured from the device's camera. This code is working on the emulator successfully. When debugged on the device the above said faults were noticed.
I also tried:-
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
It seems to be a memory issue. So I suggest to decode bitmap size with the option
options.inJustDecodeBounds = true;
then getting the size of this bitmap by looking at fields (don't try to use bitmap : it will be null) :
options.outWidth;
options.outHeight;
Then creating a scaled bitmap (depending on the screen dimension). To do this, you can look at
BitmapFactory.Options.inSampleSize
I would rather use a BitmapFactory to decode the Image from the file-path:
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
jpgView.setImageDrawable(bitmap);

Large bitmaps not loading efficiently from sdcard in Android

By following this link, I have written the following code to show a large image bitmap from sdcard.
try {
InputStream lStreamToImage = context.getContentResolver().openInputStream(Uri.parse(imagePath));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(lStreamToImage, null, options);
options.inSampleSize = 8; //Decrease the size of decoded image
options.inPreferredConfig = Bitmap.Config.ARGB_4444;
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeStream(lStreamToImage, null, options);
} catch(Exception e){}
image.setImageBitmap(bitmap);
But it is not returning the bitmap(I mean it returns null). In logcat it is showing the below message repeatedly
08-02 17:21:04.389: D/skia(19359): --- SkImageDecoder::Factory returned null
If I will comment the options.inJustDecodeBounds line and rerun it, it works fine but slowly. The developer guide link I provided above says to use inJustDecodeBounds to load bitmaps efficiently.
Please tell me where I am doing wrong.
inJustDecodeBounds does not load bitmaps. That's the point of it. It loads the dimensions of the bitmap without loading the actual bitmap so you can do any pre-processing or checking on the bitmap before you actually load it. This is helpful is you, say, were having memory issues and you needed to check if loading a bitmap would crash you program.
The reason your bitmap might be loading slowly is because it's probably very large and SD cards are very slow.
EDIT:
From the documentation:
If set to true, the decoder will return null (no bitmap), but the out... fields will still be set, allowing the caller to query the bitmap without having to allocate the memory for its pixels.
Edit 2:
Looking at your code with the example provided by Google, it looks like you are doing relatively the same thing. The reason it's returning null is possibly your InputStream has been modified in the first decoding and thus not starting at the beginning of the bitmap's memory address (they use a resource ID rather than InputStream.
From the code you supplied here, here's what I've figured. You are ALWAYS setting a sample size to 8 regardless of what the first decoding gives you. The reason Google decodes the first time is to figure out what the actual size of the bitmap is versus what they want. They determine that the bitmap is ZxZ dimensions and they want YxY dimensions, so they calculate the samplesize that they should use from the second decoding. You are not doing this. You are simply retrieving the dimensions of the bitmap and not using them. THEN, you set the sample size to a hard-coded 8, swapping it to a hard-coded ARGB_4444 bitmap, then decoding the full bitmap in to memory. In other words, these three lines are not being used:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(lStreamToImage, null, options);
Setting inJustDecodeBounds merely gives you the bitmap's dimensions without putting the bitmap in to memory. It doesn't make it more efficient. It's meant to allow you to load bitmaps in a smaller memory space if they are too big because you can pre-decide what size it should be without decoding the whole thing).
The reason decoding the bitmap is slow might merely be a CPU thing. Depending on the size of your bitmap, you're loading the bitmap from an InputStream from the SDcard which is a slow operation in itself.

BItmap:out of memory error. how to get the original image size after compressing it in android

I have drawn an image manually on bitmap. But it has shown out of memory error.
I, then reduced the size of the image which shows me the compressed form of the image.
I need the original size of the image to be displayed which is then showing out of memory error. Kindly, help me out in resolving the issue.
I am enclosing the part of the code too.
ImageView iv1 = new ImageView(mcontext);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
BitmapFactory.decodeFile(pageViewManager.getPenToolPath() + pageViewManager.getCurrentPageIndex() + ".jpg");
bmp = BitmapFactory.decodeFile(pageViewManager.getPenToolPath() + pageViewManager.getCurrentPageIndex() + ".jpg", options);
iv1.setImageBitmap(bmp);
The memory space used by an uncompressed picture is easy to calculate: it's the number of pixels*the color depth, the number of pixels itself is height*width. For example, for an image of 1000*800 in 24 bits (3 bytes), the memory size will be:
1000*800*3=2400000 bytes or 2,4 Mb

Categories

Resources