Android choose image from gallery showing memory error - android

I am working on a code sample where I have to choose an image from gallery the code is working but after selection of image from gallery I get OutOfMemoryError in my OnActivityResult
I am able to get small images but large images are creating problem.
Here is my code:
try{
Uri selectedImageUri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
bitmap = BitmapFactory.decodeFile(filePath);
_profileImage.setImageBitmap(bitmap);
_profileImage.setScaleType(ScaleType.FIT_XY);
Constant._addPhotoBitmap=bitmap;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap resizedbitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
resizedbitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte [] _byteArray = baos.toByteArray();
String base64 = Base64.encodeToString(_byteArray,Base64.DEFAULT);
Constant._addPhotoBase64 = base64;
}catch (OutOfMemoryError e) {
e.printStackTrace();
Constant.showAlertDialog(Constant.errorTitle,
"Image size is too large.Please upload small image.",
DriverProfileScreen.this, false);
} catch (Exception e) {
e.printStackTrace();
}

You are deirectly decoding the file based on its uri path..thats why it is throwing exception..before loading image set some options..this will reduce the memory for the image loading..Use this method for loading image whatever size you want..
/**
* returns the thumbnail image bitmap from the given url
*
* #param path
* #param thumbnailSize
* #return
*/
private Bitmap getThumbnailBitmap(final String path, final int thumbnailSize) {
Bitmap bitmap;
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, bounds);
if ((bounds.outWidth == -1) || (bounds.outHeight == -1)) {
bitmap = null;
}
int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight
: bounds.outWidth;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = originalSize / thumbnailSize;
bitmap = BitmapFactory.decodeFile(path, opts);
return bitmap;
}

In Android Developer document there is Topic called
Displaying Bitmaps Efficiently
So please go through it.
http://developer.android.com/training/displaying-bitmaps/index.html
Hope this will help you.

Generally android device heap size is only 16MB (varies from device/OS see post Heap Sizes), if you are loading the images and it crosses the size of 16MB , it will throw out of memory exception, instead of using the Bitmap for , loading images from SD card or from resources or even from network try to using getImageUri , loading bitmap require more memory , or you can set bitmap to null if your work done with that bitmap.
So,You need to downscale you image using below code:
public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
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_WIDTH=WIDTH;
final int REQUIRED_HIGHT=HIGHT;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
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;
}

Scale the bitmap first , then load it. It will solve the problem.
You can use the following method to do that.
private Bitmap getScaledBitmap(Uri uri){
Bitmap thumb = null ;
try {
ContentResolver cr = getContentResolver();
InputStream in = cr.openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize=8;
thumb = BitmapFactory.decodeStream(in,null,options);
} catch (FileNotFoundException e) {
Toast.makeText(PhotoTake.this , "File not found" , Toast.LENGTH_SHORT).show();
}
return thumb ;
}
Hope it helps.

try this code:
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.ActivityManager;
import android.content.ComponentCallbacks;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v4.util.LruCache;
import android.widget.ImageView;
public class UserImageLoaderWithCache implements ComponentCallbacks {
private KCLruCache cache;
public UserImageLoaderWithCache(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass() * 1024 * 1024;
cache = new KCLruCache(memoryClass);
}
public void display(String url, ImageView imageview, int defaultresource) {
imageview.setImageResource(defaultresource);
Bitmap image = cache.get(url);
if (image != null) {
imageview.setImageBitmap(image);
}
else {
new SetImageTask(imageview).execute(url);
}
}
private class KCLruCache extends LruCache<String, Bitmap> {
public KCLruCache(int maxSize) {
super(maxSize);
}
}
private class SetImageTask extends AsyncTask<String, Void, Integer> {
private ImageView imageview;
private Bitmap bmp;
public SetImageTask(ImageView imageview) {
this.imageview = imageview;
}
#Override
protected Integer doInBackground(String... params) {
String url = params[0];
try {
bmp = getBitmapFromURL(url);
if (bmp != null) {
cache.put(url, bmp);
} else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
return 0;
} catch (OutOfMemoryError o) {
o.printStackTrace();
return 0;
}
return 1;
}
#Override
protected void onPostExecute(Integer result) {
if (result == 1) {
imageview.setImageBitmap(bmp);
}
super.onPostExecute(result);
}
private Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}catch (OutOfMemoryError o) {
o.printStackTrace();
return null;
}
}
}
public void onLowMemory() {
}
/*public void onTrimMemory(int level) {
if (level >= TRIM_MEMORY_MODERATE) {
cache.evictAll();
}
else if (level >= TRIM_MEMORY_BACKGROUND) {
cache.trimToSize(cache.size() / 2);
}
}*/
public void onConfigurationChanged(Configuration arg0) {
// TODO Auto-generated method stub
}
}

