private async Task<NSUrl> SavePhotoWithLocationAsync(NSDictionary info) { var image = (UIImage)info[UIImagePickerController.EditedImage]; if (image == null) image = (UIImage)info[UIImagePickerController.OriginalImage]; var metadata = info[UIImagePickerController.MediaMetadata] as NSDictionary; var newMetadata = new NSMutableDictionary(metadata); if (!newMetadata.ContainsKey(ImageIO.CGImageProperties.GPSDictionary)) { var gpsData = await BuildGPSDataAsync(); if (gpsData != null) newMetadata.Add(ImageIO.CGImageProperties.GPSDictionary, gpsData); } // save to camera roll with metadata var assetUrlTCS = new TaskCompletionSource<NSUrl>(); using (var library = new ALAssetsLibrary()) { library.WriteImageToSavedPhotosAlbum(image.CGImage, newMetadata, (newAssetUrl, error) => { // any additional processing can go here if (error == null) assetUrlTCS.SetResult(newAssetUrl); else assetUrlTCS.SetException(new Exception(error.LocalizedFailureReason)); }); } return await assetUrlTCS.Task; }
public override void FinishedPickingMedia(UIImagePickerController picker, NSDictionary info) { //got selected image NSUrl assetURL = (NSUrl)info.ObjectForKey(UIImagePickerController.ReferenceUrl); if (assetURL != null) { Action <ALAsset> resultBlock = delegate(ALAsset myasset) { NSDictionary metadata = myasset.DefaultRepresentation.Metadata; UIImage image = new UIImage(myasset.DefaultRepresentation.GetFullScreenImage()); LoadPhotoBlock(metadata, image); }; Action <NSError> failureBlock = delegate(NSError myerror) { Console.WriteLine("cant get image - {0}", myerror.LocalizedDescription); LoadPhotoBlock(null, null); }; ALAssetsLibrary assetsLib = new ALAssetsLibrary(); assetsLib.AssetForUrl(assetURL, resultBlock, failureBlock); } }
/// <summary> /// Saves the movie to the camera roll. /// </summary> void SaveMovieToCameraRoll() { //Console.WriteLine ("Save movie to camera roll"); using (var library = new ALAssetsLibrary()) { library.WriteVideoToSavedPhotosAlbum(movieURL, (assetUrl, error) => { if (error != null) { ShowError(error); } else { RemoveFile(movieURL); } movieWritingQueue.DispatchAsync(() => { recordingWillBeStopped = false; IsRecording = false; if (RecordingDidStop != null) { RecordingDidStop(); } }); }); } }
/// <summary> /// Gets the picture media file. /// </summary> /// <param name="info">The information.</param> /// <returns>MediaFile.</returns> private void GetPictureMediaFile(NSDictionary info, Action <MediaFile> callback) { var image = (UIImage)info[UIImagePickerController.OriginalImage]; var referenceURL = (NSUrl)info[UIImagePickerController.ReferenceUrl]; if (referenceURL == null) //from camera { var metadata = (NSDictionary)info[UIImagePickerController.MediaMetadata]; ALAssetsLibrary library = new ALAssetsLibrary(); library.WriteImageToSavedPhotosAlbum(image.CGImage, metadata, (assetUrl, error) => { }); GetPictureMediaFileWithMetadata(metadata, image, callback); } else // from albun { ALAssetsLibrary library = new ALAssetsLibrary(); library.AssetForUrl(referenceURL, (ALAsset asset) => { ALAssetRepresentation rep = asset.DefaultRepresentation; NSDictionary metadata = rep.Metadata; var cgimg = rep.GetFullScreenImage(); var img = new UIImage(cgimg); GetPictureMediaFileWithMetadata(metadata, img, callback); }, (e) => { }); } }
void exportCompleted(AVAssetExportSession session) { exportProgressView.Hidden = true; currentTimeLabel.Hidden = false; var outputUrl = session.OutputUrl; progressTimer.Invalidate(); progressTimer = null; if (session.Status != AVAssetExportSessionStatus.Completed) { Console.WriteLine("exportSession error:{0}", session.Error.LocalizedDescription); reportError(session.Error); return; } exportProgressView.Progress = 1f; var library = new ALAssetsLibrary(); library.WriteVideoToSavedPhotosAlbum(outputUrl, (assetURL, error) => { if (error != null) { Console.WriteLine("writeVideoToAssetsLibrary failed: {0}", error.LocalizedDescription); reportError(error); } }); Player.Play(); playPauseButton.Enabled = true; transitionButton.Enabled = true; scrubber.Enabled = true; exportButton.Enabled = true; }
public override async void FinishedRecording(AVCaptureFileOutput captureOutput, NSUrl outputFileUrl, NSObject[] connections, NSError error) { if (UIVideo.IsCompatibleWithSavedPhotosAlbum(outputFileUrl.Path)) { var library = new ALAssetsLibrary(); library.WriteVideoToSavedPhotosAlbum(outputFileUrl, async(path, e2) => { if (e2 != null) { new UIAlertView("", e2.ToString(), null, "Error Occurred", null).Show(); } else { view.activityIndicator.StopAnimating(); new UIAlertView("", "Saved to Photos", null, "Ok", null).Show(); //by using messaging center we can send data to portable CameraPage NSData data = NSData.FromUrl(outputFileUrl); byte[] dataBytes = new byte[data.Length]; System.Runtime.InteropServices.Marshal.Copy(data.Bytes, dataBytes, 0, Convert.ToInt32(data.Length)); MessagingCenter.Send <string, byte[]>("VideoByteArrayReady", "ByteArrayIsReady", dataBytes); MessagingCenter.Send <string, string>("VideoPathReady", "VideoPathReady", outputFileUrl.AbsoluteString); await(element as CameraPage).Navigation.PopAsync(); } }); } else { new UIAlertView("Incompatible", "Incompatible", null, "Ok", null).Show(); } }
public async Task <int> DownloadHomepageAsync() { try { var httpClient = new HttpClient(); Task <string> contentsTask = httpClient.GetStringAsync("http://xamarin.com"); string contents = await contentsTask; int length = contents.Length; ResultTextView.Text += "Downloaded the html and found out the length.\n\n"; byte[] imageBytes = await httpClient.GetByteArrayAsync("http://xamarin.com/images/about/team.jpg"); SaveBytesToFile(imageBytes, "team.jpg"); ResultTextView.Text += "Downloaded the image.\n"; DownloadedImageView.Image = UIImage.FromFile(localPath); ALAssetsLibrary library = new ALAssetsLibrary(); var dict = new NSDictionary(); var assetUrl = await library.WriteImageToSavedPhotosAlbumAsync (DownloadedImageView.Image.CGImage, dict); ResultTextView.Text += "Saved to album assetUrl = " + assetUrl + "\n"; ResultTextView.Text += "\n\n\n" + contents; // just dump the entire HTML return(length); } catch { // do something with error return(-1); } }
public async Task<int> DownloadHomepageAsync() { try { var httpClient = new HttpClient(); Task<string> contentsTask = httpClient.GetStringAsync("http://xamarin.com"); string contents = await contentsTask; int length = contents.Length; ResultTextView.Text += "Downloaded the html and found out the length.\n\n"; byte[] imageBytes = await httpClient.GetByteArrayAsync("http://xamarin.com/images/about/team.jpg"); await SaveBytesToFileAsync(imageBytes, "team.jpg"); ResultTextView.Text += "Downloaded the image.\n"; ResultTextView.Text += "Save the image to a file." + Environment.NewLine; DownloadedImageView.Image = UIImage.FromFile(localPath); ALAssetsLibrary library = new ALAssetsLibrary(); var dict = new NSDictionary(); var assetUrl = await library.WriteImageToSavedPhotosAlbumAsync (DownloadedImageView.Image.CGImage, dict); ResultTextView.Text += "Saved to album assetUrl = " + assetUrl + "\n"; ResultTextView.Text += "\n\n\n" + contents; // just dump the entire HTML return length; } catch { // do something with error return -1; } }
//needed for sharing to Facebook public Task <OperationResult <string> > LegacySaveVideo(string videoPath) { var tcs = new TaskCompletionSource <OperationResult <string> >(); if (string.IsNullOrEmpty(videoPath) || !File.Exists(videoPath)) { tcs.SetResult(OperationResult <string> .AsFailure("Invalid video file path specified")); return(tcs.Task); } var url = NSUrl.CreateFileUrl(videoPath, false, null); var library = new ALAssetsLibrary(); library.WriteVideoToSavedPhotosAlbum(url, (resultUrl, error) => { if (error == null) { tcs.SetResult(OperationResult <string> .AsSuccess(resultUrl.AbsoluteString)); } else { tcs.SetResult(OperationResult <string> .AsFailure(error.LocalizedDescription)); } }); return(tcs.Task); }
public async Task <Stream> CaptureImage() { var connection = outputSession.Connections[0]; var sampleBuffer = await outputSession.CaptureStillImageTaskAsync(connection); var imageData = AVCaptureStillImageOutput.JpegStillToNSData(sampleBuffer); byte[] dataBytes = new byte[imageData.Length]; System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, dataBytes, 0, Convert.ToInt32(imageData.Length)); var image = CIImage.FromData(imageData); var metadata = image.Properties.Dictionary.MutableCopy() as NSMutableDictionary; ALAssetsLibrary library = new ALAssetsLibrary(); library.WriteImageToSavedPhotosAlbum(imageData, metadata, (assetUrl, error) => { if (error == null) { Console.WriteLine("assetUrl:" + assetUrl); } else { Console.WriteLine(error); } }); return(new MemoryStream(dataBytes)); }
private async Task <MediaFile> GetMovieMediaFile(NSDictionary info) { var url = info[UIImagePickerController.MediaURL] as NSUrl; if (url == null) { return(null); } var path = GetOutputPath(MediaImplementation.TypeMovie, options?.Directory ?? ((IsCaptured) ? string.Empty : "temp"), options?.Name ?? Path.GetFileName(url.Path), url.PathExtension); try { File.Move(url.Path, path); } catch (Exception ex) { Debug.WriteLine($"Unable to move file, trying to copy. {ex.Message}"); try { File.Copy(url.Path, path); File.Delete(url.Path); } catch (Exception) { Debug.WriteLine($"Unable to copy/delete file, will be left around :( {ex.Message}"); } } string aPath = null; if (source != UIImagePickerControllerSourceType.Camera) { //try to get the album path's url var url2 = info[UIImagePickerController.ReferenceUrl] as NSUrl; aPath = url2?.AbsoluteString; } else { if (options?.SaveToAlbum ?? false) { try { var library = new ALAssetsLibrary(); var albumSave = await library.WriteVideoToSavedPhotosAlbumAsync(new NSUrl(path)); aPath = albumSave.AbsoluteString; } catch (Exception ex) { Console.WriteLine("unable to save to album:" + ex); } } } return(new MediaFile(path, () => File.OpenRead(path), albumPath: aPath)); }
public void SavePictureToLibrary(byte[] imgData) { ALAssetsLibrary library = new ALAssetsLibrary(); library.WriteImageToSavedPhotosAlbum(imgData.ToImage().CGImage, new NSDictionary(), (assetUrl, error) => { Console.WriteLine("assetUrl:" + assetUrl); }); }
public void SaveFileToPhotosAlbum(string filePath, byte[] fileData) { string ext = Path.GetExtension(filePath); if (ext.ToUpper() == ".MOV" || ext.ToUpper() == ".M4V") { File.WriteAllBytes(filePath, fileData); if (UIVideo.IsCompatibleWithSavedPhotosAlbum(filePath)) { UIVideo.SaveToPhotosAlbum(filePath, (path, error) => { if (error == null) { if (FileSavedToPhotosAlbum != null) { FileSavedToPhotosAlbum(this, new FilesSavedToPhotosAlbumArgs(path, path)); } } else { Console.Out.WriteLine("Video {0} cannot be saved to photos album!", filePath); } }); } } else if (ext.ToUpper() == ".JPEG" || ext.ToUpper() == ".JPG" || ext.ToUpper() == ".PNG") { NSData imgData = NSData.FromArray(fileData); var img = UIImage.LoadFromData(imgData); var meta = new NSDictionary(); ALAssetsLibrary library = new ALAssetsLibrary(); library.WriteImageToSavedPhotosAlbum(img.CGImage, meta, (assetUrl, error) => { if (error == null) { if (FileSavedToPhotosAlbum != null) { FileSavedToPhotosAlbum(this, new FilesSavedToPhotosAlbumArgs(assetUrl.ToString(), filePath)); } else { Console.Out.WriteLine("Image {0} cannot be saved to photos album!", filePath); } } }); img.Dispose(); } else { File.WriteAllBytes(filePath, fileData); if (FileSavedToPhotosAlbum != null) { FileSavedToPhotosAlbum(this, new FilesSavedToPhotosAlbumArgs(filePath, filePath)); } } }
void ShowActualPhotoPermissionAlert() { ALAssetsLibrary library = new ALAssetsLibrary(); library.Enumerate(ALAssetsGroupType.SavedPhotos, HandleALAssetsLibraryGroupsEnumerationResults, delegate(NSError obj) { FirePhotoPermissionCompletionHandler(); }); }
public PictureViewCell(CGRect frame) : base(frame) { _assetLib = new ALAssetsLibrary(); _imageView = new UIImageView(Bounds); _imageView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; _imageView.ContentMode = UIViewContentMode.ScaleToFill; _imageView.ClipsToBounds = true; _imageView.Layer.EdgeAntialiasingMask = CAEdgeAntialiasingMask.LeftEdge | CAEdgeAntialiasingMask.RightEdge | CAEdgeAntialiasingMask.BottomEdge | CAEdgeAntialiasingMask.TopEdge; ContentView.AddSubview(_imageView); }
public override void ViewDidLoad () { base.ViewDidLoad (); Title = "Save to Album"; View.BackgroundColor = UIColor.White; cameraButton = UIButton.FromType (UIButtonType.RoundedRect); cameraButton.Frame = new CGRect(10, 20, 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; } }
protected void Handle_FinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs e) { bool isImage = false; switch (e.Info[UIImagePickerController.MediaType].ToString()) { case "public.image": isImage = true; break; case "public.video": break; } // get common info (shared between images and video) NSUrl referenceURL = e.Info[new NSString("UIImagePickerControllerReferenceURL")] as NSUrl; fileName = null; ALAssetsLibrary assetsLibrary = new ALAssetsLibrary(); assetsLibrary.AssetForUrl(referenceURL, delegate(ALAsset asset) { ALAssetRepresentation representation = asset.DefaultRepresentation; if (representation == null) { return; } else { fileName = representation.Filename.ToLower(); } }, delegate(NSError error) {}); if (isImage) { UIImage originalImage = e.Info[UIImagePickerController.OriginalImage] as UIImage; if (originalImage != null) { profileImageView.Image = originalImage; fileName = "1.jpg"; Update(true); } } else { NSUrl mediaURL = e.Info[UIImagePickerController.MediaURL] as NSUrl; if (mediaURL != null) { Console.WriteLine(mediaURL.ToString()); } } imagePicker.DismissModalViewController(true); }
public async Task<bool> Download(string uri, string filename) { try { string downloadPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string downloadFilePath = Path.Combine(downloadPath, filename); if (System.IO.File.Exists(downloadFilePath)) { PlayVideo( downloadFilePath ); return true; } webClient = new WebClient(); webClient.DownloadDataCompleted += async (s, e) => { if( e.Cancelled ) { BTProgressHUD.Dismiss(); webClient.Dispose(); return; } var bytes = e.Result; // get the downloaded data string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string localFilename = filename; string localPath = Path.Combine(documentsPath, localFilename); File.WriteAllBytes(localPath, bytes); // writes to local storage ALAssetsLibrary videoLibrary = new ALAssetsLibrary(); await videoLibrary.WriteVideoToSavedPhotosAlbumAsync( new Foundation.NSUrl( localPath )); BTProgressHUD.Dismiss(); PlayVideo( localPath ); webClient.Dispose(); }; BTProgressHUD.Show("cancel", OnCancelDownload, "Downloading Media....",-1, ProgressHUD.MaskType.Black ); var url = new Uri(uri); webClient.DownloadDataAsync(url); return true; } catch( Exception ex ) { return false; } }
public override void ViewDidLoad() { base.ViewDidLoad(); Title = "All Asset Groups"; // instantiate a reference to the shared assets library assetsLibrary = new ALAssetsLibrary(); // enumerate the photo albums assetsLibrary.Enumerate(ALAssetsGroupType.All, GroupsEnumerator, (NSError e) => { Console.WriteLine("Could not enumerate albums: " + e.LocalizedDescription); }); }
public override void ViewDidLoad() { base.ViewDidLoad (); Title = "All Asset Groups"; // instantiate a reference to the shared assets library assetsLibrary = new ALAssetsLibrary(); // enumerate the photo albums assetsLibrary.Enumerate(ALAssetsGroupType.All, GroupsEnumerator, (NSError e) => { Console.WriteLine ("Could not enumerate albums: " + e.LocalizedDescription); }); }
public override void ViewDidLoad() { base.ViewDidLoad(); Title = "Save to Album"; View.BackgroundColor = UIColor.White; cameraButton = UIButton.FromType(UIButtonType.RoundedRect); cameraButton.Frame = new CGRect(10, 20, 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; } }
public void CaptureVideo(string date, Action Ready) { var picker = new MediaPicker(); picker.TakeVideoAsync(new StoreVideoOptions { Name = date + ".mp4", Directory = "TemporaryFiles" }).ContinueWith(t => { ALAssetsLibrary library = new ALAssetsLibrary(); library.WriteVideoToSavedPhotosAlbum(new NSUrl(t.Result.Path), (assetUrl, error) => {}); SaveFileToMedialibrary(t.Result, ".mp4", () => Ready()); }, TaskScheduler.FromCurrentSynchronizationContext()); }
static NSUrl fetchMovieUrl() { NSUrl movieURL = null; var waitHandle = new AutoResetEvent(false); ThreadPool.QueueUserWorkItem(_ => { ALAssetsLibrary assetsLibrary = new ALAssetsLibrary(); assetsLibrary.Enumerate(ALAssetsGroupType.All, (ALAssetsGroup group, ref bool stop) => { if (group == null) { waitHandle.Set(); return; } NSDate latest = NSDate.FromTimeIntervalSince1970(0); group.Enumerate((ALAsset result, nint index, ref bool stopGroup) => { if (result == null || result.AssetType != ALAssetType.Video) { return; } NSUrl url = result.DefaultRepresentation.Url; if (url == null) { return; } var diff = result.Date.SecondsSinceReferenceDate - latest.SecondsSinceReferenceDate; if (diff > 0) { latest = result.Date; movieURL = url; } }); stop = movieURL != null; }, (error) => { waitHandle.Set(); }); }); waitHandle.WaitOne(); if (movieURL == null) { UIAlertView alertView = new UIAlertView(null, "Could not find any movies in assets library to use as sample content.", null, "OK", null); alertView.Show(); } return(movieURL); }
private void BuildFileAttachment(UIImagePickerMediaPickedEventArgs media) { string name = ""; // Build attachment and show in view NSUrl referenceURL = media.Info[new NSString("UIImagePickerControllerReferenceURL")] as NSUrl; if (referenceURL != null) { ALAssetsLibrary assetsLibrary = new ALAssetsLibrary(); assetsLibrary.AssetForUrl(referenceURL, delegate(ALAsset asset) { ALAssetRepresentation representation = asset.DefaultRepresentation; if (representation != null) { name = representation.Filename; } string nameFile = name.Length > 0 ? name : "Archivo Adjunto " + (AttachmentFilesInMemory.Count + 1).ToString(); AttachmentFile attachmentFile = new AttachmentFile(); attachmentFile.FileName = nameFile; attachmentFile.Private = privateFile; // Get image and convert to BytesArray UIImage originalImage = media.Info[UIImagePickerController.OriginalImage] as UIImage; if (originalImage != null) { string extension = referenceURL.PathExtension; using (NSData imageData = originalImage.AsJPEG(0.5f)) { Byte[] fileByteArray = new Byte[imageData.Length]; Marshal.Copy(imageData.Bytes, fileByteArray, 0, Convert.ToInt32(imageData.Length)); attachmentFile.BytesArray = fileByteArray; } } AttachmentFilesInMemory.Add(attachmentFile); // Show file selected in view LoadAttachmentsOfEvent(); }, delegate(NSError error) { return; }); } }
private async Task <MediaFile> GetPictureMediaFile(NSDictionary info) { var image = (UIImage)info[UIImagePickerController.EditedImage]; if (image == null) { image = (UIImage)info[UIImagePickerController.OriginalImage]; } var meta = info[UIImagePickerController.MediaMetadata] as NSDictionary; string path = GetOutputPath(MediaImplementation.TypeImage, options.Directory ?? ((IsCaptured) ? String.Empty : "temp"), options.Name); using (FileStream fs = File.OpenWrite(path)) using (Stream s = new NSDataStream(image.AsJPEG())) { s.CopyTo(fs); fs.Flush(); } Action <bool> dispose = null; string aPath = null; if (source != UIImagePickerControllerSourceType.Camera) { dispose = d => File.Delete(path); } else { if (this.options.SaveToAlbum) { try { var library = new ALAssetsLibrary(); var albumSave = await library.WriteImageToSavedPhotosAlbumAsync(image.CGImage, meta); aPath = albumSave.AbsoluteString; } catch (Exception ex) { Console.WriteLine("unable to save to album:" + ex); } } } return(new MediaFile(path, () => File.OpenRead(path), dispose: dispose, albumPath: aPath)); }
async partial void OnTakePhoto(UIBarButtonItem sender) { sender.Enabled = false; if (movieWriter == null) { // get new file path var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var pathToMovie = Path.Combine(documents, "Movie.m4v"); if (File.Exists(pathToMovie)) { File.Delete(pathToMovie); } movieUrl = new NSUrl(pathToMovie, false); // start recording video movieWriter = new GPUImageMovieWriter(movieUrl, new CGSize(480, 640)); movieWriter.EncodingLiveVideo = true; sepiaFilter.AddTarget(movieWriter); videoCamera.AudioEncodingTarget = movieWriter; movieWriter.StartRecording(); Console.WriteLine("Video recording started."); } else { // stop recording video sepiaFilter.RemoveTarget(movieWriter); videoCamera.AudioEncodingTarget = null; await movieWriter.FinishRecordingAsync(); // save to library var library = new ALAssetsLibrary(); try { var assetURL = await library.WriteVideoToSavedPhotosAlbumAsync(movieUrl); Console.WriteLine("Video saved: " + assetURL); } catch (Exception ex) { Console.WriteLine("Video save error: " + ex); } movieWriter = null; movieUrl = null; Console.WriteLine("Video recording completed."); } sender.Enabled = true; }
public override void ViewDidLoad() { base.ViewDidLoad(); NavigationItem.Title = "Loading..."; var cancelButton = new UIBarButtonItem(UIBarButtonSystemItem.Cancel /*, cancelImagePicker*/); cancelButton.Clicked += CancelClicked; NavigationItem.RightBarButtonItem = cancelButton; AssetGroups.Clear(); Library = new ALAssetsLibrary(); Library.Enumerate(ALAssetsGroupType.All, GroupsEnumerator, GroupsEnumeratorFailed); }
public override void ViewDidLoad() { base.ViewDidLoad(); NavigationItem.Title = NSBundle.MainBundle.LocalizedString("Loading", "Loading..."); var cancelButton = new UIBarButtonItem(UIBarButtonSystemItem.Cancel); cancelButton.Clicked += CancelClicked; NavigationItem.RightBarButtonItem = cancelButton; AssetGroups.Clear(); Library = new ALAssetsLibrary(); Library.Enumerate(ALAssetsGroupType.All, GroupsEnumerator, GroupsEnumeratorFailed); }
public Task <IList <Picture> > LoadImagesAsync() { taskCompletionSource = new TaskCompletionSource <IList <Picture> >(); //Clean the mess pictures.Clear(); var library = new ALAssetsLibrary(); library.Enumerate(ALAssetsGroupType.All, GroupEnumerator, (NSError e) => { Console.WriteLine("Could not enumerate albums: " + e.LocalizedDescription); } ); return(taskCompletionSource.Task); }
void ReadAssetStore() { assetsLibrary = new ALAssetsLibrary(); assetsLibrary.EnumerateGroups( (uint)ALAssetsLibraryTypesofAsset.Album, delegate(ALAssetsGroup group, bool stop){ // enumeration block, when group is null, there's no more if ( group == null ) return; var str = group.Value (ALAssetsGroup.PropertyName); Debug.Log ("Album Name: " + str); }, delegate(U3DXT.iOS.Native.Foundation.NSError error){ // error block } ); }
public void SaveImageToLibrary(string fileName, byte[] imageData) { try { var nsData = NSData.FromArray(imageData); var uiImage = UIImage.LoadFromData(nsData); var library = new ALAssetsLibrary(); library.WriteImageToSavedPhotosAlbum(uiImage.CGImage, new NSDictionary(), (assetUrl, error) => { Console.WriteLine("assetUrl:" + assetUrl); }); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private async Task <ALAssetRepresentation> GetAssetDefaultRepAsync(string path) { // get the default representation of the asset var library = new ALAssetsLibrary(); var dRepTCS = new TaskCompletionSource <ALAssetRepresentation>(); using (var assetUrl = new NSUrl(path)) { library.AssetForUrl(assetUrl, asset => dRepTCS.SetResult(asset.DefaultRepresentation), error => dRepTCS.SetException(new Exception(error.LocalizedFailureReason))); } var rep = await dRepTCS.Task.ConfigureAwait(false); return(rep); }
private void _setupOutputs() { if (stillImageOutput == null) { stillImageOutput = new AVCaptureStillImageOutput(); } if (movieOutput == null) { movieOutput = new AVCaptureMovieFileOutput(); movieOutput.MovieFragmentInterval = CMTime.Invalid; } if (library == null) { library = new ALAssetsLibrary(); } }
public override void ViewDidLoad() { base.ViewDidLoad(); var loading = string.IsNullOrWhiteSpace(LoadingTitle) ? NSBundle.MainBundle.GetLocalizedString("Loading", "Loading...") : LoadingTitle; NavigationItem.Title = loading; var cancelButton = new UIBarButtonItem(UIBarButtonSystemItem.Cancel); cancelButton.Clicked += CancelClicked; NavigationItem.RightBarButtonItem = cancelButton; assetGroups.Clear(); library = new ALAssetsLibrary(); library.Enumerate(ALAssetsGroupType.All, GroupsEnumerator, GroupsEnumeratorFailed); }
public static async Task ShareFacebook(UIViewController controller, Post post) { var dialog = new ShareDialog(); dialog.FromViewController = controller; dialog.Mode = ShareDialogMode.Automatic; if (post.Links.Any()) { var content = new ShareLinkContent(); content.SetContentUrl(new NSUrl(post.Links.FirstOrDefault().LinkUrl)); dialog.SetShareContent(content); } if (post.Images.Any()) { var content = new SharePhotoContent(); var path = await DownloadFileIfNecessary(post.Images.FirstOrDefault().Url); content.Photos = new SharePhoto[1] { SharePhoto.From(UIImage.FromFile(path), true) }; dialog.SetShareContent(content); } if (post.Videos.Any()) { var path = await DownloadFileIfNecessary(post.Videos.FirstOrDefault().Url); ALAssetsLibrary library = new ALAssetsLibrary(); library.WriteVideoToSavedPhotosAlbum(NSUrl.FromFilename(path), (arg1, arg2) => { controller.InvokeOnMainThread(() => { var content = new ShareVideoContent(); content.Video = ShareVideo.From(arg1.AbsoluteUrl); dialog.SetShareContent(content); dialog.Show(); }); }); } NSError error = new NSError(); dialog.ValidateWithError(out error); var result = dialog.Show(); }
//AlAssetsGroupSavedPhotos public void InitializePhotos() { assetsLibrary = new ALAssetsLibrary(); currentPhotoIndex = -1; photoAssets = new List <ALAsset> (PHOTO_ASSETS_CAPACITY); int photoIndex = 0; bool syncContentController = true; assetsLibrary.Enumerate(ALAssetsGroupType.Album, (ALAssetsGroup group, ref bool stop) => { if (group != null) { string groupName = group.Name; if (groupName.StartsWith(PNALBUM_PREFIX)) { group.SetAssetsFilter(ALAssetsFilter.AllPhotos); group.Enumerate((ALAsset asset, int index, ref bool st) => { int notfound = Int32.MaxValue; if (asset != null && index != notfound) { photoAssets.Add(asset); photoIndex++; currentPhotoIndex = 0; } if (photoIndex == PHOTO_ASSETS_CAPACITY) { st = true; } }); } } if (syncContentController) { syncContentController = false; DispatchQueue.MainQueue.DispatchAsync(() => { if (currentPhotoIndex == 0) { setCurrentPhotoToIndex(0); } ((PhotoViewController)(ViewController.contentController)).Synchronize(currentPhotoIndex >= 0); }); } }, (NSError error) => { Console.WriteLine("User denied access to photo Library... {0}", error); }); }
//AlAssetsGroupSavedPhotos public void InitializePhotos () { assetsLibrary = new ALAssetsLibrary (); currentPhotoIndex = -1; photoAssets = new List<ALAsset> (PHOTO_ASSETS_CAPACITY); int photoIndex = 0; bool syncContentController = true; assetsLibrary.Enumerate (ALAssetsGroupType.Album, ( ALAssetsGroup group, ref bool stop) => { if (group != null) { string groupName = group.Name; if (groupName.StartsWith (PNALBUM_PREFIX)) { group.SetAssetsFilter (ALAssetsFilter.AllPhotos); group.Enumerate ((ALAsset asset, nint index, ref bool st) => { int notfound = Int32.MaxValue; if (asset != null && index != notfound) { photoAssets.Add (asset); photoIndex++; currentPhotoIndex = 0; } if (photoIndex == PHOTO_ASSETS_CAPACITY) { st = true; } }); } } if (syncContentController) { syncContentController = false; DispatchQueue.MainQueue.DispatchAsync (() => { if (currentPhotoIndex == 0) { setCurrentPhotoToIndex (0); } ((PhotoViewController)(ViewController.contentController)).Synchronize (currentPhotoIndex >= 0); }); } }, (NSError error) => { Console.WriteLine ("User denied access to photo Library... {0}", error); }); }
public void DownloadHomepage() { var webClient = new WebClient(); webClient.DownloadStringCompleted += (sender, e) => { if(e.Cancelled || e.Error != null) { // do something with error } string contents = e.Result; int length = contents.Length; InvokeOnMainThread (() => { ResultTextView.Text += "Downloaded the html and found out the length.\n\n"; }); webClient.DownloadDataCompleted += (sender1, e1) => { if(e1.Cancelled || e1.Error != null) { // do something with error } SaveBytesToFile(e1.Result, "team.jpg"); InvokeOnMainThread (() => { ResultTextView.Text += "Downloaded the image.\n"; DownloadedImageView.Image = UIImage.FromFile (localPath); }); ALAssetsLibrary library = new ALAssetsLibrary(); var dict = new NSDictionary(); library.WriteImageToSavedPhotosAlbum (DownloadedImageView.Image.CGImage, dict, (s2,e2) => { InvokeOnMainThread (() => { ResultTextView.Text += "Saved to album assetUrl\n"; }); if (downloaded != null) downloaded(length); }); }; webClient.DownloadDataAsync(new Uri("http://xamarin.com/images/about/team.jpg")); }; webClient.DownloadStringAsync(new Uri("http://xamarin.com/")); }
void exportCompleted (AVAssetExportSession session) { exportProgressView.Hidden = true; currentTimeLabel.Hidden = false; var outputUrl = session.OutputUrl; progressTimer.Invalidate (); progressTimer = null; if (session.Status != AVAssetExportSessionStatus.Completed) { Console.WriteLine ("exportSession error:{0}", session.Error.LocalizedDescription); reportError (session.Error); return; } exportProgressView.Progress = 1f; var library = new ALAssetsLibrary (); library.WriteVideoToSavedPhotosAlbum (outputUrl, (assetURL, error) => { if (error != null) { Console.WriteLine ("writeVideoToAssetsLibrary failed: {0}", error.LocalizedDescription); reportError (error); } }); Player.Play (); playPauseButton.Enabled = true; transitionButton.Enabled = true; scrubber.Enabled = true; exportButton.Enabled = true; }
private void ReshareData() { if (rootDVC.View.ViewWithTag(CANCEL_BUTTON_TAG) != null) { rootDVC.View.ViewWithTag(CANCEL_BUTTON_TAG).RemoveFromSuperview(); } UpdateSecretsViewLabel(WELCOME_LABEL_TEXT); switch (ResharedItemType) { case FileType.Photo: ALAssetsLibrary library = new ALAssetsLibrary (); library.AssetForUrl (new NSUrl (ResharedItem.Data), (asset) => { if (asset != null) { UIImage image = UIImage.FromImage (asset.DefaultRepresentation.GetImage()); UploadMedia (image, NSUrl.FromFilename(ResharedItem.ItemPath), null); ResharedItem = null; } else { Console.Out.WriteLine ("Asset is null."); } }, (failureError) => { if (failureError != null) { Console.Out.WriteLine ("Error: " + failureError.LocalizedDescription); } } ); break; case FileType.Video: case FileType.Other: var fileUrl = NSUrl.FromFilename (ResharedItem.Data); UploadMedia(null, fileUrl, fileUrl); ResharedItem = null; break; default: Console.Out.WriteLine ("Error: Resharing file type is not set"); break; } }
private void OpenFile(string filePath, DataItem item) { var sbounds = UIScreen.MainScreen.Bounds; string ext = UrlHelper.GetExtension(filePath); if (ext.ToUpper () == ".MOV" || ext.ToUpper () == ".M4V") { var movieController = new AdvancedUIViewController (); moviePlayer = new MPMoviePlayerController (NSUrl.FromFilename (filePath)); moviePlayer.View.Frame = new RectangleF ( sbounds.X, sbounds.Y - 20, sbounds.Width, sbounds.Height - 30 ); moviePlayer.ControlStyle = MPMovieControlStyle.Fullscreen; moviePlayer.View.AutoresizingMask = (UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight); moviePlayer.ShouldAutoplay = true; moviePlayer.PrepareToPlay (); moviePlayer.Play (); var btnClose = UIButton.FromType (UIButtonType.RoundedRect); btnClose.Frame = new RectangleF (3, 7, 60, 30); btnClose.SetTitle ("Close", UIControlState.Normal); btnClose.SetTitleColor (UIColor.Black, UIControlState.Normal); btnClose.TouchDown += delegate { movieController.DismissModalViewControllerAnimated (true); }; var btnShare = UIButton.FromType (UIButtonType.RoundedRect); btnShare.Frame = new RectangleF ( (sbounds.Width / 2) - 50, sbounds.Height - 50, 100, 30 ); btnShare.SetTitle ("Share", UIControlState.Normal); btnShare.SetTitleColor (UIColor.Black, UIControlState.Normal); btnShare.TouchDown += delegate { ResharedItem = item; ResharedItemType = FileType.Video; ShowSecretsView(); }; movieController.View.AddSubview (moviePlayer.View); movieController.View.AddSubview (btnClose); movieController.View.AddSubview (btnShare); navigation.PresentModalViewController (movieController, true); } else if (ext.ToUpper () == ".JPEG" || ext.ToUpper () == ".JPG" || ext.ToUpper () == ".PNG") { ALAssetsLibrary library = new ALAssetsLibrary (); library.AssetForUrl (new NSUrl (filePath), (asset) => { if (asset != null) { var imageController = new AdvancedUIViewController (); var image = UIImage.FromImage (asset.DefaultRepresentation.GetFullScreenImage ()); var imageView = new UIImageView (image); imageView.Frame = sbounds; imageView.UserInteractionEnabled = true; imageView.ClipsToBounds = true; imageView.ContentMode = UIViewContentMode.ScaleAspectFit; var btnClose = UIButton.FromType (UIButtonType.RoundedRect); btnClose.Frame = new RectangleF ( (sbounds.Width / 2) - 50, 20, 100, 30 ); btnClose.SetTitle ("Close", UIControlState.Normal); btnClose.SetTitleColor (UIColor.Black, UIControlState.Normal); btnClose.TouchDown += delegate { imageController.DismissModalViewControllerAnimated (true); }; var btnShare = UIButton.FromType (UIButtonType.RoundedRect); btnShare.Frame = new RectangleF ( (sbounds.Width / 2) - 50, sbounds.Height - 60, 100, 30 ); btnShare.SetTitle ("Share", UIControlState.Normal); btnShare.SetTitleColor (UIColor.Black, UIControlState.Normal); btnShare.TouchDown += delegate { ResharedItem = item; ResharedItemType = FileType.Photo; ShowSecretsView(); }; var scrollView = new UIScrollView (sbounds); scrollView.ClipsToBounds = true; scrollView.ContentSize = sbounds.Size; scrollView.BackgroundColor = UIColor.Gray; scrollView.MinimumZoomScale = 1.0f; scrollView.MaximumZoomScale = 3.0f; scrollView.MultipleTouchEnabled = true; scrollView.AutoresizingMask = (UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight); scrollView.ViewForZoomingInScrollView = delegate(UIScrollView sv) { return imageView; }; scrollView.AddSubview (imageView); imageController.View.AddSubview (scrollView); imageController.View.AddSubview (btnClose); imageController.View.AddSubview (btnShare); navigation.PresentModalViewController (imageController, true); } else { Console.Out.WriteLine ("Asset is null."); } }, (error) => { if (error != null) { Console.Out.WriteLine ("Error: " + error.LocalizedDescription); } } ); } else { var btnShare = UIButton.FromType (UIButtonType.RoundedRect); btnShare.Frame = new RectangleF ( (sbounds.Width / 2) - 50, sbounds.Height - 50, 100, 30 ); btnShare.SetTitle ("Share", UIControlState.Normal); btnShare.SetTitleColor (UIColor.Black, UIControlState.Normal); btnShare.Tag = SHARE_BUTTON_TAG; btnShare.TouchDown += delegate { ResharedItem = item; ResharedItemType = FileType.Other; ShowSecretsView(); }; navigation.Add(btnShare); interactionControllerDelegate = new UIDocumentInteractionControllerDelegateClass(navigation); interactionController = UIDocumentInteractionController.FromUrl(NSUrl.FromFilename(filePath)); interactionController.Delegate = interactionControllerDelegate; InvokeOnMainThread(delegate { interactionController.PresentPreview(true); }); } }
/// <summary> /// Saves the movie to the camera roll. /// </summary> void SaveMovieToCameraRoll () { //Console.WriteLine ("Save movie to camera roll"); using (var library = new ALAssetsLibrary ()) { library.WriteVideoToSavedPhotosAlbum (movieURL, (assetUrl, error) => { if (error != null) ShowError (error); else RemoveFile (movieURL); movieWritingQueue.DispatchAsync (() => { recordingWillBeStopped = false; IsRecording = false; if (RecordingDidStop != null) RecordingDidStop (); }); }); } }
public override void ViewDidLoad () { base.ViewDidLoad (); Title = "Color Controls Pro"; View.BackgroundColor = UIColor.White; cameraButton = UIButton.FromType (UIButtonType.RoundedRect); cameraButton.Frame = new CGRect(10, 60, 90,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; sourceImage = photo; displayImage = sourceImage.Scale(new CGSize(300, 200)); imageView.Image = displayImage; sourceMeta = meta; }); }; View.Add (cameraButton); resetButton = UIButton.FromType (UIButtonType.RoundedRect); resetButton.Frame = new CGRect(110, 60, 90, 40); resetButton.SetTitle ("Reset", UIControlState.Normal); resetButton.TouchUpInside += (sender, e) => { sliderS.Value = 1; sliderB.Value = 0; sliderC.Value = 1; HandleValueChanged (sender, e); }; View.Add (resetButton); saveButton = UIButton.FromType (UIButtonType.RoundedRect); saveButton.Frame = new CGRect(210, 60, 90, 40); saveButton.SetTitle ("Save", UIControlState.Normal); saveButton.TouchUpInside += (sender, e) => { ALAssetsLibrary library = new ALAssetsLibrary(); var img = AdjustImage (sourceImage); if (sourceMeta == null) sourceMeta = new NSDictionary(); // when using 'clouds.jpg' library.WriteImageToSavedPhotosAlbum (img.CGImage, sourceMeta, (assetUrl, error) => { Console.WriteLine ("SAVED TO assetUrl:"+assetUrl); new UIAlertView("Saved", "Photo saved to Camera Roll", null, "OK", null).Show (); }); }; View.Add (saveButton); labelC = new UILabel(new CGRect(10, 120, 90, 20)); labelS = new UILabel(new CGRect(10, 160, 90, 20)); labelB = new UILabel(new CGRect(10, 200, 90, 20)); labelC.Text = "Contrast"; labelS.Text = "Saturation"; labelB.Text = "Brightness"; View.Add (labelC); View.Add (labelS); View.Add (labelB); sliderB = new UISlider(new CGRect(100, 120, 210, 20)); sliderS = new UISlider(new CGRect(100, 160, 210, 20)); sliderC = new UISlider(new CGRect(100, 200, 210, 20)); // http://developer.apple.com/library/mac/#documentation/graphicsimaging/reference/CoreImageFilterReference/Reference/reference.html#//apple_ref/doc/filter/ci/CIColorControls sliderS.MinValue = 0; sliderS.MaxValue = 2; sliderS.Value = 1; sliderB.MinValue = -1; sliderB.MaxValue = 1; sliderB.Value = 0; sliderC.MinValue = 0; sliderC.MaxValue = 4; sliderC.Value = 1; sliderC.TouchUpInside += HandleValueChanged; sliderS.TouchUpInside += HandleValueChanged; sliderB.TouchUpInside += HandleValueChanged; View.Add (sliderC); View.Add (sliderS); View.Add (sliderB); imageView = new UIImageView(new CGRect(10, 240, 300, 200)); sourceImage = UIImage.FromFile ("clouds.jpg"); displayImage = sourceImage; imageView.Image = displayImage; View.Add (imageView); if (!UIImagePickerController.IsSourceTypeAvailable (UIImagePickerControllerSourceType.Camera)) { cameraButton.SetTitle ("No camera", UIControlState.Disabled); cameraButton.SetTitleColor (UIColor.Gray, UIControlState.Disabled); cameraButton.Enabled = false; } }
private async Task<ALAssetRepresentation> GetAssetDefaultRepAsync(string path) { // get the default representation of the asset var library = new ALAssetsLibrary(); var dRepTCS = new TaskCompletionSource<ALAssetRepresentation>(); using (var assetUrl = new NSUrl(path)) { library.AssetForUrl(assetUrl, asset => dRepTCS.SetResult(asset.DefaultRepresentation), error => dRepTCS.SetException(new Exception(error.LocalizedFailureReason))); } var rep = await dRepTCS.Task.ConfigureAwait(false); return rep; }
void ShowActualPhotoPermissionAlert() { ALAssetsLibrary library = new ALAssetsLibrary (); library.Enumerate (ALAssetsGroupType.SavedPhotos, HandleALAssetsLibraryGroupsEnumerationResults, delegate (NSError obj) { FirePhotoPermissionCompletionHandler (); }); }
public async Task<int> DownloadHomepageAsync() { try { var httpClient = new HttpClient(); // Xamarin supports HttpClient! // // download HTML string Task<string> contentsTask = httpClient.GetStringAsync("http://xamarin.com"); // async method! ResultTextView.Text += "DownloadHomepage method continues after Async() call, until await is used\n"; // await! control returns to the caller and the task continues to run on another thread string contents = await contentsTask; // After contentTask completes, you can calculate the length of the string. int length = contents.Length; ResultTextView.Text += "Downloaded the html and found out the length.\n\n"; // // download image bytes ResultTextView.Text += "Start downloading image.\n"; byte[] imageBytes = await httpClient.GetByteArrayAsync("http://xamarin.com/images/about/team.jpg"); // async method! ResultTextView.Text += "Downloaded the image.\n"; await SaveBytesToFileAsync(imageBytes, "team.jpg"); ResultTextView.Text += "Save the image to a file." + Environment.NewLine; DownloadedImageView.Image = UIImage.FromFile(localPath); // // save image to Photo Album using async-ified iOS API ALAssetsLibrary library = new ALAssetsLibrary(); var dict = new NSDictionary(); var assetUrl = await library.WriteImageToSavedPhotosAlbumAsync(DownloadedImageView.Image.CGImage, dict); ResultTextView.Text += "Saved to album assetUrl = " + assetUrl + "\n"; // // download multiple images // http://blogs.msdn.com/b/pfxteam/archive/2012/08/02/processing-tasks-as-they-complete.aspx Task<byte[]> task1 = httpClient.GetByteArrayAsync("http://xamarin.com/images/tour/amazing-ide.png"); // async method! Task<byte[]> task2 = httpClient.GetByteArrayAsync("http://xamarin.com/images/how-it-works/chalkboard2.jpg"); // async method! Task<byte[]> task3 = httpClient.GetByteArrayAsync("http://cdn1.xamarin.com/webimages/images/features/shared-code-2.pngXXX"); // ERROR async method! List<Task<byte[]>> tasks = new List<Task<byte[]>>(); tasks.Add(task1); tasks.Add(task2); tasks.Add(task3); while (tasks.Count > 0) { var t = await Task.WhenAny(tasks); tasks.Remove(t); try { await t; ResultTextView.Text += "** Downloaded " + t.Result.Length + " bytes\n"; } catch (OperationCanceledException) { } catch (Exception exc) { ResultTextView.Text += "-- Download ERROR: " + exc.Message + "\n"; } } // this doesn't happen until the image has downloaded as well ResultTextView.Text += "\n\n\n" + contents; // just dump the entire HTML return length; // Task<TResult> returns an object of type TResult, in this case int } catch (Exception ex) { Console.WriteLine("Centralized exception handling!"); return -1; } }
public void RequestPhotoAccess (bool useImagePicker) { if (useImagePicker) { UIImagePickerController picker = new UIImagePickerController (); picker.Delegate = this; PresentViewController (picker, true, null); } else { if (assetLibrary == null) assetLibrary = new ALAssetsLibrary (); assetLibrary.Enumerate (ALAssetsGroupType.All, delegate { }, delegate { }); } }
public override void ViewDidLoad() { base.ViewDidLoad (); NavigationItem.Title = NSBundle.MainBundle.LocalizedString ("Loading", "Loading..."); var cancelButton = new UIBarButtonItem (UIBarButtonSystemItem.Cancel); cancelButton.Clicked += CancelClicked; NavigationItem.RightBarButtonItem = cancelButton; AssetGroups.Clear (); Library = new ALAssetsLibrary (); Library.Enumerate (ALAssetsGroupType.All, GroupsEnumerator, GroupsEnumeratorFailed); }
private async Task<MediaFile> GetPictureMediaFile(NSDictionary info) { var image = (UIImage)info[UIImagePickerController.EditedImage]; if (image == null) image = (UIImage)info[UIImagePickerController.OriginalImage]; var meta = info[UIImagePickerController.MediaMetadata] as NSDictionary; string path = GetOutputPath(MediaImplementation.TypeImage, options.Directory ?? ((IsCaptured) ? String.Empty : "temp"), options.Name); using (FileStream fs = File.OpenWrite(path)) using (Stream s = new NSDataStream(image.AsJPEG())) { s.CopyTo(fs); fs.Flush(); } Action<bool> dispose = null; string aPath = null; if (source != UIImagePickerControllerSourceType.Camera) dispose = d => File.Delete(path); else { if (this.options.SaveToAlbum) { try { var library = new ALAssetsLibrary(); var albumSave = await library.WriteImageToSavedPhotosAlbumAsync(image.CGImage, meta); aPath = albumSave.AbsoluteString; } catch (Exception ex) { Console.WriteLine("unable to save to album:" + ex); } } } return new MediaFile(path, () => File.OpenRead(path), dispose: dispose, albumPath: aPath); }
protected void MoveFinishedMovieToAlbum() { var lib = new ALAssetsLibrary(); lib.WriteVideoToSavedPhotosAlbum(videoUrl, (o, s) => InfoLabel.BeginInvokeOnMainThread(() => InfoLabel.Text = "Movie saved to Album.")); }
public void SaveFileToPhotosAlbum(string filePath, byte[] fileData) { string ext = Path.GetExtension (filePath); if (ext.ToUpper () == ".MOV" || ext.ToUpper () == ".M4V") { File.WriteAllBytes (filePath, fileData); if (UIVideo.IsCompatibleWithSavedPhotosAlbum(filePath)) { UIVideo.SaveToPhotosAlbum(filePath, (path, error) => { if (error == null) { if (FileSavedToPhotosAlbum != null) { FileSavedToPhotosAlbum (this, new FilesSavedToPhotosAlbumArgs (path, path)); } } else { Console.Out.WriteLine ("Video {0} cannot be saved to photos album!", filePath); } }); } } else if (ext.ToUpper () == ".JPEG" || ext.ToUpper () == ".JPG" || ext.ToUpper () == ".PNG") { NSData imgData = NSData.FromArray(fileData); var img = UIImage.LoadFromData(imgData); var meta = new NSDictionary(); ALAssetsLibrary library = new ALAssetsLibrary(); library.WriteImageToSavedPhotosAlbum (img.CGImage, meta, (assetUrl, error) => { if (error == null) { if (FileSavedToPhotosAlbum != null) { FileSavedToPhotosAlbum (this, new FilesSavedToPhotosAlbumArgs (assetUrl.ToString(), filePath)); } else { Console.Out.WriteLine ("Image {0} cannot be saved to photos album!", filePath); } } }); img.Dispose(); } else { File.WriteAllBytes (filePath, fileData); if (FileSavedToPhotosAlbum != null) { FileSavedToPhotosAlbum (this, new FilesSavedToPhotosAlbumArgs (filePath, filePath)); } } }
public override void ViewDidLoad() { base.ViewDidLoad (); NavigationItem.Title = Catalog.GetString ("Loading..."); var cancelButton = new UIBarButtonItem (UIBarButtonSystemItem.Cancel/*, cancelImagePicker*/); cancelButton.Clicked += CancelClicked; NavigationItem.RightBarButtonItem = cancelButton; AssetGroups.Clear (); Library = new ALAssetsLibrary (); Library.Enumerate (ALAssetsGroupType.All, GroupsEnumerator, GroupsEnumeratorFailed); }
static NSUrl fetchMovieUrl () { NSUrl movieURL = null; var waitHandle = new AutoResetEvent (false); ThreadPool.QueueUserWorkItem (_ => { ALAssetsLibrary assetsLibrary = new ALAssetsLibrary (); assetsLibrary.Enumerate (ALAssetsGroupType.All, (ALAssetsGroup group, ref bool stop) => { if (group == null) { waitHandle.Set (); return; } NSDate latest = NSDate.FromTimeIntervalSince1970(0); group.Enumerate ((ALAsset result, nint index, ref bool stopGroup) => { if(result == null || result.AssetType != ALAssetType.Video) return; NSUrl url = result.DefaultRepresentation.Url; if (url == null) return; var diff = result.Date.SecondsSinceReferenceDate - latest.SecondsSinceReferenceDate; if(diff > 0) { latest = result.Date; movieURL = url; } }); stop = movieURL != null; }, (error) => { waitHandle.Set (); }); }); waitHandle.WaitOne (); if (movieURL == null) { UIAlertView alertView = new UIAlertView (null, "Could not find any movies in assets library to use as sample content.", null, "OK", null); alertView.Show (); } return movieURL; }
/// <summary> /// Initializes a new instance of the <see cref="Intranel.Mobile.Touch.AssetLibraryReadStream"/> class. /// </summary> public AssetLibraryReadStream(ALAsset asset, ALAssetsLibrary assetLibrary) { AssetRep = asset.DefaultRepresentation; Lib = assetLibrary; m_Position = 0; }
private async Task<MediaFile> GetMovieMediaFile(NSDictionary info) { NSUrl url = (NSUrl)info[UIImagePickerController.MediaURL]; string path = GetOutputPath(MediaImplementation.TypeMovie, options.Directory ?? ((IsCaptured) ? String.Empty : "temp"), options.Name ?? Path.GetFileName(url.Path)); File.Move(url.Path, path); string aPath = null; Action<bool> dispose = null; if (source != UIImagePickerControllerSourceType.Camera) dispose = d => File.Delete(path); else { if (this.options.SaveToAlbum) { try { var library = new ALAssetsLibrary(); var albumSave = await library.WriteVideoToSavedPhotosAlbumAsync(new NSUrl(path)); aPath = albumSave.AbsoluteString; } catch (Exception ex) { Console.WriteLine("unable to save to album:" + ex); } } } return new MediaFile(path, () => File.OpenRead(path), dispose: dispose, albumPath: aPath); }