I have a straight-forward wallpaper app which I've just finished coding. I've used the tutorial here ( http://developer.android.com/training/displaying-bitmaps/load-bitmap.html ) to load the image on the screen at a lower resolution, while I use the code below to set the wallpaper. imageId represents the currently selected drawable.
InputStream is = getResources().openRawResource(imageId);
Bitmap bitmap = BitmapFactory.decodeStream(is);
WallpaperManager myWallpaperManager = WallpaperManager
.getInstance(getApplicationContext());
try {
myWallpaperManager.setBitmap(bitmap);
Toast.makeText(MainActivity.this, "Teamwork! Wallpaper set.",
Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(
MainActivity.this,
"Damnit, clickers! Wallpaper wasn't set. Try killing and restarting the app?",
Toast.LENGTH_LONG).show();
}
However, I fear that the above code may cause phones of less memory to crash when it is called. Is there anything I can do to prevent this from happening, or is there nothing to fear?
EDIT:
I used this code to display the images in the app:
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res,
int resId, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public void setImage() {
switch (imageNum) {
case 1:
options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.drawable.aaaae,
options);
display.setImageBitmap(decodeSampledBitmapFromResource(
getResources(), R.drawable.aaaae, 300, 300));
imageId = R.drawable.aaaae;
break;
// Etc, etc.
}
}
The method setImage is called every time the "Next" button is pressed.
I guess you are not handling images properly
Here is the solution to handle bitmaps in android
(This approach can handle 25000px by 25000px images in a non-ui thread.)
First, you should calculate the sampleBitmapSize of the bitmap ( to load the lower version of the same bitmap )
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
Below is the util function to calculate InSampleSize ( an integer that defines the value (rating) of quality of a bitmap).
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
Log.i("ImageUtil", "InSampleSize: "+inSampleSize);
return inSampleSize;
}
Related
This question already has answers here:
Strange OutOfMemory issue while loading an image to a Bitmap object
(44 answers)
Closed 7 years ago.
I have image 3264х2448.
I load it in bitmap crudeImage = BitmapFactory.decodeFile(picturePath); then set to the ImageView imageCrop.setImageBitmap(crudeImage);
the problem is that it very big(3264х2448) and my library cropper
work very slowly with this image.
I want reduce the image to a smaller size. but to preserve the quality and proportion. how can this be done?
You should read Loading Large Bitmaps Efficiently.
Essentially, calculate the sample size first by
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
then load the image using the sample size:
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
I use this to resize my bitmap's. Maybe can be useful for you.
public Bitmap resizeBitmap(Bitmap bitmap, int newWidth, int newHeight)
{
//bitmap it's the bitmap you want to resize
//newWidth and newHeight are the with and height that you want to the new bitmap
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) /height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
I hope this help you.
If you read the tutorial here you'll see google gives you a very comprehensive guide on how to scale bitmaps without excessive memory usage.
In particular, these two methods (from the tutorial):
public static Bitmap decodeSampledBitmapFromResource(File file, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(file, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight){
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
Will accomplish your scaling whilst preserving aspect ratio.
The trick with these two methods is that the first decode operation is set to only decode the image's properties (dimensions and other information) as set by:
options.inJustDecodeBounds = true;
in which the new scale factor is calculated proportionally by the method calculateInSampleSize().
Then the image is decoded again, this time with
options.inJustDecodeBounds = false;
as well as the scale factor set, so the bitmap factory automatically scales whilst decoding, reducing the memory footprint.
Regarding what resolution the image needs to be decoded to, that really depends on your use-case. But, if the particular image does not need to be zoomed in later, you need no more than the device's physical screen size, which can be obtained via:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getRealSize(size);
in which object size will hold the device's screen size.
I am trying to implement the application which is doing lots of operations on an image. I have the problem with optimalization. The time of running my application is too long. I need to compress the images that I'm processing. I was trying with this tutorial:
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
It works well when I want to take the image from drawable folder. The problem is when I want to take the picture from camera or gallery. I have no idea what should I put in " R.id.myimage"
So the question is, how to use this line of code:
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
when I want to use the camera or gallery instead of drawable folder ?
To avoid OOM error, scale image using:
//For resource
image.setImageBitmap(decodeSampledBitmapFromResource("android.resource://com.my.package/drawable/image_name"));
//For file
image.setImageBitmap(decodeSampledBitmapFromResource(filepath));
Sampling function:
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 2;
if (height >= reqHeight || width >= reqWidth) {
inSampleSize *= 2;
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(String file,
int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(file, options);
}
Given a file path (without extension) I'd like to know if the image inside the file is a JPEG or a PNG.
How can I do it?
Try looking for the image headers, somewhat like this:
File file = /* (get your file) */;
byte[] data = new byte[2];
try {
new FileInputStream(file).read(data);
} catch (Exception e) {
// handle the error somehow!
}
if (data[0] == 0xFF && data[1] == 0xD8) {
// jpeg
} else if (data[0] == 0x89 && data[1] == 0x50) {
// png
} else {
// error?
}
JPEG headers will always be FFD8, and PNG headers are 89504E470D0A1E0A (for which we only need to look at the first two bytes to distinguish from JPEG).
You can find it like this:
step 1: You just get the image bounds only....
step 2: You can change your image with your corresponding size using the below method
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
in.mark(in.available());
BitmapFactory.decodeStream(in, null, options);
(or)
BitmapFactory.decodeFile(pathName);
(or)
BitmapFactory.decodeResource(MainActivity.this.getResources(), R.drawable.ic_launcher);
String name = options.outMimeType;
this below method is used to get the large bitmaps loading with efficiently
re-sizing the image with your required height and width
public static Bitmap decodeSampledBitmapFromResource(InputStream in,
int reqWidth, int reqHeight) throws IOException {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
in.mark(in.available());
BitmapFactory.decodeStream(in, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
in.reset();
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(in, null, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
Do you search for this? Why don't you have the extension?
"In Java 7 you can now just use
Files.probeContentType(path)"
-> source
but we are not sure if it's supported in android.
So why don't you just get the full path and extract the file extension with substring?
I'm trying to scale down a bitmap. In short, the image is originally from a ByteArray with a width of 4016. After I scale the image down with factory options, it still reports the image with a width of 4016.
Here are two clips of my code:
Bitmap myBitmap = null;
#Override
protected byte[] doInBackground(Object... params) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
if (options.outHeight > options.outWidth) {
options.inSampleSize = calculateInSampleSize(options, 640, 960);
} else {
options.inSampleSize = calculateInSampleSize(options, 960, 640);
}
options.inJustDecodeBounds = false;
//myImageByteArray is 4016 wide
myBitmap = BitmapFactory.decodeByteArray(myImageByteArray, 0, myImageByteArray.length, options);
//This log statement outputs 4016!!! Shouldn't it be smaller since I just decoded the byteArray with options?
Log.d("bitmap", myBitmap.getWidth()+"");
}
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to
// the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
Update:
Here are two clips of my code:
Bitmap myBitmap = null;
#Override
protected byte[] doInBackground(Object... params) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
//myImageByteArray is 4016 wide
myBitmap = BitmapFactory.decodeByteArray(myImageByteArray, 0, myImageByteArray.length, options);
if (options.outHeight > options.outWidth) {
options.inSampleSize = calculateInSampleSize(options, 640, 960);
} else {
options.inSampleSize = calculateInSampleSize(options, 960, 640);
}
options.inJustDecodeBounds = false;
//myImageByteArray is 4016 wide
myBitmap = BitmapFactory.decodeByteArray(myImageByteArray, 0, myImageByteArray.length, options);
//This log statement outputs around 1000 now.
Log.d("bitmap", myBitmap.getWidth()+"");
}
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to
// the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
You need to call .decodeByteArray(..) twice! Once to attain the width and the height with .inJustDecodeBounds set to true and then again with .inSampleSize to get the actual scaled Bitmap, options.outHeight and options.outWidth in your code are probably zero.
call BitmapFactory.decodeByteArray(myImageByteArray, 0, myImageByteArray.length, options); before checking outHeight and outWidth.
Edit
Take a look at this example from Google's Android Dev site:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
Notice that options.outHeight is used after calling decodeResources(...). This you have to fix in your code.
you didn't fill the bitmapOptions with anything that will set its "outHeight" and "outWidth".
you should check out the bitmap tutorials of google:
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
in order to decide what is the value to scale to, you need to know the size of the image compared to the destination size. that's why you need to do decoding twice.
btw, there is another way to downsample images, as i've shown here.
I am trying rotate taken image in onActivityResult() from camera Intent, but I am getting Out of memory errors occasionally.
How can I optimize this code?
http://pastebin.com/ieaHS8qB
bmp = BitmapFactory.decodeStream(new FileInputStream(f), null, null);
correctBmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(),
bmp.getHeight(), mat, true);
I was trying to add bmp.recycle() and correctBmp.recycle() after these lines, but it didn't help.
if you develope your application api level 10+ you can add your manifest this
android:largeHeap="true" //add this entity.
like
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen" >
or try this (Create Class)
public Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
thanks to that code you can also resize your bitmap.
try to add below code before decodestream and pass option as a parameter.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 5;
options.inPurgeable = true;
options.inInputShareable = true;
bmp = BitmapFactory.decodeStream(new FileInputStream(f),null, options);