1

I'm using the following code to create a resized bitmap, the code works okay, but it's very slow. The problem is that when I try to use this for more than one image the phone freezes until the images are created.

Here is my code:

Bitmap bitmap = null;
File imgFile = new File(my_pic_file);
if(imgFile.exists()) {
  bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
  Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, 300, 200, false);
  first_image.setImageBitmap(resizedBitmap);
}
Alekz
  • 89
  • 6
steo
  • 293
  • 1
  • 4
  • 15

1 Answers1

2

The problem is that you are doing the work on the main thread. This means that it will freeze the UI until all the processing is finished. You can fix this by either using a thread or asynchronous task.

 private class LoadImageTask extends AsyncTask<String, Void, Bitamp> {

 private ImageView mImageView = null;

 public LoadImageTask(ImageView imageView) {

    mImageView = imageView;
 }

 protected Bitmap doInBackground(String... file) {

    Bitmap bitmap = null;
    Bitmap resizedBitmap = null;
    File imgFile = new File(file);
    if(imgFile.exists()) {
      bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
      resizedBitmap = Bitmap.createScaledBitmap(bitmap, 300, 200, false);
    }

    return resizedBitmap;
 }

 protected void onPostExecute(Bitmap result) {
     if (result != null && mImageView != null) {

        mImageView.setImageBitmap(result);
     }
 }

Then in your code just call

new LoadImageTask(first_image).execute(my_pic_file);
Stratus_Hunter
  • 301
  • 2
  • 4