异步PNG保存有时很慢

时间:2017-03-26 05:42:43

标签: android bitmap android-asynctask save png

在图像编辑器中实际保存大的PNG很慢,所以我在活动暂停(关闭)后使用AsyncTask保存在后台。它通常很完美。但有时候(也许是在将应用程序保留在后台几个小时然后将应用程序带到前台之后)保存会延迟,可能是在我关闭活动后20秒。

@Override
protected void onPause() {
    savePngAsync();
}

public void savePngAsync() {
    int theBitmapW=Math.max(png_width,MAX_DRAWN_X);
    int theBitmapH=Math.max(png_height,MAX_DRAWN_Y);

    Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
    Bitmap bmp = Bitmap.createBitmap(theBitmapW, theBitmapH, conf); // this creates a MUTABLE bitmap
    Canvas canvas = new Canvas(bmp);
    drawOnCanvas(canvas,true,false);
    String outputfilename=filename+".png";

    AsyncPngSaver asyncPngSaver=new AsyncPngSaver(outputfilename);
    asyncPngSaver.execute(bmp);
}

public class AsyncPngSaver extends AsyncTask<Bitmap,Integer,Boolean>
{
    public String outputfilename;

    public AsyncPngSaver(String outputfilename)
    {
        this.outputfilename=outputfilename;
    }

    @Override
    protected Boolean doInBackground(Bitmap... bitmaps) {
        try {
            FileOutputStream out=null;
            Bitmap bmp = bitmaps[0];
            try {
                out = new FileOutputStream(outputfilename);
                bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
                // PNG is a lossless format, the compression factor (100) is ignored
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        Log.d(Utils.DTAG,"png saved in background, broadcasting");
        Intent in = new Intent(Utils.KEY_REFRESH_BROADCAST);
        getContext().sendBroadcast(in);
    }
}

1 个答案:

答案 0 :(得分:0)

你不关心透明度,请使用 Bitmap.Config.RGB_565

它会很快!!!

Bitmap.Config conf = Bitmap.Config.RGB_565;