首页 > 解决方案 > 为什么另一个activity中没有图片预览?

问题描述

我想捕获一张图片并在下一个活动中显示捕获的图片,但该图片没有显示在我的下一个活动中使用此代码。摄像头运行良好,可以跳转到下一个活动。

数据列表.cs

btnCamera.Click += delegate
        {
            Intent intent = new Intent(MediaStore.ActionImageCapture);
            StartActivityForResult(intent, 0);
        };
    }
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
    {
        base.OnActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == Result.Ok)
        {

            Bitmap imageBitmap = (Bitmap)data.Extras.Get("data"); 
            byte[] bitmapData;
            using (new MemoryStream())
            {
                imageBitmap.Compress(Bitmap.CompressFormat.Png, 0, new MemoryStream());
                bitmapData = new MemoryStream().ToArray();
            }

            Intent intent = new Intent(this, typeof(camera));

            intent.PutExtra("picture", bitmapData);

            StartActivity(intent);

        }

相机.cs

   protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.image_upload);
        upload = FindViewById<Button>(Resource.Id.upload);
        pic = FindViewById<ImageView>(Resource.Id.camera);


        if (Intent.GetByteArrayExtra("picture") != null)
        {
            //Convert byte array back into bitmap
            Bitmap bitmap = 
BitmapFactory.DecodeByteArray(Intent.GetByteArrayExtra("picture"), 0, 
Intent.GetByteArrayExtra("picture").Length);
            pic.SetImageBitmap(bitmap);
        }

标签: c#androidxamarin.android

解决方案


 using (new MemoryStream())
        {
            imageBitmap.Compress(Bitmap.CompressFormat.Png, 0, new MemoryStream());
            bitmapData = new MemoryStream().ToArray();
        }

你总是使用new MemoryStream(),所以bitmapDatabyte[0]

像这样改变:

using ( var stream =new MemoryStream())
     {
        imageBitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
        bitmapData = stream.ToArray();
     }

推荐阅读