如何将Bitmap对象从一个活动传递到另一个活动

mic*_*ael 138 java android bitmap parcelable

在我的活动中,我创建了一个Bitmap对象,然后我需要启动另一个Activity,如何Bitmap从子活动(将要启动的那个)传递这个对象?

Eri*_*ass 288

Bitmap实现Parcelable,所以你总是可以通过意图传递它:

Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", bitmap);
Run Code Online (Sandbox Code Playgroud)

并在另一端检索它:

Intent intent = getIntent(); 
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
Run Code Online (Sandbox Code Playgroud)

  • 如果位图作为文件或资源存在,则总是更好地传递位图的"URI"或"ResourceID"而不是位图本身.传递整个位图需要大量内存.传递URL只需要很少的内存,并允许每个活动在需要时加载和缩放位图. (80认同)
  • 对我不起作用,但是这个可以:http://stackoverflow.com/questions/11010386/send-bitmap-using-intent-android (3认同)

Har*_*mes 23

实际上,将位图作为Parcelable传递将导致"JAVA BINDER FAILURE"错误.尝试将位图作为字节数组传递并构建它以便在下一个活动中显示.

我在这里分享了我的解决方案:
如何使用bundle在android活动之间传递图像(位图)?


Ill*_*ent 13

由于Parceable(1mb)的大小限制,将位图在活动之间的包中传递为parceable并不是一个好主意.您可以将位图存储在内部存储器中的文件中,并在多个活动中检索存储的位图.这是一些示例代码.

要将位图存储在内部存储中的文件myImage中:

public String createImageFromBitmap(Bitmap bitmap) {
    String fileName = "myImage";//no .png or .jpg needed
    try {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
        fo.write(bytes.toByteArray());
        // remember close file output
        fo.close();
    } catch (Exception e) {
        e.printStackTrace();
        fileName = null;
    }
    return fileName;
}
Run Code Online (Sandbox Code Playgroud)

然后在下一个活动中,您可以使用以下代码将此文件myImage解码为位图:

//here context can be anything like getActivity() for fragment, this or MainActivity.this
Bitmap bitmap = BitmapFactory.decodeStream(context.openFileInput("myImage"));
Run Code Online (Sandbox Code Playgroud)

注意很多都会检查null和缩放位图.

  • 这将无法编译 - 无法解析方法“openFileOutput”。 (2认同)

and*_*per 5

如果图像太大并且无法将其保存和加载到存储中,则应考虑仅使用位图的全局静态引用(在接收活动内),仅当“isChangingConfigurations”时,该位图才会在 onDestory 上重置为 null返回真。


Ada*_*itz 5

压缩并发送 Bitmap

Bitmap太大时,接受的答案将崩溃。我相信这是一个1MB 的限制。在Bitmap必须被压缩到不同的文件格式,诸如JPG由a表示ByteArray,那么它可以安全地通过传递Intent

执行

该函数包含在使用Kotlin 协程的单独线程中,因为Bitmap压缩Bitmap是在从 url 创建之后链接的String。在Bitmap创建要求,以避免一个单独的线程应用程序无响应(ANR)错误。

使用的概念

  • Kotlin 协程 注释
  • 下面使用了加载、内容、错误 (LCE)模式。如果有兴趣,您可以在此演讲和视频中了解更多信息。
  • LiveData用于返回数据。我在这些笔记中编译了我最喜欢的LiveData资源。
  • 第 3 步中toBitmap()是一个Kotlin 扩展函数,要求将该库添加到应用程序依赖项中。

代码

1.创建好后压缩BitmapJPG ByteArray

存储库.kt

suspend fun bitmapToByteArray(url: String) = withContext(Dispatchers.IO) {
    MutableLiveData<Lce<ContentResult.ContentBitmap>>().apply {
        postValue(Lce.Loading())
        postValue(Lce.Content(ContentResult.ContentBitmap(
            ByteArrayOutputStream().apply {
                try {                     
                    BitmapFactory.decodeStream(URL(url).openConnection().apply {
                        doInput = true
                        connect()
                    }.getInputStream())
                } catch (e: IOException) {
                   postValue(Lce.Error(ContentResult.ContentBitmap(ByteArray(0), "bitmapToByteArray error or null - ${e.localizedMessage}")))
                   null
                }?.compress(CompressFormat.JPEG, BITMAP_COMPRESSION_QUALITY, this)
           }.toByteArray(), "")))
        }
    }
Run Code Online (Sandbox Code Playgroud)

视图模型.kt

//Calls bitmapToByteArray from the Repository
private fun bitmapToByteArray(url: String) = liveData {
    emitSource(switchMap(repository.bitmapToByteArray(url)) { lce ->
        when (lce) {
            is Lce.Loading -> liveData {}
            is Lce.Content -> liveData {
                emit(Event(ContentResult.ContentBitmap(lce.packet.image, lce.packet.errorMessage)))
            }
            is Lce.Error -> liveData {
                Crashlytics.log(Log.WARN, LOG_TAG,
                        "bitmapToByteArray error or null - ${lce.packet.errorMessage}")
            }
        }
    })
}
Run Code Online (Sandbox Code Playgroud)

2.ByteArray通过Intent.

在此示例中,它从Fragment传递到Service。如果在两个活动之间共享,则是相同的概念。

片段.kt

ContextCompat.startForegroundService(
    context!!,
    Intent(context, AudioService::class.java).apply {
        action = CONTENT_SELECTED_ACTION
        putExtra(CONTENT_SELECTED_BITMAP_KEY, contentPlayer.image)
    })
Run Code Online (Sandbox Code Playgroud)

3. 转换ByteArrayBitmap.

实用工具.kt

fun ByteArray.byteArrayToBitmap(context: Context) =
    run {
        BitmapFactory.decodeByteArray(this, BITMAP_OFFSET, size).run {
            if (this != null) this
            // In case the Bitmap loaded was empty or there is an error I have a default Bitmap to return.
            else AppCompatResources.getDrawable(context, ic_coinverse_48dp)?.toBitmap()
        }
    }
Run Code Online (Sandbox Code Playgroud)