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; } }
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); } }
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; try { // capture from camera var processedJPEG = await stillCamera.CapturePhotoAsJPEGAsync(sepiaFilter); // Save to assets library var library = new ALAssetsLibrary(); try { var assetURL = await library.WriteImageToSavedPhotosAlbumAsync(processedJPEG, stillCamera.CurrentCaptureMetadata); Console.WriteLine("Photo saved: " + assetURL); } catch (Exception ex) { Console.WriteLine("Photo save error: " + ex); } } catch (Exception ex) { Console.WriteLine("Photo capture error: " + ex); } sender.Enabled = true; }
public async Task <int> DownloadHomepageAsync() { try { var httpClient = new HttpClient(); // Xamarin supports HttpClient! // // download HTML string Task <string> contentsTask = httpClient.GetStringAsync("https://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("https://xamarin.com/content/images/pages/about/team-h.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("https://developer.xamarin.com/guides/cross-platform/advanced/async_support_overview/Images/AsyncAwait.png"); // async method! Task <byte[]> task2 = httpClient.GetByteArrayAsync("https://blog.xamarin.com/wp-content/uploads/2013/07/monkey_cowboy.jpg"); // async method! Task <byte[]> task3 = httpClient.GetByteArrayAsync("https://developer.xamarin.com/image-doesn't-exist.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 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! bilgiField.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; bilgiField.Text += "Downloaded the html and found out the length.\n\n"; // // download image bytes bilgiField.Text += "Start downloading image.\n"; byte[] imageBytes = await httpClient.GetByteArrayAsync("http://img.gawkerassets.com/img/196gi7ybcdtk0jpg/original.jpg"); // async method! bilgiField.Text += "Downloaded the image.\n"; await SaveBytesToFileAsync(imageBytes, "original.jpg"); resimField.Image = UIImage.FromFile(localPath); // // byte[] docxBytes = await httpClient.GetByteArrayAsync("http://etkintrafik.com/text.docx"); // async method! // ResultTextView.Text += " döküman indi.\n"; // await SaveBytesToFileAsync(docxBytes, "text.docx"); // byte[] xmlBytes = await httpClient.GetByteArrayAsync("http://mobelsis.net/mobelsis.xml"); // async method! bilgiField.Text += " döküman indi.\n"; await SaveBytesToFileAsync(xmlBytes, "mobelsis.xml"); bilgiField .Text += localPath.ToString(); // // // save image to Photo Album using async-ified iOS API ALAssetsLibrary library = new ALAssetsLibrary(); var dict = new NSDictionary(); var assetUrl = await library.WriteImageToSavedPhotosAlbumAsync(resimField.Image.CGImage, dict); bilgiField.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; bilgiField.Text += "** Downloaded " + t.Result.Length + " bytes\n"; } catch (OperationCanceledException) { } catch (Exception exc) { bilgiField.Text += "-- Download ERROR: " + exc.Message + "\n"; } } // this doesn't happen until the image has downloaded as well bilgiField.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); } }
private async Task <MediaFile> GetPictureMediaFile(NSDictionary info) { var image = (UIImage)info[UIImagePickerController.EditedImage] ?? (UIImage)info[UIImagePickerController.OriginalImage]; if (image == null) { return(null); } var path = GetOutputPath(MediaImplementation.TypeImage, options.Directory ?? ((IsCaptured) ? string.Empty : "temp"), options.Name); var cgImage = image.CGImage; var percent = 1.0f; float newHeight = image.CGImage.Height; float newWidth = image.CGImage.Width; if (options.PhotoSize != PhotoSize.Full) { try { switch (options.PhotoSize) { case PhotoSize.Large: percent = .75f; break; case PhotoSize.Medium: percent = .5f; break; case PhotoSize.Small: percent = .25f; break; case PhotoSize.Custom: percent = (float)options.CustomPhotoSize / 100f; break; } if (options.PhotoSize == PhotoSize.MaxWidthHeight && options.MaxWidthHeight.HasValue) { var max = Math.Max(image.CGImage.Width, image.CGImage.Height); if (max > options.MaxWidthHeight.Value) { percent = (float)options.MaxWidthHeight.Value / (float)max; } } if (percent < 1.0f) { //begin resizing image image = image.ResizeImageWithAspectRatio(percent); } } catch (Exception ex) { Console.WriteLine($"Unable to compress image: {ex}"); } } NSDictionary meta = null; try { if (options.SaveMetaData) { if (source == UIImagePickerControllerSourceType.Camera) { meta = info[UIImagePickerController.MediaMetadata] as NSDictionary; if (meta != null && meta.ContainsKey(ImageIO.CGImageProperties.Orientation)) { var newMeta = new NSMutableDictionary(); newMeta.SetValuesForKeysWithDictionary(meta); var newTiffDict = new NSMutableDictionary(); newTiffDict.SetValuesForKeysWithDictionary(meta[ImageIO.CGImageProperties.TIFFDictionary] as NSDictionary); newTiffDict.SetValueForKey(meta[ImageIO.CGImageProperties.Orientation], ImageIO.CGImageProperties.TIFFOrientation); newMeta[ImageIO.CGImageProperties.TIFFDictionary] = newTiffDict; meta = newMeta; } var location = options.Location; if (meta != null && location != null) { meta = SetGpsLocation(meta, location); } } else { meta = PhotoLibraryAccess.GetPhotoLibraryMetadata(info[UIImagePickerController.ReferenceUrl] as NSUrl); } } } catch (Exception ex) { Console.WriteLine($"Unable to get metadata: {ex}"); } //iOS quality is 0.0-1.0 var quality = (options.CompressionQuality / 100f); var savedImage = false; if (meta != null) { savedImage = SaveImageWithMetadata(image, quality, meta, path); } if (!savedImage) { var finalQuality = quality; var imageData = image.AsJPEG(finalQuality); //continue to move down quality , rare instances while (imageData == null && finalQuality > 0) { finalQuality -= 0.05f; imageData = image.AsJPEG(finalQuality); } if (imageData == null) { throw new NullReferenceException("Unable to convert image to jpeg, please ensure file exists or lower quality level"); } imageData.Save(path, true); imageData.Dispose(); } string aPath = null; if (source != UIImagePickerControllerSourceType.Camera) { //try to get the album path's url var url = (NSUrl)info[UIImagePickerController.ReferenceUrl]; aPath = url?.AbsoluteString; } else { if (options.SaveToAlbum) { try { var library = new ALAssetsLibrary(); var albumSave = await library.WriteImageToSavedPhotosAlbumAsync(cgImage, meta); aPath = albumSave.AbsoluteString; } catch (Exception ex) { Console.WriteLine("unable to save to album:" + ex); } } } Func <Stream> getStreamForExternalStorage = () => { if (options.RotateImage) { return(RotateImage(image)); } else { return(File.OpenRead(path)); } }; return(new MediaFile(path, () => File.OpenRead(path), streamGetterForExternalStorage: () => getStreamForExternalStorage(), albumPath: aPath)); }
private async Task <MediaFile> GetPictureMediaFile(NSDictionary info) { var image = (UIImage)info[UIImagePickerController.EditedImage] ?? (UIImage)info[UIImagePickerController.OriginalImage]; NSDictionary meta = null; if (source == UIImagePickerControllerSourceType.Camera) { meta = info[UIImagePickerController.MediaMetadata] as NSDictionary; if (meta != null && meta.ContainsKey(ImageIO.CGImageProperties.Orientation)) { var newMeta = new NSMutableDictionary(); newMeta.SetValuesForKeysWithDictionary(meta); var newTiffDict = new NSMutableDictionary(); newTiffDict.SetValuesForKeysWithDictionary(meta[ImageIO.CGImageProperties.TIFFDictionary] as NSDictionary); newTiffDict.SetValueForKey(meta[ImageIO.CGImageProperties.Orientation], ImageIO.CGImageProperties.TIFFOrientation); newMeta[ImageIO.CGImageProperties.TIFFDictionary] = newTiffDict; meta = newMeta; } var location = options.Location; if (meta != null && location.Latitude > 0.0) { meta = SetGpsLocation(meta, location); } } else { meta = PhotoLibraryAccess.GetPhotoLibraryMetadata(info[UIImagePickerController.ReferenceUrl] as NSUrl); } string path = GetOutputPath(MediaImplementation.TypeImage, options.Directory ?? ((IsCaptured) ? String.Empty : "temp"), options.Name); var cgImage = image.CGImage; if (options.PhotoSize != PhotoSize.Full) { try { var percent = 1.0f; switch (options.PhotoSize) { case PhotoSize.Large: percent = .75f; break; case PhotoSize.Medium: percent = .5f; break; case PhotoSize.Small: percent = .25f; break; case PhotoSize.Custom: percent = (float)options.CustomPhotoSize / 100f; break; } if (options.PhotoSize == PhotoSize.MaxWidthHeight && options.MaxWidthHeight.HasValue) { var max = Math.Max(image.CGImage.Width, image.CGImage.Height); if (max > options.MaxWidthHeight) { percent = (float)options.MaxWidthHeight / (float)max; } } //calculate new size var width = (image.CGImage.Width * percent); var height = (image.CGImage.Height * percent); //begin resizing image image = image.ResizeImageWithAspectRatio(width, height); //update exif pixel dimiensions meta[ImageIO.CGImageProperties.ExifDictionary].SetValueForKey(new NSString(width.ToString()), ImageIO.CGImageProperties.ExifPixelXDimension); meta[ImageIO.CGImageProperties.ExifDictionary].SetValueForKey(new NSString(height.ToString()), ImageIO.CGImageProperties.ExifPixelYDimension); } catch (Exception ex) { Console.WriteLine($"Unable to compress image: {ex}"); } } //iOS quality is 0.0-1.0 var quality = (options.CompressionQuality / 100f); if (meta == null) { image.AsJPEG(quality).Save(path, true); } else { var success = SaveImageWithMetadata(image, quality, meta, path); if (!success) { image.AsJPEG(quality).Save(path, true); } } string aPath = null; if (source != UIImagePickerControllerSourceType.Camera) { //try to get the album path's url var url = (NSUrl)info[UIImagePickerController.ReferenceUrl]; aPath = url?.AbsoluteString; } else { if (this.options.SaveToAlbum) { try { var library = new ALAssetsLibrary(); var albumSave = await library.WriteImageToSavedPhotosAlbumAsync(cgImage, meta); aPath = albumSave.AbsoluteString; } catch (Exception ex) { Console.WriteLine("unable to save to album:" + ex); } } } return(new MediaFile(path, () => File.OpenRead(path), albumPath: aPath)); }
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); var cgImage = image.CGImage; if (options.PhotoSize != PhotoSize.Full) { try { var percent = 1.0f; switch (options.PhotoSize) { case PhotoSize.Large: percent = .75f; break; case PhotoSize.Medium: percent = .5f; break; case PhotoSize.Small: percent = .25f; break; } //calculate new size var width = (image.CGImage.Width * percent); var height = (image.CGImage.Height * percent); //begin resizing image image = image.ResizeImageWithAspectRatio(width, height); } catch (Exception ex) { Console.WriteLine($"Unable to compress image: {ex}"); } } //iOS quality is 0.0-1.0 var quality = (options.CompressionQuality / 100f); image.AsJPEG(quality).Save(path, true); Action <bool> dispose = null; string aPath = null; if (source != UIImagePickerControllerSourceType.Camera) { dispose = d => File.Delete(path); //try to get the album path's url var url = (NSUrl)info[UIImagePickerController.ReferenceUrl]; aPath = url?.AbsoluteString; } else { if (this.options.SaveToAlbum) { try { var library = new ALAssetsLibrary(); var albumSave = await library.WriteImageToSavedPhotosAlbumAsync(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)); }
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; } }
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); }