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.
答案 0 :(得分:0)
new Thread(new Runnable() {
@Override
public void run() {
// save your picture
handler.sendEmptyMessage(0);
}
}).start();
最好使用rxjava和rxAndroid。
希望它可以帮到你
答案 1 :(得分:0)
如果图像太大而在另一个线程上工作也无济于事,它仍然会导致OutOfMemory,
你应该尝试使用Glide库来做你最好的方式实现它
这个链接适用于Glide \ Picasso分期付款和基本使用 -
https://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en
用于缩放 -
https://futurestud.io/tutorials/glide-image-resizing-scaling