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属性,这样可以对选择的图片进行远程服务器上传,你懂的。

时间: 2024-07-29 00:40:44

monotouch拍照、选择图片上传实现的相关文章

HTML5 Plus 拍照或者相册选择图片上传

利用HTML Plus的Camera.GalleryIO.Storage和Uploader来实现手机APP拍照或者从相册选择图片上传.Camera模块管理设备的摄像头,可用于拍照.摄像操作,通过plus.camera获取摄像头管理对象.Gallery模块管理系统相册,支持从相册中选择图片或视频文件.保存图片或视频文件到相册等功能.通过plus.gallery获取相册管理对象.IO模块管理本地文件系统,用于对文件系统的目录浏览.文件的读取.文件的写入等操作.通过plus.io可获取文件系统管理对象

H5拍照、选择图片上传组件核心

背景 前段时间项目重构,改成SSR的项目,但之前用的图片选择上传组件不支持SSR(server-side-render).遂进行了调研,发现很多的工具.但有的太大,有的使用麻烦,有的不满足使用需求.决定自己写一个h5移动端图片上传组件.图片上传是一个比较普遍的需求,PC端还好,移动端就不是特别好做了.下面将过程中一些重点的问题进行简单的记录. 重点 1.关于input 选择功能使用<input>标签实现.属性accept='image/*',:capture表示,可以捕获到系统默认的设备,比如

调用相机,选择图片上传,带预览功能、图片压缩、相机文字设置、

摘要 iOS调用相机,iOS调用相册,保存至应用程序沙盒,高保真压缩图片,并有点击放大预览,再次点击缩回至原大小,带动画效果,附源码下载地址. Xcode版本4.5.1 类库ios6.0 IOS调用相机 图片预览 图片上传 压缩图片 模拟器添加图片 目录[-] 判断是否支持相机,跳转到相机或相册界面 七.保存图片 高保真压缩图片方法 八.实现点击图片预览功能,滑动放大缩小,带动画 ps:模拟器添加图片 源码下载地址: 一.新建工程 二.拖控件,创建映射 三.在.h中加入delegate ? 1

微信小程序开发之从相册获取图片 使用相机拍照 本地图片上传

1.index.wxml 1 <!--index.wxml--> 2 <button style="margin:30rpx;" bindtap="chooseimage">获取图片</button> 3 <image src="{{tempFilePaths }}" mode="aspecFill" style="width: 100%; height: 450rpx&qu

Ionic3学习笔记(十二)拍照上传图片以及从相册选择图片上传

本文为原创文章,转载请标明出处 目录 安装插件 导入 app.module.ts 创建 provider 更多 效果图 1. 安装插件 终端运行: ionic cordova plugin add cordova-plugin-camera npm install --save @ionic-native/camera ionic cordova plugin add cordova-plugin-telerik-imagepicker --variable PHOTO_LIBRARY_USAG

在Android浏览器中通过WebView调用相机拍照/选择文件 上传到服务器

最近做的一个项目中,有这样一个要求,在浏览器中调用系统的拍照功能或者选择文件,然后将文件上传到服务器,类似修改头像.        简单而言,就是在一个html页面中有这样一段代码 <input class="filePrew" type="file" capture="camera" accept="image/*" name="image"> 刚开始的时候,没有感觉很难的,因为在UC浏览器.

Ionic 选择图片上传

1.添加插件 1.1 安装ngcordova 1.2 安装选择图片插件 1.3 安装上传插件 1.4查看安装插件集合 2.html 代码 <div class="item item-icon-right"> <span>封面图片</span> <i class="icon ion-images royal" data-tap-disabled="true" ng-click="taskFMpic

iOS UIPickerController 调用相机,选择图片上传,带预览功能

在.h中加入delegate @interface ViewController : UIViewController<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate> //实现按钮事件 -(IBAction)chooseImage:(id)sender { UIActionSheet *sheet; <p> // 判断是否支持相机 </p> if(

iOS学习:调用相机,选择图片上传,带预览功能

一.新建工程 <ignore_js_op> 二.拖控件,创建映射 <ignore_js_op> 三.在.h中加入delegate @interface ViewController : UIViewController 复制代码 四.实现按钮事件 -(IBAction)chooseImage:(id)sender { UIActionSheet *sheet; // 判断是否支持相机 if([UIImagePickerController isSourceTypeAvailable