在单触感中将UIImage转换为UIData失败

时间:2014-03-08 16:04:00

标签: xamarin.ios uiimage xamarin uiimagepickercontroller nsdata

我已经看到了关于堆栈溢出的问题的变化,但没有任何对我有用的答案。我正在尝试将通过UIImagePickerController检索的图像转换为NSData对象。在我调用AsJPEG之后的调试器中,NSData对象的文本显示为...

System.Exception: Could not initialize an instance of the type 'MonoTouch.Foundation.NSString': the native 'initWithDa…

(注意调试器切断字符串)

我的代码非常简单(从堆栈溢出的样本中获取)

    protected void Handle_FinishedPickingMedia (object sender, UIImagePickerMediaPickedEventArgs e) {
        // determine what was selected, video or image
        bool isImage = false;
        switch(e.Info[UIImagePickerController.MediaType].ToString()) {
        case "public.image":
            Console.WriteLine("Image selected");
            isImage = true;
            break;
        case "public.video":
            Console.WriteLine("Video selected");
            break;
        }

        string path = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
        path = Path.Combine (path, "media");
        if (!Directory.Exists (path))
            Directory.CreateDirectory (path);
        path = Path.Combine (path, Path.GetRandomFileName ());

        // get common info (shared between images and video)
        NSUrl referenceURL = e.Info[new NSString("UIImagePickerControllerReferenceUrl")] as NSUrl;
        if (referenceURL != null)
            Console.WriteLine("Url:"+referenceURL.ToString ());

        // if it was an image, get the other image info
        if(isImage) {
            // get the original image
            UIImage originalImage = e.Info[UIImagePickerController.OriginalImage] as UIImage;

            if(originalImage != null) {
                // do something with the image
                Console.WriteLine ("got the original image");

                using (NSData imageData = originalImage.AsJPEG(0.75f)) {
                    byte[] dataBytes = new byte[imageData.Length];
                    System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, dataBytes, 0, Convert.ToInt32(imageData.Length));
                    File.WriteAllBytes (path, dataBytes);
                }
            }
        } else { // if it's a video
            // get video url
            NSUrl mediaURL = e.Info[UIImagePickerController.MediaURL] as NSUrl;
            if(mediaURL != null) {
                // ...
            }
        }          

        // dismiss the picker
        NavigationController.DismissViewController (true, null);
    }

我看过其他帖子表明它的大小与UIImage相同,所以我已经尝试过裁剪它。结果相同。我也尝试过AsPNG,结果相同。我甚至尝试将图像缩小到1/4它的原始尺寸并仍然得到错误。

我认为关键是提到NSString,它告诉我一些可疑的东西......因为Xcode中使用的本机C调用不涉及NSString,所以我认为还有其他事情发生。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

正如Therealjohn的评论中所指出的,当调试器将值转换为字符串以在调试器窗口中显示它似乎遇到错误时,这似乎是一个错误。 NSData对象实际上很好。