Java 如何将 Bitmap 对象从一个活动传递到另一个活动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2459524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I pass a Bitmap object from one activity to another
提问by michael
In my activity, I create a Bitmap
object and then I need to launch another Activity
,
How can I pass this Bitmap
object from the sub-activity (the one which is going to be launched)?
在我的活动中,我创建了一个Bitmap
对象,然后我需要启动另一个对象Activity
,如何Bitmap
从子活动(将要启动的那个)传递这个对象?
采纳答案by Erich Douglass
Bitmap
implements Parcelable
, so you could always pass it with the intent:
Bitmap
实现Parcelable
,因此您始终可以通过以下意图传递它:
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", bitmap);
and retrieve it on the other end:
并在另一端检索它:
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
回答by Harlo Holmes
Actually, passing a bitmap as a Parcelable will result in a "JAVA BINDER FAILURE" error. Try passing the bitmap as a byte array and building it for display in the next activity.
实际上,将位图作为 Parcelable 传递将导致“JAVA BINDER FAILURE”错误。尝试将位图作为字节数组传递并构建它以在下一个活动中显示。
I shared my solution here:
how do you pass images (bitmaps) between android activities using bundles?
我在这里分享了我的解决方案:
如何使用捆绑包在 android 活动之间传递图像(位图)?
回答by Camino2007
In my case, the way mentioned above didn't worked for me. Every time I put the bitmap in the intent, the 2nd activity didn't start. The same happened when I passed the bitmap as byte[].
就我而言,上述方法对我不起作用。每次我将位图放入意图中时,第二个活动都没有开始。当我将位图作为 byte[] 传递时也发生了同样的情况。
I followed this linkand it worked like a charme and very fast:
我点击了这个链接,它工作得非常好,而且速度非常快:
package your.packagename
import android.graphics.Bitmap;
public class CommonResources {
public static Bitmap photoFinishBitmap = null;
}
in my 1st acitiviy:
在我的第一个活动中:
Constants.photoFinishBitmap = photoFinishBitmap;
Intent intent = new Intent(mContext, ImageViewerActivity.class);
startActivity(intent);
and here is the onCreate() of my 2nd Activity:
这是我的第二个活动的 onCreate():
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bitmap photo = Constants.photoFinishBitmap;
if (photo != null) {
mViewHolder.imageViewerImage.setImageDrawable(new BitmapDrawable(getResources(), photo));
}
}
回答by Illegal Argument
Passsing bitmap as parceable in bundle between activity is not a good idea because of size limitation of Parceable(1mb). You can store the bitmap in a file in internal storage and retrieve the stored bitmap in several activities. Here's some sample code.
由于 Parceable(1mb) 的大小限制,在活动之间的 bundle 中将位图作为 parceable 传递不是一个好主意。您可以将位图存储在内部存储的文件中,并在多个活动中检索存储的位图。这是一些示例代码。
To store bitmap in a file myImagein internal storage:
要将位图存储在内部存储器中的文件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;
}
Then in the next activity you can decode this file myImage to a bitmap using following code:
然后在下一个活动中,您可以使用以下代码将此文件 myImage 解码为位图:
//here context can be anything like getActivity() for fragment, this or MainActivity.this
Bitmap bitmap = BitmapFactory.decodeStream(context.openFileInput("myImage"));
NoteA lot of checking for null and scaling bitmap's is ommited.
注意省略了对空值和缩放位图的大量检查。
回答by android developer
If the image is too large and you can't save&load it to the storage, you should consider just using a global static reference to the bitmap (inside the receiving activity), which will be reset to null on onDestory, only if "isChangingConfigurations" returns true.
如果图像太大并且您无法将其保存并加载到存储中,您应该考虑仅使用位图的全局静态引用(在接收活动中),只有在“isChangingConfigurations”时才会在 onDestory 上将其重置为 null返回真。
回答by
Because Intent has size limit . I use public static object to do pass bitmap from service to broadcast ....
因为 Intent 有 size limit 。我使用公共静态对象将位图从服务传递到广播......
public class ImageBox {
public static Queue<Bitmap> mQ = new LinkedBlockingQueue<Bitmap>();
}
pass in my service
传递我的服务
private void downloadFile(final String url){
mExecutorService.submit(new Runnable() {
@Override
public void run() {
Bitmap b = BitmapFromURL.getBitmapFromURL(url);
synchronized (this){
TaskCount--;
}
Intent i = new Intent(ACTION_ON_GET_IMAGE);
ImageBox.mQ.offer(b);
sendBroadcast(i);
if(TaskCount<=0)stopSelf();
}
});
}
My BroadcastReceiver
我的广播接收器
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
LOG.d(TAG, "BroadcastReceiver get broadcast");
String action = intent.getAction();
if (DownLoadImageService.ACTION_ON_GET_IMAGE.equals(action)) {
Bitmap b = ImageBox.mQ.poll();
if(b==null)return;
if(mListener!=null)mListener.OnGetImage(b);
}
}
};
回答by Mwangi Njuguna
It might be late but can help. On the first fragment or activity do declare a class...for example
可能会迟到,但可以提供帮助。在第一个片段或活动上声明一个类......例如
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
description des = new description();
if (requestCode == PICK_IMAGE_REQUEST && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
constan.photoMap = bitmap;
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static class constan {
public static Bitmap photoMap = null;
public static String namePass = null;
}
Then on the second class/fragment do this..
然后在第二堂课/片段上做这个..
Bitmap bm = postFragment.constan.photoMap;
final String itemName = postFragment.constan.namePass;
Hope it helps.
希望能帮助到你。
回答by R?mulo Z. C. Cunha
You can create a bitmap transfer. try this....
您可以创建位图传输。尝试这个....
In the first class:
在第一堂课中:
1) Create:
1)创建:
private static Bitmap bitmap_transfer;
2) Create getter and setter
2)创建getter和setter
public static Bitmap getBitmap_transfer() {
return bitmap_transfer;
}
public static void setBitmap_transfer(Bitmap bitmap_transfer_param) {
bitmap_transfer = bitmap_transfer_param;
}
3) Set the image:
3)设置图像:
ImageView image = (ImageView) view.findViewById(R.id.image);
image.buildDrawingCache();
setBitmap_transfer(image.getDrawingCache());
Then, in the second class:
然后,在第二个类中:
ImageView image2 = (ImageView) view.findViewById(R.id.img2);
imagem2.setImageDrawable(new BitmapDrawable(getResources(), classe1.getBitmap_transfer()));
回答by Ali Tamoor
All of the above solutions doesn't work for me, Sending bitmap as parceableByteArray
also generates error android.os.TransactionTooLargeException: data parcel size
.
以上所有解决方案对我都不起作用,发送位图parceableByteArray
也会产生错误android.os.TransactionTooLargeException: data parcel size
。
Solution
解决方案
- Saved the bitmap in internal storage as:
- 将内部存储中的位图保存为:
public String saveBitmap(Bitmap bitmap) {
String fileName = "ImageName";//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;
}
- and send in
putExtra(String)
as
- 并
putExtra(String)
作为
Intent intent = new Intent(ActivitySketcher.this,ActivityEditor.class);
intent.putExtra("KEY", saveBitmap(bmp));
startActivity(intent);
- and Receive it in other activity as:
- 并在其他活动中将其接收为:
if(getIntent() != null){
try {
src = BitmapFactory.decodeStream(openFileInput("myImage"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
回答by Adam Hurwitz
Compress and Send Bitmap
压缩并发送 Bitmap
The accepted answer will crash when the Bitmap
is too large.I believe it's a 1MBlimit. The Bitmap
must be compressed into a different file format such as a JPGrepresented by a ByteArray
, then it can be safely passed via an Intent
.
当Bitmap
太大时,接受的答案将崩溃。我相信这是一个1MB 的限制。在Bitmap
必须被压缩到不同的文件格式,诸如JPG由a表示ByteArray
,那么它可以安全地通过传递Intent
。
Implementation
执行
The function is contained in a separate thread using Kotlin Coroutinesbecause the Bitmap
compression is chained after the Bitmap
is created from an url String
. The Bitmap
creation requires a separate thread in order to avoid Application Not Responding (ANR)errors.
该函数包含在使用Kotlin 协程的单独线程中,因为Bitmap
压缩Bitmap
是在从 url 创建之后链接的String
。在Bitmap
创建要求,以避免一个单独的线程应用程序无响应(ANR)错误。
Concepts Used
使用的概念
- Kotlin Coroutinesnotes.
- The Loading, Content, Error (LCE)pattern is used below. If interested you can learn more about it in this talk and video.
- LiveDatais used to return the data. I've compiled my favorite LiveDataresource in these notes.
- In Step 3,
toBitmap()
is a Kotlin extension functionrequiring that library to be added to the app dependencies.
- Kotlin 协程注释。
- 下面使用了加载、内容、错误 (LCE)模式。如果有兴趣,您可以在此演讲和视频中了解更多信息。
- LiveData用于返回数据。我在这些笔记中编译了我最喜欢的LiveData资源。
- 在第 3 步中,
toBitmap()
是一个Kotlin 扩展函数,要求将该库添加到应用程序依赖项中。
Code
代码
1. Compress Bitmap
to JPGByteArray
after it has been created.
1.创建好后压缩Bitmap
成JPGByteArray
。
Repository.kt
存储库.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(), "")))
}
}
ViewModel.kt
视图模型.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}")
}
}
})
}
2. Pass image as ByteArray
via an Intent
.
2.ByteArray
通过Intent
.
In this sample it's passed from a Fragmentto a Service. It's the same concept if being shared between two Activities.
在此示例中,它从Fragment传递到Service。如果在两个活动之间共享,则是相同的概念。
Fragment.kt
片段.kt
ContextCompat.startForegroundService(
context!!,
Intent(context, AudioService::class.java).apply {
action = CONTENT_SELECTED_ACTION
putExtra(CONTENT_SELECTED_BITMAP_KEY, contentPlayer.image)
})
3. Convert ByteArray
back to Bitmap
.
3. 转换ByteArray
回Bitmap
.
Utils.kt
实用工具.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()
}
}