I have used below code and used bitmap to store resized Image in local storage and It worked like charm
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap b = BitmapFactory.decodeFile(path, options);
here path is image Uri path in String

Related

What is the correct URI to send to handleSamplingAndRotationBitmap?

I have the common problem of display a picture in the correct rotation. My images are stored on a server. I call an image and display it in my app. Each image is rotated. So I found a correction with handleSamplingAndRotationBitmap.
public static Bitmap handleSamplingAndRotationBitmap(Context context, Uri selectedImage)
throws IOException {
int MAX_HEIGHT = 1024;
int MAX_WIDTH = 1024;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
InputStream imageStream = context.getContentResolver().openInputStream(selectedImage);
BitmapFactory.decodeStream(imageStream, null, options);
imageStream.close();
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
imageStream = context.getContentResolver().openInputStream(selectedImage);
Bitmap img = BitmapFactory.decodeStream(imageStream, null, options);
img = rotateImageIfRequired(img, selectedImage);
return img;
}
But it's impossible for me to send the correct Uri selectedImage.
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
final String myUrlStr = urldisplay;
URL url;
try {
url = new URL(myUrlStr);
uri = Uri.fromFile(new File(urldisplay));
uri2 = Uri.parse((urldisplay).toString());
mIcon = handleSamplingAndRotationBitmap(getContext(),uri2);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
I have the error
} catch (FileNotFoundException e) {
InputStream in = null;
try {
in = new URL(DataConstantes.lien_URLEtb + "Aucune_photo_etablissement.png").openStream();
} catch (IOException e1) {
flagError = true;
}
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
flagError=true;
}
java.io.FileNotFoundException:
/http:/$$$$$$$$$$/appli/android_connect/Etablissement/abordage.jpg (No
such file or directory)
Do you know how I can send the correct URI ?
Thanks

How to apply bitmap recycle in recycleView because of out of memory exception

