I am downloading images from web URL and showing on my android application but I am not able to resize my image according to my requirements.
private Bitmap decodeFile(File f) {
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
//Find the correct scale value. It should be the power of 2.
// Set width/height of recreated image
final int REQUIRED_SIZE = 285;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 1;
height_tmp /= 1;
scale *= 2;
}
//decode with current scale values
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
now can any one tell me how can i resize my images to 250*250 px
also thanx in advance
Try and use Picasso library - http://square.github.io/picasso/.
It is fairly easy to use and integrate, and has a resize method doing exactly this.
Picasso.with(context).load(url).resize(250, 250).centerCrop().into(imageView);
you basically put instead of 'url' your url.
Related
In my app user can take picture from camera intent , then I save this image as full size image
not thumbnail. Then what I want to do is use this saved image to compress it and send it over to server.
The image size from camera intent is around 7-8 MB and resolution of 5664x4248.
The requirements is to achieve is image of same size and quality of whatsapp which is 40-80KB
I tried different solution but I couldn't achieve the same good quality and size.
For this I used id.zelory:compressor:2.1.1 library
Any Idea?
Here I call this method after saving the image to resize it
private File customCompressImage (File imgFile) {
String destinationDirectoryPath= Environment.getExternalStorageDirectory().getPath() + "/Pictures/";
try {
return new CustomCompressor(context)
.setMaxWidth(612)
.setMaxHeight(816)
.setQuality(80)
.setCompressFormat(Bitmap.CompressFormat.JPEG)
.setDestinationDirectoryPath(destinationDirectoryPath)
.compressToFile(imgFile);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
CompressImage
static File compressImage(File imageFile, int reqWidth, int reqHeight, Bitmap.CompressFormat compressFormat, int quality, String destinationPath) throws IOException {
FileOutputStream fileOutputStream = null;
File file = new File(destinationPath).getParentFile();
if (!file.exists()) {
file.mkdirs();
}
try {
fileOutputStream = new FileOutputStream(destinationPath);
// write the compressed bitmap at the destination specified by destinationPath.
decodeSampledBitmapFromFile(imageFile, reqWidth, reqHeight).compress(compressFormat, quality, fileOutputStream);
} finally {
if (fileOutputStream != null) {
fileOutputStream.flush();
fileOutputStream.close();
}
}
return new File(destinationPath);
}
static Bitmap decodeSampledBitmapFromFile(File imageFile, int reqWidth, int reqHeight) throws IOException {
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap scaledBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options);
//check the rotation of the image and display it properly
ExifInterface exif;
exif = new ExifInterface(imageFile.getAbsolutePath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
} else if (orientation == 3) {
matrix.postRotate(180);
} else if (orientation == 8) {
matrix.postRotate(270);
}
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
return scaledBitmap;
}
private 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;
}
I tried passing different max width and height and quality and I never achived both small size and good quality
You can try this piece of code.
public static Bitmap getCompressed( Bitmap imageBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
return imageBitmap;
}
// 100 is quality,
change it according to your need
#End User shouldn't it be like this instead (that's at least what I get from reading the documentation):
public static Bitmap getCompressed(Bitmap imageBitmap) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
if (!imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out))
throw new IllegalStateException("Unable to compress image");
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
return BitmapFactory.decodeStream(in);
}
I Need to compress the image size after a taken a photo. I want to decrease the size to a maximum of 400K.
So, the average image size after taken the photo is about 3.3MB. I need to compress it to 400K.
What is the best option for this ?
I have tried :
Bitmap original = BitmapFactory.decodeStream(getAssets().open("1024x768.jpg"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.compress(Bitmap.CompressFormat.PNG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
.
The code below allow me to reduce the size by way of width and height, but not is storage space.
Bitmap bitmap = Bitmap.createScaledBitmap(capturedImage, width, height, true);
i find this sample from https://stackoverflow.com/a/823966/556337, But he does not explain how to make a image of a maxim size of XXX.MB. There is there a way to implement my issue. ?
// Decodes image and scales it to reduce memory consumption
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=70;
// 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;
}
This question already has answers here:
Resize a large bitmap file to scaled output file on Android
(21 answers)
Closed 7 years ago.
I have String like this
String path = "storage/sdcard0/Pictures/location/img.jpg";
that string is location for file img.jpg. How can i scale/resize that image.
thanks..
/*
* Resizing image size
*/
public static Bitmap decodeFile(String filePath, int WIDTH, int HIGHT) {
try {
File f = new File(filePath);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = WIDTH;
final int REQUIRED_HIGHT = HIGHT;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HIGHT)
scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
Bitmap image = decodeFile(_filePaths.get(position), imageWidth, imageHeight);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
imageWidth));
imageView.setImageBitmap(image);
I'm trying to display an image having it's absolute path. I came upon this code on stackoverflow which should theoretically work, however I get error Bitmap too big to be uploaded into a texture on most images so I'm looking for another way to do it. Surprisingly there aren't any examples apart from this one on how to do it.
This is what I am trying:
Bitmap myBitmap = BitmapFactory.decodeFile(imagePath);
ImageView image = new ImageView(context);
image.setImageBitmap(myBitmap);
layout.addView(image);
By the way the images I'm working with have been taken with the default camera app so they don't have any uncommon format or size (and can be seen with no problem on the gallery app). How can I add them to my layout?
Just try to resize your image first by using below code and then set it into the ImageView:
public static Drawable GetDrawable(String newFileName)
{
File f;
BitmapFactory.Options o2;
Bitmap drawImage = null;
Drawable d = null;
try
{
f = new File(newFileName);
//decodes image and scales it to reduce memory consumption
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
o.inTempStorage = new byte[16 * 1024];
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
//The new size we want to scale to
final int REQUIRED_SIZE = 150;
//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
o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
drawImage = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
//Bitmap bmp = pictureDrawableToBitmap((PictureDrawable) drawable);
d = new BitmapDrawable(drawImage);
//drawImage.recycle();
//new BitmapWorkerTask
}
catch (FileNotFoundException e)
{
}
return d;
}
Use the above method as below:
imageView.setImageBitmap(myBitmap);
You might want to use a smaller sample size (inSampleSize) that fits the heap
First, create a bitmap that fits the heap, possibly slightly larger than the one you require
BitmapFactory.Options bounds = new BitmapFactory.Options();
this.bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, bounds);
if (bounds.outWidth == -1) { // TODO: Error }
int width = bounds.outWidth;
int height = bounds.outHeight;
boolean withinBounds = width <= maxWidth && height <= maxHeight;
if (!withinBounds) {
int newWidth = calculateNewWidth(int width, int height);
float sampleSizeF = (float) width / (float) newWidth;
int sampleSize = Math.round(sampleSizeF);
BitmapFactory.Options resample = new BitmapFactory.Options();
resample.inSampleSize = sampleSize;
bitmap = BitmapFactory.decodeFile(filePath, resample);
}
The second step is to call Bitmap.createScaledBitmap() to create a new bitmap to the exact resolution you require.
Make sure you clean up after the temporary bitmap to reclaim its memory. (Either let the variable go out of scope and let the GC deal with it, or call .recycle() on it if you are loading lots of images and are running tight on memory.)
I'm using ImageLoader in one of ma listview to display images from URL. While scrolling the list, app didn't response. I checked logcat and got this log report http://pastebin.com/Zfsk7r9X. In this log, "Clamp target GC heap from 55.234MB to 48.00MB" is shown. How can I avoid this memory issue. I've done System.GC() in ImageLoader class.
decodeFile() which i used is shown below
// decodes image and scales it to reduce memory consumption
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);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
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;
}
The message "Clamp target GC heap" is by logged by the VM when it gets desperate, a heap allocation fails, and the heap is returned to a previous ideal limit after the attempt. From documentation of setIdealFootprint in HeapSource.cpp:
/*
* Sets the maximum number of bytes that the heap source is allowed
* to allocate from the system. Clamps to the appropriate maximum
* value.
*/