[英]Speed up execution of caching an image in Android
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.该方法在一个单独的Runnable()
中调用,我希望它可以加快应用程序的速度。 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.就目前而言,Bitmap 的压缩在处理器上非常昂贵,并导致应用程序的 rest 非常慢。 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 Thread
and call the method or by creating a new Thread
and passing the Runnable
as a constructor argument.您应该使用单独的线程来运行该方法,方法是创建一个扩展Thread
的新内部 class 并调用该方法,或者创建一个新Thread
并将Runnable
作为构造函数参数传递。 If it is an ongoing task, ie you have many bitmaps to process, you may want to have a look at HandlerThread
or IntentService
.如果它是一项正在进行的任务,即您有许多位图要处理,您可能想看看HandlerThread
或IntentService
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.