I have the following code to save an image to the cache directory of my application. The method is called within a separate Runnable() which I hoped would speed up the application. As it stands the compressing of the Bitmap is very expensive on the processor and causes the rest of the application to be very slow. How can I speed it up?
public void combineImages(Bitmap bmp, int count, int count2){
Bitmap bottomImage = bmp.copy(Config.RGB_565, true);
float width = bmp.getWidth();
float height = bmp.getHeight();
bmp.recycle();
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image1);
Bitmap topImage = myBitmap.copy(Config.ARGB_4444, true);
myBitmap.recycle();
myBitmap = null;
Canvas comboImage = new Canvas(bottomImage);
// Then draw the second on top of that
comboImage.drawBitmap(topImage, (width / 2) - 200, (height / 2) - 160, null);
topImage.recycle();
topImage = null;
// bottomImage is now a composite of the two.
// To write the file out to the Cache:
OutputStream os = null;
try {
os = new FileOutputStream(getApplicationContext().getCacheDir() + "/" + path);
bottomImage.compress(CompressFormat.PNG, 50, os); //Here it is most expensive and what slows the app down
} catch (IOException e) {
e.printStackTrace();
}
}
You should use a separate thread to run the method, either by creating a new inner class that extends
Threadand call the method or by creating a newThreadand passing theRunnableas a constructor argument. If it is an ongoing task, i.e. you have many bitmaps to process, you may want to have a look atHandlerThreadorIntentService.