monotouch拍照、选择图片上传实现

不多说,上码:


选择图片上传========》

using System;
using System.Drawing;
using MonoTouch.AssetsLibrary;
using MonoTouch.UIKit;
using MonoTouch.Foundation;

namespace world
{
	public class ImageViewController : UIViewController
	{
		UIImagePickerController imagePicker;
		UIButton choosePhotoButton;
		UIImageView imageView;

		public ImageViewController ()
		{
		}

		public override void ViewWillAppear (bool animated)
		{
			base.ViewWillAppear (animated);
			this.NavigationController.SetNavigationBarHidden (false, false);
		}

		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			Title = "选择图片";
			View.BackgroundColor = UIColor.White;

			imageView = new UIImageView (new RectangleF (10, 80, 300, 300));
			Add (imageView);

			choosePhotoButton = UIButton.FromType (UIButtonType.RoundedRect);
			choosePhotoButton.Frame = new RectangleF (10, 200, 100, 40);
			choosePhotoButton.SetTitle ("Picker", UIControlState.Normal);
			choosePhotoButton.TouchUpInside += (s, e) => {
				// create a new picker controller
				imagePicker = new UIImagePickerController ();

				// set our source to the photo library
				imagePicker.SourceType = UIImagePickerControllerSourceType.PhotoLibrary;

				// set what media types
				imagePicker.MediaTypes = UIImagePickerController.AvailableMediaTypes (UIImagePickerControllerSourceType.PhotoLibrary);

				imagePicker.FinishedPickingMedia += Handle_FinishedPickingMedia;
				imagePicker.Canceled += Handle_Canceled;

				// show the picker
				NavigationController.PresentViewController (imagePicker, true, null);
			};
			View.Add (choosePhotoButton);
		}

		// Do something when the
		void Handle_Canceled (object sender, EventArgs e)
		{
			Console.WriteLine ("picker cancelled");
			imagePicker.DismissViewController (true, null);
		}

		// This is a sample method that handles the FinishedPickingMediaEvent
		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;
			}

			Console.WriteLine (" ==> Reference URL: [" + UIImagePickerController.ReferenceUrl + "]");

			// get common info (shared between images and video)
			NSUrl referenceURL = e.Info [new NSString ("UIImagePickerControllerReferenceURL")] as NSUrl;
			if (referenceURL != null)
				Console.WriteLine (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");

					var documentsDirectory = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
					string jpgFilename = System.IO.Path.Combine (documentsDirectory, DateTime.Now.ToString ("yyyyMMddHHmmss") + ".jpg");
					NSData imgData = originalImage.AsJPEG ();
					NSError err = null;
					if (imgData.Save (jpgFilename, false, out err)) {
						Console.WriteLine ("saved as " + jpgFilename);
					} else {
						Console.WriteLine ("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
					}

					//imageView.Image = originalImage;
					imageView.Image = UIImage.FromFile (jpgFilename);
				}

				// get the edited image
				UIImage editedImage = e.Info [UIImagePickerController.EditedImage] as UIImage;
				if (editedImage != null) {
					// do something with the image
					Console.WriteLine ("got the edited image");
					imageView.Image = editedImage;
				}

				//- get the image metadata
				NSDictionary imageMetadata = e.Info [UIImagePickerController.MediaMetadata] as NSDictionary;
				if (imageMetadata != null) {
					// do something with the metadata
					Console.WriteLine ("got image metadata");
				}

			}
			// if it's a video
			else {
				// get video url
				NSUrl mediaURL = e.Info [UIImagePickerController.MediaURL] as NSUrl;
				if (mediaURL != null) {
					//
					Console.WriteLine (mediaURL.ToString ());
				}
			}

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

		//...

	}
}
注意,从模拟器中调试的时候,选择的图片需要先黏贴,然后保存,才可以选择。关于这点百度一下就知道了。

拍照实现图片上传,核心代码如下:

//
// Camera.cs: Support code for taking pictures
//
// Copyright 2010 Miguel de Icaza
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using MonoTouch.UIKit;
using MonoTouch.Foundation;

namespace TweetStation
{
	//
	// A static class that will reuse the UIImagePickerController
	// as iPhoneOS has a crash if multiple UIImagePickerController are created
	//   http://stackoverflow.com/questions/487173
	// (Follow the links)
	//
	public static class Camera
	{
		static UIImagePickerController picker;
		static Action<NSDictionary> _callback;
		
