I'm facing this problem since a month with no solution:
I need to convert a file into a bitmap and rescaling it.
I'm using the following method, taken from android guide: Loading Large Bitmaps Efficiently
public Bitmap decodeSampledBitmapFromFile(String path, int reqSize) {
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inMutable = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
double ratio = (double) options.outHeight / options.outWidth;
boolean portrait = true;
if (ratio < 1) {
portrait = false;
}
double floatSampleSize = options.outHeight / (double)reqSize;
options.inSampleSize = (int) Math.floor(floatSampleSize);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap resultBitmap = BitmapFactory.decodeFile(path, options);
if(floatSampleSize % options.inSampleSize != 0){
if(portrait) {
resultBitmap = Bitmap.createScaledBitmap(resultBitmap, (int)(reqSize/ratio), reqSize, true);
} else {
resultBitmap = Bitmap.createScaledBitmap(resultBitmap, reqSize, (int)(ratio*reqSize), true);
}
}
return resultBitmap;
}
I've got the same NullPointerException but i can't reproduce it:
NullPointerException (#Utilities:decodeSampledBitmapFromFile:397) {AsyncTask #2}
NullPointerException (#Utilities:decodeSampledBitmapFromFile:399) {AsyncTask #3}
lines 397 and 399 are:
resultBitmap = Bitmap.createScaledBitmap(resultBitmap, (int)(reqSize/ratio), reqSize, true);
resultBitmap = Bitmap.createScaledBitmap(resultBitmap, reqSize, (int)(ratio*reqSize), true);
in this device models:
ST21a
U9500
M7
U8950-1
GT-I9305
Someone can help me to solve this?
is BitmapFactory.decodeFile returns null?
thank you so much
Try this hope works for you
public Bitmap decodeFile(String path, int reqSize) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = reqSize;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
Related
I try show a bitmap from the gallery. this is my URL
file:///storage/emulated/0/DCIM/Camera/IMG_20161103_180603.jpg
I know how to get bitmap using onActivityResult(), but I don't know how to get a bitmap
this is my source
final ImageView imageView=(ImageView)findViewById(R.id.imageView);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
final Bitmap bitmap = BitmapFactory.decodeFile("file:///storage/emulated/0/DCIM/Camera/IMG_20161103_180603.jpg", options);
runOnUiThread(new Runnable() {
#Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
How can I solve my problem?
please refer below code
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
//Get our saved file into a bitmap object:
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "DCIM"+ File.separator + "Camera "+File.separator + "IMG_20161103_180603.jpg");
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
imageView.setImageBitmap(bitmap);
I had the same problem caused by large image size which couldn't be processed at run time. Solved it using this.
// Decodes image and scales it to reduce memory consumption
public static Bitmap decodeFile(File f) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 200;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE &&
o.outHeight / scale / 2 >= REQUIRED_SIZE) {
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
where File f will be retrieved using https://stackoverflow.com/a/20559418/3758972
just put the size of thumbnail you want (typically the size of your imageview) in REQUIRED_SIZE and you are done. It will give you a scaled image which you can set to your imageview.
decodeFile( "file:///storage/emulated/0/DCIM/Camera/IMG_20161103_180603.jpg
Change to:
decodeFile( "/storage/emulated/0/DCIM/Camera/IMG_20161103_180603.jpg
I am developing an app in which i want to reduce the size of my image.For example if size is 1MB then i want it to get reduce into kb.
But resolution should not get changed.
Can anyone help in this?
I tried this code but its not working
public static Bitmap resizeBitMapImage1(String filePath, int targetWidth, int targetHeight) {
Bitmap bitMapImage = null;
try {
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
double sampleSize = 0;
Boolean scaleByHeight = Math.abs(options.outHeight - targetHeight) >= Math.abs(options.outWidth
- targetWidth);
if (options.outHeight * options.outWidth * 2 >= 1638) {
sampleSize = scaleByHeight ? options.outHeight / targetHeight : options.outWidth / targetWidth;
sampleSize = (int) Math.pow(2d, Math.floor(Math.log(sampleSize) / Math.log(2d)));
}
options.inJustDecodeBounds = false;
options.inTempStorage = new byte[128];
while (true) {
try {
options.inSampleSize = (int) sampleSize;
bitMapImage = BitmapFactory.decodeFile(filePath, options);
break;
} catch (Exception ex) {
try {
sampleSize = sampleSize * 2;
} catch (Exception ex1) {
}
}
}
} catch (Exception ex) {
}
return bitMapImage;
}
Using this code it reduces the resolution but not much size of the image.
I also tried
public static Bitmap reduceImgSizeToHundredKB(Bitmap bitmap) {
Bitmap scaled = bitmap;
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return scaled;
}
If you don't want to resize your image then your only option is to compress it.
Here is an example on how to do that:
byte[] data = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
In my thought, In most cases, we can't do that. Because it related to resolution of the image and the color range of the image.
so, If we have a large image with a lot of colors, then reduce the size of the image will induce to reduce resolution of it.
There are two aproches: lossy (where you'll lose quality of the image) and lossless.
The answer provided by rickman is lossy so it will work well but reduce the quality of the image - it works particularly well for pictures taken with a camera.
The lossless approach is using PNG, which consists of using Bitmap.CompressFormat.PNG as argument to the compress method.
A not as well known but very efficient format is WebP. It's also available as an argument to the compress method (Bitmap.CompressFormat.PNG). I'd suggest testing with WebP, specially considering it supports both lossy and lossless compression.
Use this method if you are decoding from path
public Bitmap decodeSampledBitmapFromPath(String path, int reqWidth,
int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bmp = BitmapFactory.decodeFile(path, options);
return bmp;
}
}
public int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
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;
}
Use this if you are decoding from resources
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 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) {
// 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;
}
If you want to reduce the file size of the image without losing a great ammount of quality you can do this:
First you need to flatten the image, then save it for web (ctrl+alt+shift+s)
Then select the preset PNG-8 128 Dithered.
You can now customize this preset by setting the colors to "256", then select "selective" under the PNG-8, under "selective" change dither to "diffusion", deselect the "interlaced" option and make shure that the web snap option is set to 0%.
I want to load an image from gallery as a bitmap an show it on a custom view(not an imageview).Here is the code for loading bitmap.
private Bitmap loadBitmap(String filePath, int orientation, int width, int height) {
Bitmap bitmap = null;
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
int scale = 1;
if ((options.outWidth > width) || (options.outHeight > height)) {
if (options.outWidth < options.outHeight) {
scale = Math.round((float) options.outWidth / width);
} else {
scale = Math.round((float) options.outHeight/ height);
}
}
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(filePath, options);
if (orientation > 0) {
// rotate the image w.r.to orientation
Matrix matrix = new Matrix();
matrix.postRotate(orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0,width,height, matrix, true);
}
} catch (Exception e) {
bitmap = null;
}
return bitmap;
}
Now my problem is that the canvas does not show the bitmap completely.Only a part o it.How can i adjust the image (without losing its clarity,not stretching) with screen size?
Thanks in Advance
May be you can try the ScaleType options and use the one whihc suits you the best. Follow the link below for details:
http://developer.android.com/reference/android/widget/ImageView.ScaleType.html
I am doing a "Image Editor" like application. I used default camera intent to capture the image. I used to parse the URI and set that to the image view like the following:
imgCaptured.setImageURI(Uri.parse(filePath));
If I use this raw image, occasionally it is throwing me out of memory error! So I decided to decode the image using the following:
"Got from stackoverflow"
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
preview_bitmap = BitmapFactory.decodeStream(is, null, options);
private Bitmap decodeFile(File f) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 95;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE
&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
If I use the decoded image, the output is not in good quality. Some how it seems to be blur. I want a good clear image! After setting it into the ImageView. I need to drag and drop another views.
How can I achieve the above?
What is a good way to do this?
what is the reason to divide by 2 in the loop ?
try this
while (o.outWidth / scale >= REQUIRED_SIZE
&& o.outHeight / scale >= REQUIRED_SIZE)
Probably You also would like to scale the image to the view's size with this method
http://developer.android.com/reference/android/graphics/Bitmap.html#createScaledBitmap(android.graphics.Bitmap, int, int, boolean)
change options.inSampleSize = 8 to options.inSampleSize = 4.
The method which you had used is not complete, you have to add few Math functions to, too maintain the quality of the image.
private static Bitmap decodeFile(File f) {
Bitmap b = null;
final int IMAGE_MAX_SIZE = 100;
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int scale = 1;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
scale = (int) Math.pow(
2.0,
(int) Math.round(Math.log(IMAGE_MAX_SIZE
/ (double) Math.max(o.outHeight, o.outWidth))
/ Math.log(0.5)));
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
} catch (Exception e) {
Log.v("Exception in decodeFile() ", e.toString() + "");
}
return b;
}
Please let me know, if it worked for you...!!!!:)
i am displaying my images from assests/image folder ,
but this code is not working . this code display images from assets folder in gallery . i am using gallery prefine library or jar file.
please expert check it . thank u
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("image");
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
for(String filename : files) {
System.out.println("File name => "+filename);
InputStream in = null;
try {
ImageViewTouch imageView = new ImageViewTouch(Rahul.this);
imageView.setLayoutParams(new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
final Options options = new Options();
options.outHeight = (int) scaleHeight;
options.outWidth = (int) scaleWidth;
options.inScaled = true;
options.inPurgeable = true;
options.inSampleSize = 2;
in = assetManager.open("image/"+filename);
Bitmap bit=BitmapFactory.decodeStream(in);
imageView.setImageBitmap(bit);
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
gallery.setAdapter(arrayAdapter);
Hey please check my answer on the same issue: bitmap size exceeds Vm budget error android
And also always try to use maximum options while dealing with bitmaps like this:
final Options options = new Options();
options.outHeight = (int) scaleHeight; // new smaller height
options.outWidth = (int) scaleWidth; // new smaller width
options.inScaled = true;
options.inPurgeable = true;
// to scale the image to 1/8
options.inSampleSize = 8;
bitmap = BitmapFactory.decodeFile(imagePath, options);
This might solve your problem.
1) try to use bitmap.recycle(); to release memory before setting a new bitmap to your images
BitmapDrawable drawable = (BitmapDrawable) myImage.getDrawable();
Bitmap bitmap = drawable.getBitmap();
if (bitmap != null)
{
bitmap.recycle();
}
2) if your images are too large scale down them:
public static Bitmap decodeFile(File file, int requiredSize) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(file), null, o);
// The new size we want to scale to
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < requiredSize
|| height_tmp / 2 < requiredSize)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(file),
null, o2);
return bmp;
} catch (FileNotFoundException e) {
} finally {
}
return null;
}
Update
something like this:
for(int i=0; i<it.size();i++) {
ImageViewTouch imageView = new ImageViewTouch(GalleryTouchTestActivity.this);
imageView.setLayoutParams(new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
Options options = new Options();
options.inSampleSize = 2;
String photoURL = it.get(i);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
if (bitmap != null)
{
bitmap.recycle();
}
bitmap = BitmapFactory.decodeFile(photoURL);
imageView.setImageBitmap(bitmap);
arrayAdapter.add(imageView);
}