在处理图像时始终获取DidReceiveMemoryWarning

时间:2017-05-27 07:00:51

标签: c# ios xamarin.ios

附加我创建的应用程序的源代码,它是一个带有集合视图和按钮的简单应用程序,用于从库或相机中选择图像。从相机连续拍摄8张图像后,ios应用程序崩溃。

using CoreGraphics;
using Foundation;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using UIKit;

namespace App2.iOS
{
public class imagesDisplay
{
public bool PlusImg;
public bool uploaded;
public string path { get; set; }
public int id { get; set; }

        public imagesDisplay(bool uploaded, bool PlusImg = false, string path = null, int id = 0)
        {
            this.uploaded = uploaded;
            this.PlusImg = PlusImg;
            this.path = path;
            this.id = id;
        }
    }
public partial class ViewController : UIViewController
{

    public List<imagesDisplay> images = new List<imagesDisplay>();
    private UIAlertController alert;
    private UIImagePickerController imagePicker;
    private NSData imgData;
    private NSData thumdata;

    public ViewController (IntPtr handle) : base (handle)
    {
    }

    public override void ViewDidLoad ()
    {
        base.ViewDidLoad ();
        imgCollection.SetCollectionViewLayout(new LineLayout(), false);
        imgCollection.AllowsMultipleSelection = true;
        imgCollection.RegisterNibForCell(UINib.FromName("imageceCollectionViewCell", null), imageceCollectionViewCell.Key);
        alert = UIAlertController.Create("", "Select image from : ", UIAlertControllerStyle.ActionSheet);

        var cameraaction = UIAlertAction.Create("Bruk kamera", UIAlertActionStyle.Default, a =>
        {
            imagePicker = new UIImagePickerController();
            imagePicker.SourceType = UIImagePickerControllerSourceType.Camera;
            imagePicker.FinishedPickingMedia += Handle_FinishedPickingMedia;
            imagePicker.Canceled += Handle_Canceled;
            imagePicker.AllowsImageEditing = false;
            this.NavigationController.PresentViewController(imagePicker, true, null);
        });
        alert.AddAction(cameraaction);

        var galleryaction = UIAlertAction.Create("Last opp bilder", UIAlertActionStyle.Default, a =>
        {
            imagePicker = new UIImagePickerController();
            imagePicker.SourceType = UIImagePickerControllerSourceType.PhotoLibrary;
            imagePicker.FinishedPickingMedia += Handle_FinishedPickingMedia;
            imagePicker.Canceled += Handle_Canceled;
            imagePicker.AllowsImageEditing = false;
            this.NavigationController.PresentViewController(imagePicker, true, null);
        });
        alert.AddAction(galleryaction);
        alert.AddAction(UIAlertAction.Create("Avbryt", UIAlertActionStyle.Cancel, a => { }));
        imgCollection.Source = new ImageCollectionSource(images,new WeakReference<UINavigationController>(this.NavigationController));
    }

    public override void DidReceiveMemoryWarning ()
    {
        base.DidReceiveMemoryWarning ();
        // Release any cached data, images, etc that aren't in use.
    }

    partial void UIButton125_TouchUpInside(UIButton sender)
    {            
        this.PresentViewController(alert, true, null);
    }
    private void Handle_Canceled(object sender, EventArgs e)
    {
        imagePicker.DismissModalViewController(true);
    }

    private void Handle_FinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs e)
    {
        try
        {
            NSUrl referenceURL = e.Info[new NSString("UIImagePickerControllerReferenceUrl")] as NSUrl;
            if (referenceURL != null)
                Console.WriteLine("Url:" + referenceURL.ToString());
            UIImage originalImage = e.Info[UIImagePickerController.OriginalImage] as UIImage;
            if (originalImage != null)
            {
                var documentsDirectory = Environment.GetFolderPath
                     (Environment.SpecialFolder.Personal);
                string timestamp = DateTime.Now.ToString("yyyyMMddHHmmssffff");
                string jpgFilename = System.IO.Path.Combine(documentsDirectory, timestamp + ".jpg"); // hardcoded filename, overwritten each time
                string thumname = System.IO.Path.Combine(documentsDirectory, timestamp + "_thumb" + ".jpg");
                imgData = originalImage.AsJPEG();
                Console.WriteLine("Original image size = " + imgData.Length);
                thumdata = originalImage.AsJPEG(0.0f);
                Console.WriteLine("after funtion compresion image size = " + thumdata.Length);
                NSError err = null;
                if (imgData.Save(jpgFilename, false, out err))
                {
                    Console.WriteLine("saved as " + jpgFilename);
                    NSError err1 = null;
                    if (thumdata.Save(thumname, false, out err1))
                    {
                        Console.WriteLine("saved as " + jpgFilename);
                    }
                    else
                    {
                        Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
                    }
                }
                else
                {
                    Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
                }
                images.Add(new imagesDisplay(false, false, thumname, 0));
            }
            imgCollection.ReloadData();
            imagePicker.DismissViewController(true, null);
        }
        catch (Exception ex)
        {

        }
    }        
}
public class LineLayout : UICollectionViewFlowLayout
{
    public LineLayout()
    {
        ItemSize = new CGSize((UIScreen.MainScreen.Bounds.Width / 2) - 12, (UIScreen.MainScreen.Bounds.Height / 3) - 40);
        MinimumInteritemSpacing = 0f;
    }
}
}

1 个答案:

答案 0 :(得分:0)

强制在创建新图像数据之前释放图像数据:

if (imgData != null) {
    imgData.Dispose(); 
    imgData = null;
}
imgData = originalImage.AsJPEG();

或者使用using句子的局部变量:

using (NSData imgData = originalImage.AsJPEG()) { //imgData will be disposed immediately at the end of block
    //......
}