		static void Init ()
		{
			if (picker != null)
				return;
			
			picker = new UIImagePickerController ();
			picker.Delegate = new CameraDelegate ();
		}
		
		class CameraDelegate : UIImagePickerControllerDelegate {
			public override void FinishedPickingMedia (UIImagePickerController picker, NSDictionary info)
			{
				var cb = _callback;
				_callback = null;
				
				picker.DismissViewController (true, null);
				cb (info);
			}
		}

		//照相
		public static void TakePicture (UIViewController parent, Action<NSDictionary> callback)
		{
			Init ();
			picker.SourceType = UIImagePickerControllerSourceType.Camera;
			_callback = callback;
			parent.PresentViewController (picker, true, null);
		}
		
		public static void SelectPicture (UIViewController parent, Action<NSDictionary> callback)
		{
			Init ();
			picker.SourceType = UIImagePickerControllerSourceType.PhotoLibrary;
			_callback = callback;
			parent.PresentViewController (picker, true, null);
		}
	}
}
using System;
using System.Drawing;
using MonoTouch.AssetsLibrary;
using MonoTouch.UIKit;
using MonoTouch.Foundation;

namespace ImageView {

	public class ImageViewController : UIViewController {
		
		UIButton cameraButton;

		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			Title = "Save to Album";
			View.BackgroundColor = UIColor.White;

			cameraButton = UIButton.FromType (UIButtonType.RoundedRect);
			cameraButton.Frame = new RectangleF(10, 200, 100,40);
			cameraButton.SetTitle ("Camera", UIControlState.Normal);
			cameraButton.TouchUpInside += (sender, e) => {
			
				TweetStation.Camera.TakePicture (this, (obj) =>{
					// https://developer.apple.com/library/ios/#documentation/uikit/reference/UIImagePickerControllerDelegate_Protocol/UIImagePickerControllerDelegate/UIImagePickerControllerDelegate.html#//apple_ref/occ/intfm/UIImagePickerControllerDelegate/imagePickerController:didFinishPickingMediaWithInfo:
					var photo = obj.ValueForKey(new NSString("UIImagePickerControllerOriginalImage")) as UIImage;
					var meta = obj.ValueForKey(new NSString("UIImagePickerControllerMediaMetadata")) as NSDictionary;
					
// This bit of code saves to the Photo Album with metadata
					ALAssetsLibrary library = new ALAssetsLibrary();
					library.WriteImageToSavedPhotosAlbum (photo.CGImage, meta, (assetUrl, error) =>{
						Console.WriteLine ("assetUrl:"+assetUrl);
					});
					

// This bit of code does basic 'save to photo album', doesn't save metadata
//			var someImage = UIImage.FromFile("someImage.jpg");
//			someImage.SaveToPhotosAlbum ((image, error)=> {
//				var o = image as UIImage;
//				Console.WriteLine ("error:" + error);
//			});
					

// This bit of code saves to the application's Documents directory, doesn't save metadata
//					var documentsDirectory = Environment.GetFolderPath
//					                          (Environment.SpecialFolder.Personal);
//					string jpgFilename = System.IO.Path.Combine (documentsDirectory, "Photo.jpg");
//					NSData imgData = photo.AsJPEG();
//					NSError err = null;
//					if (imgData.Save(jpgFilename, false, out err))
//					{
//					    Console.WriteLine("saved as " + jpgFilename);
//					} else {
//					    Console.WriteLine("NOT saved as" + jpgFilename + " because" + err.LocalizedDescription);
//					}


				});
			};
			View.Add (cameraButton);
			
			if (!UIImagePickerController.IsSourceTypeAvailable (UIImagePickerControllerSourceType.Camera)) {
				cameraButton.SetTitle ("No camera", UIControlState.Disabled);
				cameraButton.SetTitleColor (UIColor.Gray, UIControlState.Disabled);
				cameraButton.Enabled = false;
			}
		}
	}
}
顺便说一下,
originalImage.AsJPEG ();
后面有一个AsStream属性,这样可以对选择的图片进行远程服务器上传,你懂的。

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。