I am working with an application and have about 10 Recycle view, when i move between fragments, app crash with out of memory.
I am using a lot of images in this app
I want to know how to apply bitmap recycle as it's the main reason of the exception
My recycle adapter is:
public void onBindViewHolder(MboViewHolder holder, int position) {
GameEvent gameEvent = ev.get(position);
holder.bindPhoto(holder,cnt,gameEvent.getEventImage());}
BindPhoto mwthod is:
public void bindPhoto(MboViewHolder mbo,Context cnt, String photoUrl) {
mbo.img.setTag(photoUrl);
Bitmap imgz = Tools.getPhoto(photoUrl, 0);
if (imgz != null) {
mbo.img.setImageBitmap(imgz);
Log.e("NoDwnLd","No");
} else {
Bitmap largeIcon = BitmapFactory.decodeResource(cnt.getResources(), R.drawable.ic_default);
mbo.img.setImageBitmap(largeIcon);
new DownloadBitmap(cnt,mbo.img,"2").execute(photoUrl);
}
My DownloadBitmap asynctask is:
public class DownloadBitmap extends AsyncTask<String, Void, Bitmap> {
private int flag=0;
private ImageView img;
private String type;
private HashMap<String, Bitmap> map= new HashMap<>();
private Context cnt;
private String url;
public DownloadBitmap(Context cnt, ImageView img, String type) {
this.cnt = cnt;
this.img=img;
this.type=type;
}
public DownloadBitmap(Context cnt, ImageView img, String type, HashMap<String, Bitmap> map) {
this.cnt = cnt;
this.img=img;
this.type=type;
this.map=map;
}
public DownloadBitmap(Context context) {
this.cnt=context;
this.flag=2;
}
#Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap=null;
if (cnt!=null){
boolean check = new CheckInternetConnection(cnt).haveNetworkConnection();
if (check) {
try {
url=params[0];
if (url==null || url.equals("")) return null;
InputStream in = new java.net.URL(url).openStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = Globals.inSampleSize;
bitmap = BitmapFactory.decodeStream(in,null,options);
return bitmap;
} catch (Exception e) {
Log.e("ImageDownload", "Download failed: " + e.getMessage());
}
}
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if(bitmap != null){
bitmap=Tools.resizeImage(bitmap,500,500);
//view.setImageViewBitmap(R.id.nt_img, bitmap);
if(type == "1") Tools.sendNotification(cnt, bitmap);
if(type == "2") {
if(img.getTag()!= null && img.getTag() == url){
// keep all images stored on memory for fast retrieval
// map.put(url, bitmap);
// Log.e("url", url);
// save the image inside the image holder
//img.setImageBitmap(map.get(url));
Log.e("DwnLD",img.getTag()+"");
img.setImageBitmap(bitmap);
Tools.storePhoto(img.getTag().toString(), bitmap);
}
// Log.e("ImageDownload", "bitmap in imageview");
}
if (type == null){
// map.put(url, bitmap);
// if (img!=null && map.get(url)!=null)img.setImageBitmap(map.get(url));
if (img!=null)img.setImageBitmap(bitmap);
}
if (cnt != null && flag ==2){
Tools.storePhoto(CreateEvent1Fragment.searchResult.get(0).getEventImage(),bitmap);
// Log.e("ImageDownload", "bitmap in imageview");
}
}
}
My Tools.resizeImage is:
public static Bitmap resizeImage(Bitmap bitmap,int newWidth,int newHeight){
Bitmap resized = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
return resized;
}
My Tools.storePhoto is:
public static void storePhoto(String url,Bitmap image){
File img = null;
File env = new File(Environment.getExternalStorageDirectory() + Globals.DIR);
if(!env.exists()) env.mkdir();
String filename = extractUrl(url);
img=new File(Environment.getExternalStorageDirectory()+Globals.DIR+filename);
if (!img.exists()) {
// Log.e("PHOTOS",img.getAbsolutePath());
try {
FileOutputStream fos = new FileOutputStream(img);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
My Tools.getPhoto is:
public static Bitmap getPhoto(String url,int type){
Bitmap bmp=null;
String filename = extractUrl(url);
File ff = new File(Environment.getExternalStorageDirectory()+Globals.DIR+filename);
if(!ff.exists()){
return bmp;
}else {
if (type != 1){
bmp = Tools.decodeFile(ff);
return bmp;
}else {
bmp = BitmapFactory.decodeFile(ff.getAbsolutePath());
return bmp;
}
}
}
My Tools.decodeFile is:
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=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;
}
o.inSampleSize = scale;
o.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o);
} catch (FileNotFoundException e) {}
return null;
}
I want to apply bitmap recycle... How can I do that?
try using Libs Glide
https://github.com/bumptech/glide
change
if (imgz != null) {
mbo.img.setImageBitmap(imgz);
Log.e("NoDwnLd","No");
} else {
Bitmap largeIcon = BitmapFactory.decodeResource(cnt.getResources(), R.drawable.ic_default);
mbo.img.setImageBitmap(largeIcon);
new DownloadBitmap(cnt,mbo.img,"2").execute(photoUrl);
}
to
if(!photoUrl.isEmpty()) {
Glide.with(this).load(photoUrl).error(R.drawable.ic_default).into(mbo.img);
Log.e("NoDwnLd","No");
} else {
Glide.with(this).load(R.drawable.ic_default).error(R.drawable.ic_default).into(mbo.img);
new DownloadBitmap(cnt,mbo.img,"2").execute(photoUrl);
}

Bitmap not setting in imageView random issue

I am trying to fetch file from device storage and showing it in image view .
Sometimes it is working perfectly fine, but sometimes not. Although bitmap is there but image view remains black.
Kindly suggest.
storage file Location
file:/storage/emulated/0/Download/Full-hd-nature-wallpapers-free-download2.jpg
method which is returning bitmap
public static Bitmap convertToBitmap(File file) {
URI uri = null;
try {
uri = file.toURI();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap bmp = BitmapFactory.decodeStream(uri.toURL().openStream(), new Rect(), options);
//bmp.recycle();
return bmp;
} catch (Exception e) {
return null;
}//catch
}
setting image
imageViewPatientImage.setImageBitmap(convertToBitmap(new File(mImagePath));
Try this:
Bitmap bitmap = getThumbnail(uri);
showImage.setImageBitmap(bitmap);
Pass Bitmap for Optimization:
public Bitmap getThumbnail(Uri uri) throws FileNotFoundException, IOException{
InputStream input = getContext().getContentResolver().openInputStream(uri);
BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
onlyBoundsOptions.inJustDecodeBounds = true;
onlyBoundsOptions.inDither=true;//optional
onlyBoundsOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//optional
BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
input.close();
if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1))
return null;
int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth;
double ratio = (originalSize > 500) ? (originalSize / 500) : 1.0;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
bitmapOptions.inDither=true;//optional
bitmapOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//optional
input = getContext().getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
input.close();
return bitmap;
}
private static int getPowerOfTwoForSampleRatio(double ratio){
int k = Integer.highestOneBit((int)Math.floor(ratio));
if(k==0) return 1;
else return k;
}

