I am loading images from URL and showing on the imageview at runtime.
My problem is sometimes my images are shown only HALF OF THE IMAGE and rest part of the image is shown white. Have read many posts on the net but none of them has helped me in the same..
Kindly provide a good solution for the same and the real cause.
Here is the code I have used to create the bitmap.
public static Bitmap getBitmapFromCard(String path, int reqWidth,
int reqHeight) {
try {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
} catch (OutOfMemoryError e) {
System.gc();
System.gc();
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = 3;
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
}
Calculation - InSampleSize
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 heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
Screenshot attached.
Related
I'm scaling down some bitmaps and getting low quality results.The result image looks different than original image.. I have used following code to scale down image,
Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap ib=BitmapFactory.decodeResource(getResources(), R.drawable.card,options);
Bitmap mm=Bitmap.createScaledBitmap(ib,ib.getWidth()/5,ib.getHeight()/5, true);
AND
BitmapFactory.Options m_bmpFactoryOptions = new BitmapFactory.Options();
m_bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap m_bitmap = BitmapFactory.decodeFile(p_file, m_bmpFactoryOptions);
int m_heightRatio =
(int) Math.ceil(m_bmpFactoryOptions.outHeight / (float) p_height);
int m_widthRatio =
(int) Math.ceil(m_bmpFactoryOptions.outWidth / (float) p_width);
if (m_heightRatio > 1 || m_widthRatio > 1)
{
if (m_heightRatio > m_widthRatio)
{
m_bmpFactoryOptions.inSampleSize = m_heightRatio;
}
else
{
m_bmpFactoryOptions.inSampleSize = m_widthRatio;
}
}
m_bmpFactoryOptions.inJustDecodeBounds = false;
m_bitmap = BitmapFactory.decodeFile(p_file, m_bmpFactoryOptions);
*Please help If there are any filters like lanczos,catrom to improve image quality after scale down *
Use this method
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;
}
Replace options.inScaled = false; with
options.inSampleSize =2
I am displaying an image in full screen mode,but whenever going to display large image then nothing display in the image view. Below code try to resize bitmap but got same result blank imageview.
public static Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// RECREATE THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
matrix, false);
return resizedBitmap;
}
You solve your problem from two mehtods
Method 1
call this method(function)
public Bitmap decodeImage(int resourceId) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), resourceId, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 100; // you are free to modify size as your requirement
// 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.decodeResource(getResources(), resourceId, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
add this before your adapter
picture.setImageBitmap((decodeImage(item.drawableId));
instead of
picture.setImageResource(item.drawableId);
Mehtod 2
You need to adjust your image size. The better way is to decode the image to a bitmap, and set the bitmap to the ImageView. For example:
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), item.drawableId, opts);
picture.setImageBitmap (bitmap);
I had the same problem. Got is solved through the following code.
Provide the filepath, desired width and desired height to the method. For more reference see here
public static Bitmap decodeScaledBitmapFromSdCard(String filePath, int reqWidth,
int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, 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;
}
Probably the image size is too large that the system cannot allocate enough memory to load it.
you can try loading your image after scaling it it with BitmapFactory.Options sampleSize
check this link for more info
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
may be this will work for you
public static Bitmap decodeSampledBitmapFromResource(String pathName,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(pathName, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(pathName, 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;
}
You solve your problem in Fragment
Add method in adapter
public Bitmap decodeImage(int gridViewImageId) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeResource(mContext.getResources(), gridViewImageId, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 100; // you are free to modify size as your requirement
// 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.decodeResource(mContext.getResources(), gridViewImageId, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
and add this line
imageViewAndroid.setImageBitmap(decodeImage(gridViewImageId[i]));
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%.
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
final int height = options.outHeight;
final int width = options.outWidth;
path is the image file path which is proper.
The problem is options.outHeight and options.outWidth are 0 when the image is captured in Landscape mode with AutoRotate on. If I turn off AutoRotate, it works fine. Since its width and height are 0 I was getting a null Bitmap at the end.
Complete Code:
Bitmap photo = decodeSampledBitmapFromFile(filePath, DESIRED_WIDTH,
DESIRED_HEIGHT);
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth,
int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
int inSampleSize = 1;
if (height > reqHeight) {
inSampleSize = Math.round((float) height / (float) reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth) {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
I had the same issue, I fixed it by changing :
BitmapFactory.decodeFile(path, options);
to:
try {
InputStream in = getContentResolver().openInputStream(
Uri.parse(path));
BitmapFactory.decodeStream(in, null, options);
} catch (FileNotFoundException e) {
// do something
}
After that change, the width and height were correctly set.
I want variable background to GridView and I run my app on a 800*480 resolution device.
I am able to add variable background, but after some time I am getting OutOfMemoryError.
I need to add that bitmap for each shelf and shelf has 800*200 dimensions.
I have tried bitmap.recycle()
and also
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
and also
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;
}
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;
}
But still I am unable to get rid of that OutOfMemory error. Please help me.
Its Working Fine For Me.
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;
options.inDither=false; //Disable Dithering mode
options.inPurgeable=true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared
options.inInputShareable=true;
options.inTempStorage=new byte[32 * 1024];
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;
}