gpt4 book ai didi

android - 如何在 Android Activity 之间发送大字节数组?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:20:07 25 4
gpt4 key购买 nike

我需要从 Activity1 发送 byte[] 数据Activity2,以便写入 data("FileOutputStream.write (data)") 在一个 jpg 文件中。我的最终 .jpg 文件可能超过 1mb。

Activity 1:

public void onPictureTaken(byte[] data, Camera camera) {

Log.w("ImageSizeMyApp", String.valueOf(data.length));

mCamera.startPreview();
Intent shareWindow = new Intent(Activity1.this, Activity2.class);
shareWindow.putExtra("photo",data);
startActivity(shareWindow);
closeCamera();

Log.w("CameraActivity:", "onPictureTaken");

}

在 Activity 2 中:

Bundle extras = getIntent().getExtras();
data = extras.getByteArray("photo");

我使用 Log.w("ImageSizeMyApp", String.valueOf(data.length)); 得到这个:

  1. ImageSizeMyApp:446367(这个尺寸发送到下一个activity,一切正常)

  2. ImageSizeMyApp:577368(这个尺寸会关闭我的相机,并且不会发送到下一个 Activity )

所以500kb是Intent的极限维度。有没有其他稳定的方法可以在 Activity 之间发送大于 500kb 的 byte[]

欢迎任何引用或建议。提前致谢!

更新:

我可以创建另一个类来存储那个 byte[] 数组吗?还是使用静态变量更好?

最佳答案

  1. 创建一个临时文件。
  2. 将文件路径传递给其他 Activity 。
  3. 获取路径并加载图片。

Activity 1:

    //creates the temporary file and gets the path
String filePath= tempFileImage(context,yourBitmap,"name");



Intent intent = new Intent(context, Activity2.class);

//passes the file path string with the intent
intent.putExtra("path", filePath);


startActivity(intent);

使用此方法创建文件:

   //creates a temporary file and return the absolute file path
public static String tempFileImage(Context context, Bitmap bitmap, String name) {

File outputDir = context.getCacheDir();
File imageFile = new File(outputDir, name + ".jpg");

OutputStream os;
try {
os = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(context.getClass().getSimpleName(), "Error writing file", e);
}

return imageFile.getAbsolutePath();
}

Activity 2:

//gets the file path
String filePath=getIntent().getStringExtra("path");

//loads the file
File file = new File(filePath);

最后加载图片:

Picasso.with(context).load(file).fit().centerCrop().into(imageView);

或者:

Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
imageView.setImageBitmap(bitmap);

关于android - 如何在 Android Activity 之间发送大字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31426447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com