Recycler NetworkImageView Scrolling back and forward, out of memory and resizing issues

I am working to add an image from the gallery horizontally using recycler view as follows. I could able to add images next to each other.
The following code works but crashes sometimes because of out of memory concerns.
RecyclerViewAdapter, I am calling setSelectedPic method to load the image.
#Override
public void onBindViewHolder(final ListViewHolder holder, int position) {
PostProductImageLIst item = mItems.get(position);
ImageUtil.setSelectedPic(holder.imgViewIcon, item.getPath());
}
ImageUtil Class
public static void setSelectedPic(CustomNetworkImageView view, String url) {
Context context = view.getContext();
ImageLoader imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
if (!TextUtils.isEmpty(url)) {
if (url.startsWith("http")) {
imageLoader.get(url, ImageLoader.getImageListener(view,
R.drawable.image, android.R.drawable
.ic_dialog_alert));
view.setImageUrl(url, imageLoader);
} else {
try {
Uri uri = Uri.parse(url);
InputStream is = context.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(is);
view.setLocalImageBitmap(bitmap);
if (is!=null) {
is.close();
}
} catch (Exception ex) {
Log.e("Image", ex.getMessage(), ex);
}
}
} else {
view.setImageUrl("", CustomVolleyRequest.getInstance(view.getContext()).getImageLoader());
}
}
And then I decide to resize the images to solve the aferomentioned issue, out of memory-.The following code works. BUT, when I scroll back to first image, that image shows blank or white, but when I delete the second image, then I could able to see first image. I could not able to figure out the root of the problem. I am using NetworkImageView.
RecyclerViewAdapter, I am calling setSelectedPic method to load the image.
#Override
public void onBindViewHolder(final ListViewHolder holder, int position) {
PostProductImageLIst item = mItems.get(position);
ImageUtil.setSelectedPic(holder.imgViewIcon, item.getPath());
}
ImageUtil Class
public static void setSelectedPic(CustomNetworkImageView view, String url) {
Context context = view.getContext();
ImageLoader imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
if (!TextUtils.isEmpty(url)) {
if (url.startsWith("http")) {
imageLoader.get(url, ImageLoader.getImageListener(view,
R.drawable.image, android.R.drawable
.ic_dialog_alert));
view.setImageUrl(url, imageLoader);
} else {
try {
int targetW = view.getWidth();
int targetH = view.getHeight();
Uri uri = Uri.parse(url);
InputStream is = context.getContentResolver().openInputStream(uri);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(url, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
Bitmap bitmap = BitmapFactory.decodeStream(is);
Matrix matrix = new Matrix();
matrix.postRotate(getImageOrientation(url));
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), matrix, true);
view.setLocalImageBitmap(rotatedBitmap);
if (is!=null) {
is.close();
} catch (Exception ex) {
Log.e("Image", ex.getMessage(), ex);
}
}
} else {
view.setImageUrl("", CustomVolleyRequest.getInstance(view.getContext()).getImageLoader());
}
}
You should scale your Bitmap and use caching for reducing loading time. Here on this repository I've put reference code for approaching image loading with scaling and caching.
I report here code to be used for setPic method. This essentially uses an LruCache for improving Bitmap loading while scrolling. This could be a good starting point. Notice also that Bitmap are scaled before putting them in cache.
private static final int WIDTH = 100;
private LruCache<String, Bitmap> mMemoryCache;
public void setPic(MyImageView view, String url) {
Context context = view.getContext();
if (!TextUtils.isEmpty(url)) {
if (url.startsWith("http")) {
view.setImageUrl(url, VolleyHandler.getInstance(context).getImageLoader());
} else {
try {
Uri uri = Uri.parse(url);
Bitmap bitmap = mMemoryCache.get(url);
if (bitmap == null) {
InputStream is = context.getContentResolver().openInputStream(uri);
bitmap = BitmapFactory.decodeStream(is);
Bitmap scaled = ImageUtils.getInstance().scaleBitmap(bitmap);
mMemoryCache.put(url, scaled);
if (is!=null) {
is.close();
}
}
view.setLocalImageBitmap(bitmap);
} catch (Exception ex) {
Log.e("Image", ex.getMessage(), ex);
}
}
} else {
view.setImageUrl("", VolleyHandler.getInstance(view.getContext()).getImageLoader());
}
}
public Bitmap scaleBitmap(Bitmap bitmap) {
int width = WIDTH;
int height = (WIDTH * bitmap.getHeight()) / bitmap.getWidth();
return Bitmap.createScaledBitmap(bitmap, width, height, false);
}
I suggest also to refer to Android Developers documentation here (for efficient Bitmap loading) and here (for Bitmap caching with Volley).

