Android异步任务重新映射位图

时间:2017-06-29 08:49:59

标签: java android multithreading bitmap android-asynctask

我想将位图数组存储到TextFile。所以我将每个Bitmap转换为Base64 String并将其连接成一个字符串并存储在TextFile中。

这有效:

String imjCodSrg = getImjCodSrgFrmBitmapAryFnc(bitmapAryVar);

但这需要很长时间,所以我试图放入Async任务或线程,但得到Recycled错误。

new AsyncTask<Void, Void, Void>()
{
    protected Void doInBackground(Void... ArgAryPsgVar)
    {
        String imjCodSrg = getImjCodSrgFrmBitmapAryFnc(bitmapAryVar);

        return null;
    }
}.execute();        

|或|

new Thread(new Runnable()
{
    @Override
    public void run()
    {
        String imjCodSrg = getImjCodSrgFrmBitmapAryFnc(bitmapAryVar);
    }
}).start();

| * |我的助手功能:

// |==| Get Imj Byte Ary From Bitmap :

byte[] getImjBytAryFrmBitmapFnc(Bitmap srcImjBitmap)
{
    ByteArrayOutputStream imjBytAryVar = new ByteArrayOutputStream();
    srcImjBitmap.compress(Bitmap.CompressFormat.JPEG, 100, imjBytAryVar);
    return imjBytAryVar.toByteArray();
}

// |==| Get Image String Code From Bitmap Array :

String getImjCodSrgFrmBitmapAryFnc(List<Bitmap> srcImjBitmapVar)
{
    List<String> imjSrgCodAryVar = new ArrayList<>();
    for (Bitmap bitmapIdxVar : srcImjBitmapVar)
    {
        PrnFnc("bitmapIdxVar.isRecycled() : " + bitmapIdxVar.isRecycled());
        byte[] ImjBytAryIdxVar = getImjBytAryFrmBitmapFnc(bitmapIdxVar);
        String ImjCodSrgIdxVar = Base64.encodeToString(ImjBytAryIdxVar, Base64.DEFAULT);
        imjSrgCodAryVar.add(ImjCodSrgIdxVar);
    }
    return TextUtils.join("|", imjSrgCodAryVar);
}

我无法理解为什么AsyncTask或线程会使Bitmap重复使用。

  

我收到以下错误:

     

D / TAG:bitmapIdxVar.isRecycled():false
    D / TAG:bitmapIdxVar.isRecycled():true

>   E/UncaughtException: java.lang.RuntimeException: An error occurred while executing doInBackground()
                     at android.os.AsyncTask$3.done(AsyncTask.java:309)
                     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                     at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                     at java.lang.Thread.run(Thread.java:818)
                  Caused by: java.lang.IllegalStateException: Can't compress a recycled bitmap
                     at android.graphics.Bitmap.checkRecycled(Bitmap.java:351)
                     at android.graphics.Bitmap.compress(Bitmap.java:1018)

1 个答案:

答案 0 :(得分:1)

首先 - 你不应该像这样存储位图。这样做会导致非常大的内存消耗。存储图像的正确方法 - 将它们保存到存储中并将文件路径写入数据库。 Here是缓存Bitmaps的有用链接。