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

来源:互联网 发布:火影忍者拍照软件 编辑:程序博客网 时间:2024/04/30 15:30

不多说,上码:


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

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 controllerimagePicker = new UIImagePickerController ();// set our source to the photo libraryimagePicker.SourceType = UIImagePickerControllerSourceType.PhotoLibrary;// set what media typesimagePicker.MediaTypes = UIImagePickerController.AvailableMediaTypes (UIImagePickerControllerSourceType.PhotoLibrary);imagePicker.FinishedPickingMedia += Handle_FinishedPickingMedia;imagePicker.Canceled += Handle_Canceled;// show the pickerNavigationController.PresentViewController (imagePicker, true, null);};View.Add (choosePhotoButton);}// Do something when thevoid Handle_Canceled (object sender, EventArgs e){Console.WriteLine ("picker cancelled");imagePicker.DismissViewController (true, null);}// This is a sample method that handles the FinishedPickingMediaEventprotected void Handle_FinishedPickingMedia (object sender, UIImagePickerMediaPickedEventArgs e){// determine what was selected, video or imagebool 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 infoif (isImage) {// get the original imageUIImage originalImage = e.Info [UIImagePickerController.OriginalImage] as UIImage;if (originalImage != null) {// do something with the imageConsole.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 imageUIImage editedImage = e.Info [UIImagePickerController.EditedImage] as UIImage;if (editedImage != null) {// do something with the imageConsole.WriteLine ("got the edited image");imageView.Image = editedImage;}//- get the image metadataNSDictionary imageMetadata = e.Info [UIImagePickerController.MediaMetadata] as NSDictionary;if (imageMetadata != null) {// do something with the metadataConsole.WriteLine ("got image metadata");}}// if it's a videoelse {// get video urlNSUrl mediaURL = e.Info [UIImagePickerController.MediaURL] as NSUrl;if (mediaURL != null) {//Console.WriteLine (mediaURL.ToString ());}}// dismiss the pickerimagePicker.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 metadataALAssetsLibrary 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属性,这样可以对选择的图片进行远程服务器上传,你懂的。

0 0