Android AsyncTask decode bitmap and set to image

im using a custom method to decode bitmap and set it to imageview as background. For now it's working fine, but in some devices sometimes it's crashing due to out ot memory error. Any idea how can I optime that code and make it better? Here is what I am using :
class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private String data = null;
public BitmapWorkerTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference<ImageView>(imageView);
}
// Decode image in background.
#Override
protected Bitmap doInBackground(String... params) {
data = params[0];
if(data != null){
File bufferFile = new File(data);
Log.e("","data : "+data);
FileInputStream fis = null;
try {
fis = new FileInputStream(bufferFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Cipher cipher = null;
try {
cipher = Cipher.getInstance("AES/CBC/NoPadding");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
int userId = RPCCommunicator.getUserId(Store.this);
String secretSalt = RPCCommunicator.getSecretKey(userId);
String iv = RPCCommunicator.getIv(secretSalt);
SecretKeySpec keySpec = new SecretKeySpec(secretSalt.getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
try {
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
CipherInputStream cis = new CipherInputStream(fis, cipher);
BitmapFactory.Options o2 = new BitmapFactory.Options();
//o2.inSampleSize=2;
o2.inTempStorage = new byte[4*1024];
int width = (int) RPCCommunicator.getPlaceHolderWidth(Store.this, 45);
int height = (int) RPCCommunicator.getPlaceHolderHeight(Store.this, 25);
Rect rect = new Rect();
rect.inset(width, height);
Bitmap finall = BitmapFactory.decodeStream(cis,rect,o2);
if(finall != null){
Bitmap bmp = Bitmap.createScaledBitmap(finall, width, height, true);
return bmp;
} else {
return null;
}
}
return null;
}
// Once complete, see if ImageView is still around and set bitmap.
#Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null) {
final ImageView imageView = imageViewReference.get();
if(bitmap != null){
if (imageView != null) {
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fadein);
imageView.startAnimation(animation);
imageView.setImageBitmap(bitmap);
}
} else {
int width = (int) RPCCommunicator.getPlaceHolderWidth(Store.this, 45);
int height = (int) RPCCommunicator.getPlaceHolderHeight(Store.this, 25);
RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(width, height);
param.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
param.rightMargin = 15;
imageView.setBackgroundResource(R.drawable.placeholder);
imageView.setLayoutParams(param);
}
}
}
}
Any ideas / suggestions / helps are really appreciated!
try this code
public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
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_WIDTH=WIDTH;
final int REQUIRED_HIGHT=HIGHT;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
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 will scale bitmap as you pass width and height..
Use bitmap.recycle() after using your bitmap and before allocating it another value. You can also scale your bitmap down before actually using it. Here's a link: https://stackoverflow.com/a/13226982/1117338
Also one advice: please search well before posting questions. This is an old problem already solved by many.

Categories

Resources