从Camera加载单个位图时如何处理Out of Memory错误

时间:2012-11-13 21:36:35

标签: android bitmap camera xamarin.android out-of-memory

我的问题是如何在将字节数组解码为位图时处理Out of Memory错误,以便我可以对其进行旋转。我的代码如下,在您说它的副本之前,我尝试使用BitmapFactory.Options并将样本大小设置为2.但是质量损失太糟糕了,无法接受。它似乎只发生在一个设备上,所以也许它是一个一次性的东西,但是我倾向于相信如果它影响一个,将会有25个更喜欢它。这也发生在拍摄的第一张照片上,这是此活动与位图有关的唯一工作。虽然我在Monodroid工作,但我也欢迎Java的答案,因为我通常可以很容易地将它们转换为C#。

public void GotImage(byte[] image)
    {
        try
        {
            Android.Graphics.Bitmap thePicture = Android.Graphics.BitmapFactory.DecodeByteArray(image, 0, image.Length);
            Array.Clear(image, 0, image.Length);
            image = null;
            GC.Collect();
            Android.Graphics.Matrix m = new Android.Graphics.Matrix();
            m.PostRotate(90);
            Android.Graphics.Bitmap rotatedPicture = Android.Graphics.Bitmap.CreateBitmap(thePicture, 0, 0, thePicture.Width, thePicture.Height, m, true);
            thePicture.Dispose();
            thePicture = null;
            GC.Collect();

            using (MemoryStream ms = new MemoryStream())
            {
                rotatedPicture.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, ms);
                image = ms.ToArray();
            }
            rotatedPicture.Dispose();
            rotatedPicture = null;
            GC.Collect();

            listOfImages.Add(image);
            storeButton.Text = "  Store " + listOfImages.Count + " Pages  ";
            storeButton.Enabled = true;
            takePicButton.Enabled = true;
            gotImage = false;
            cameraPreviewArea.camera.StartPreview();
        }
        catch (Exception ex)
        {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
            alertDialog.SetTitle("Error Taking Picture");
            alertDialog.SetMessage(ex.ToString());
            alertDialog.SetPositiveButton("OK", delegate { });
            alertDialog.Show();
        }
    }

2 个答案:

答案 0 :(得分:0)

什么是rotatedPicture.Dispose()?这只是将引用设置为null吗?摆脱Bitmap内存的最佳和最快捷的方法是使用recycle()方法。

答案 1 :(得分:0)

经过漫长的一天学习后,我发现了修复/解决方法。这涉及在拍摄照片之前设置照相机拍摄的照片的分辨率,而不是在事实之后尝试缩放照片。我还在设置中设置选项,以便用户尝试不同的分辨率,直到他们得到最适合他们的分辨率。

Camera.Parameters parameters = camera.GetParameters();
parameters.SetPictureSize(parameters.SupportedPictureSizes[parameters.SupportedPictureSizes.Count - 1].Width,
                    parameters.SupportedPictureSizes[parameters.SupportedPictureSizes.Count - 1].Height);
camera.SetParameters(parameters);
camera.StartPreview();
相关问题