0

I let the user choose a background and the user can pick their own pictures from gallery or pictures from the list I bring with the app. I save this picture to FileOutputStream. However, my application gets really slow, I am using the following functions;

//When user picks from gallery
public void save(Bitmap bitmapImage) {
    bitmapImage = scaleBitmap(bitmapImage);

    FileOutputStream fileOutputStream = null;
    try {
        fileOutputStream = new FileOutputStream(createFile());
        bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//When user picks from list and I load from drawables
public void save(int resId) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = IMAGE_IN_SAMPLE_SIZE;
    options.inScaled = false;
    options.inJustDecodeBounds = false;

    Bitmap bitmapImage = BitmapFactory.decodeResource(context.getResources(), resId, options);

    FileOutputStream fileOutputStream = null;
    try {
        fileOutputStream = new FileOutputStream(createFile());
        bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How can I make those functions faster?

I also get this messages:

06-15 12:02:58.884 22320-22320/com I/dalvikvm-heap: Grow heap (frag case) to 15.172MB for 2073616-byte allocation
06-15 12:03:00.716 22320-22320/com I/dalvikvm-heap: Grow heap (frag case) to 15.149MB for 2073616-byte allocation
06-15 12:03:03.129 22320-22320/com I/Choreographer: Skipped 145 frames!  The application may be doing too much work on its main thread.
tomhogenkamp
  • 83
  • 1
  • 11

2 Answers2

0

U should not do must IO work in main thread,maybe you can do it int a Thread, and update your ui by hanlder.

  new Thread(new Runnable() {
        @Override
        public void run() {
            // save your picture
            handler.sendEmptyMessage(0);
        }
    }).start();

And it is better to use rxjava and rxAndroid.

Hope it can help you

Lewis
  • 304
  • 3
  • 10
0

If the image is too big working on another thread will not help , it will still cause OutOfMemory ,

You should try using Glide library to do your thing they implement it in the best way

This link for Glide\Picasso installment and basic use-

https://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en

For scaling-

https://futurestud.io/tutorials/glide-image-resizing-scaling

yanivtwin
  • 617
  • 8
  • 32