/// <summary> /// Saves the image to temporary file in png format. /// </summary> /// <returns>Path to temporary file representing image provide as paramater</returns> /// <param name="image">The image to be saved to a tempoarary png file</param> public async Task<string> SaveImageToTemporaryFilePng(UIImage image) { var uniqueFileNamePortion = Guid.NewGuid().ToString(); var temporaryImageFileName = string.Format("{0}.png", uniqueFileNamePortion); var documentsFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var temporaryStorageFolderPath = Path.Combine(documentsFolderPath, "..", "tmp"); var temporaryImageFilePath = Path.Combine(temporaryStorageFolderPath, temporaryImageFileName); var imageData = image.AsPNG(); await Task.Run(() => { //File.WriteAllBytes(temporaryImageFilePath, imageData); NSError error = null; if (imageData.Save(temporaryImageFilePath, false, out error)) { Console.WriteLine("Saved image to temporary file: " + temporaryImageFilePath); } else { Console.WriteLine("ERROR! Did NOT SAVE file because" + error.LocalizedDescription); } }); return temporaryImageFilePath; }
NSData SerializeImage (UIImage image, string typeIdentifier) { if (typeIdentifier == "public.png") return image.AsPNG (); return image.AsJPEG (JpegCompressionQuality); }
private void PublicarPost() { BTProgressHUD.Show(); byte[] Fotografia; if (ImagenPublicacion != null) { Fotografia = ImagenPublicacion?.AsPNG().ToArray(); } else { Fotografia = new byte[0]; } if (InternetConectionHelper.VerificarConexion()) { if (new Controllers.EscritorioController().SetPost(KeyChainHelper.GetKey("Usuario_Id"), KeyChainHelper.GetKey("Usuario_Tipo"), txtPublicacion.Text, Fotografia)) { this.PostPublicadoDelegate.PostPublicado(); this.SendMessage(); this.DismissViewController(true, null); BTProgressHUD.Dismiss(); } else { BTProgressHUD.Dismiss(); new MessageDialog().SendToast("No pudimos publicar tu mensaje, intenta de nuevo"); } } else { BTProgressHUD.Dismiss(); new MessageDialog().SendToast("No tienes conexión a internet, intenta de nuevo"); } }
private CloudBlockBlob UploadImage(UIImage image, String name) { var client = GetClient (); var container = client.GetContainerReference("images"); container.CreateIfNotExists(); var blob = container.GetBlockBlobReference(name); var pngImage = image.AsPNG (); var stream = pngImage.AsStream(); blob.UploadFromStream (stream); return blob; }
private NSData CreateData(ImageFormat format = ImageFormat.Png, float quality = 1) { NSData data; switch (format) { case ImageFormat.Jpeg: data = _image.AsJPEG(quality); break; default: data = _image.AsPNG(); break; } if (data == null) { throw new Exception($"Unable to write the image in the {format} format."); } return(data); }
internal static bool SaveImageWithMetadataiOS13(UIImage image, float quality, NSDictionary meta, string path, string pathExtension) { try { pathExtension = pathExtension.ToLowerInvariant(); var finalQuality = quality; var imageData = pathExtension == "png" ? image.AsPNG(): 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"); } // Copy over meta data using var ciImage = CIImage.FromData(imageData); using var newImageSource = ciImage.CreateBySettingProperties(meta); using var ciContext = new CIContext(); if (pathExtension == "png") { return(ciContext.WritePngRepresentation(newImageSource, NSUrl.FromFilename(path), CIFormat.ARGB8, CGColorSpace.CreateSrgb(), new NSDictionary(), out var error2)); } return(ciContext.WriteJpegRepresentation(newImageSource, NSUrl.FromFilename(path), CGColorSpace.CreateSrgb(), new NSDictionary(), out var error)); } catch (Exception ex) { Console.WriteLine($"Unable to save image with metadata: {ex}"); } return(false); }
public override void OnMapRendered(Bitmap bitmap) { if (!map.FocusPos.Equals(position)) { position = map.FocusPos; number++; UIImage image = BitmapUtils.CreateUIImageFromBitmap(bitmap); string folder = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string filename = number + "png"; string path = System.IO.Path.Combine(folder, filename); NSData data = image.AsPNG(); NSError error; bool success = data.Save(path, false, out error); if (ScreenCaptured != null) { ScreenshotEventArgs args = new ScreenshotEventArgs { Path = path }; if (!success) { args.Message = error.LocalizedDescription; } ScreenCaptured(this, args); } if (success) { Share(data); } } }
private async Task <byte[]> GetImageAsByteAsync(bool usePNG, int quality, int desiredWidth, int desiredHeight) { UIImage image = null; await MainThreadDispatcher.Instance.PostAsync(() => { if (Control != null) { image = Control.Image; } }); if (image == null) { return(null); } if (desiredWidth != 0 || desiredHeight != 0) { image = image.ResizeUIImage((double)desiredWidth, (double)desiredHeight, InterpolationMode.Default); } NSData imageData = usePNG ? image.AsPNG() : image.AsJPEG((nfloat)quality / 100f); if (imageData == null || imageData.Length == 0) { return(null); } var encoded = imageData.ToArray(); imageData.Dispose(); if (desiredWidth != 0 || desiredHeight != 0) { image.Dispose(); } return(encoded); }
public ImageData (UIImage image, string filename) { if (image == null) { throw new ArgumentNullException ("image"); } if (string.IsNullOrEmpty (filename)) { throw new ArgumentException ("filename"); } Image = image; Filename = filename; MimeType = (filename.ToLowerInvariant ().EndsWith (".png")) ? "image/png" : "image/jpeg"; if (MimeType == "image/png") { Data = new NSDataStream (image.AsPNG ()); } else { Data = new NSDataStream (image.AsJPEG ()); } }
internal void AddToCache(string id, UIImage img) { string file = String.Format("{0}{1}.png", picDir, GenerateMD5(id)); if (!File.Exists(file)) { //Save it to disk NSError err = null; try { img.AsPNG().Save(file, false, out err); if (err != null) { Console.WriteLine(String.Format("{0} - {1}", err.Code, err.LocalizedDescription)); } } catch (Exception ex) { Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace); } } }
public byte[] GetImageStreamAtSizeFromStream(byte[] streamData, int targetWidth, int targetHeight) { Stream stream = new MemoryStream(streamData); UIImage uiImage = UIImage.LoadFromData(NSData.FromStream(stream)); stream.Dispose(); UIGraphics.BeginImageContext(new CGSize(targetWidth, targetHeight)); uiImage.Draw(new CGRect(0, 0, targetWidth, targetHeight)); UIImage scaledUIImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); NSData nsData = scaledUIImage.AsPNG(); MemoryStream scaledStream = new MemoryStream(); nsData.AsStream().CopyTo(scaledStream); byte[] scaledStreamData = scaledStream.ToArray(); scaledStream.Dispose(); return(scaledStreamData); }
// method for capture the photo public async void CapturePhoto() { var current = CrossConnectivity.Current.IsConnected; // check for the internet connection to use the ResDiary API if (!current) { var okAlertController = UIAlertController.Create("Connection Error", "Please connect to the internet", UIAlertControllerStyle.Alert); okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(okAlertController, true, null); } else { DialogService.ShowLoading("Scanning Logo"); var videoConnection = stillImageOutput.ConnectionFromMediaType(AVMediaType.Video); var sampleBuffer = await stillImageOutput.CaptureStillImageTaskAsync(videoConnection); var jpegImageAsNsData = AVCaptureStillImageOutput.JpegStillToNSData(sampleBuffer); // crop photo, first change it to UIImage, then crop it UIImage img = new UIImage(jpegImageAsNsData); img = CropImage(img, (int)View.Bounds.GetMidX() + 40, (int)View.Bounds.GetMidY() + 225, 600, 600); // values in rectangle are the starting point and then width and height byte[] CroppedImage; // change UIImage to byte array using (NSData imageData = img.AsPNG()) { CroppedImage = new Byte[imageData.Length]; System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, CroppedImage, 0, Convert.ToInt32(imageData.Length)); } SendPhoto(CroppedImage); } }
private static async void Finalize(ImageCropper imageCropper, UIImage image, OutputImageFormatType outputImageFormat) { string documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string filename; NSData imgData; if (outputImageFormat == OutputImageFormatType.JPG) { filename = System.IO.Path.Combine(documentsDirectory, Guid.NewGuid().ToString() + ".jpg"); imgData = image.AsJPEG(); } else if (outputImageFormat == OutputImageFormatType.PNG) { filename = System.IO.Path.Combine(documentsDirectory, Guid.NewGuid().ToString() + ".png"); imgData = image.AsPNG(); } else { throw new ArgumentException("Unsupported image format"); } NSError err; // small delay await System.Threading.Tasks.Task.Delay(TimeSpan.FromMilliseconds(100)); if (imgData.Save(filename, false, out err)) { imageCropper.Success?.Invoke(filename); } else { Debug.WriteLine("NOT saved as " + filename + " because" + err.LocalizedDescription); imageCropper.Faiure?.Invoke(); } UIApplication.SharedApplication.KeyWindow.RootViewController.DismissViewController(true, null); }
public byte[] Crop(int index) { if (iOSbitmap == null) { return(null); } var sourceWidth = iOSbitmap.Size.Width / columns; var sourceHeight = iOSbitmap.Size.Height / rows; var xPosition = (index % columns) * sourceWidth; var yPosition = (index / columns) * sourceHeight; var rect = new CGRect(xPosition, yPosition, sourceWidth, sourceHeight); var crop = iOSbitmap.CGImage.WithImageInRect(rect); iOSbitmap.Dispose(); var modifiedImage = new UIImage(crop); var data = modifiedImage.AsPNG(); return(data.ToArray()); }
public static byte[] UIImageToBytes(this UIImage image) { if (image == null) { return(null); } NSData data = null; try { data = image.AsPNG(); return(data.ToArray()); } catch (Exception) { return(null); } finally { image.Dispose(); data?.Dispose(); } }
private void ResizeImage(string filename) { UIImage image = UIImage.FromFileUncached(filename); if (image != null) { try { if (image.Size.Width > 300 && image.Size.Height > 200) { UIImage newImage = Scale(image, new Size(300, 200)); NSError error; if (Path.GetExtension(filename).ToLower() == "jpg") { newImage.AsJPEG().Save(filename, false, out error); } else { newImage.AsPNG().Save(filename, false, out error); } Logger.Info("Resize image saved {0}", filename); if (error != null) { Logger.Warn("NSError saving {0}", filename); } } } catch (Exception e) { Logger.Warn("Exception resizing {0}: \n{1}", filename, e); } } }
// void DownloadImagesWorker(object state) // { // threadCount++; // // UrlImageStoreRequest<TKey> nextReq = null; // // while ((nextReq = GetNextRequest()) != null) // { // UIImage img = null; // // // try { img = UIImage.LoadFromData(NSData.FromUrl(NSUrl.FromString(nextReq.Url))); } // catch (Exception ex) // { // Console.WriteLine("Failed to Download Image: " + ex.Message + Environment.NewLine + ex.StackTrace); // } // // if (img == null) // continue; // // //See if the consumer needs to do any processing to the image // if (this.ProcessImage != null) // img = this.ProcessImage(img, nextReq.Id); // // //Add it to cache // AddToCache(nextReq.Id, img); // // // // //Notify the listener waiting for this, // // but do this on the main thread so the user of this class doesn't worry about that // //nsDispatcher.BeginInvokeOnMainThread(delegate { nextReq.Notify.UrlImageUpdated(nextReq.Id); }); // nextReq.Notify.UrlImageUpdated(nextReq.Id); // } // // threadCount--; // } internal void AddToCache(TKey id, UIImage img) { lock (cache) { if (cache.ContainsKey(id)) { cache[id] = img; } else { cache.Add(id, img); } } string file = picDir + "/" + id + ".png"; if (!File.Exists(file)) { //Save it to disk NSError err = null; try { img.AsPNG().Save(file, false, out err); if (err != null) { Console.WriteLine(err.Code.ToString() + " - " + err.LocalizedDescription); } //Console.WriteLine("Saved to Cache: " + file); } catch (Exception ex) { Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace); } } }
public void GalleryMedia() { var imagePicker = new UIImagePickerController { SourceType = UIImagePickerControllerSourceType.PhotoLibrary, MediaTypes = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.PhotoLibrary) }; imagePicker.AllowsEditing = true; var window = UIApplication.SharedApplication.KeyWindow; var vc = window.RootViewController; while (vc.PresentedViewController != null) { vc = vc.PresentedViewController; } vc.PresentViewController(imagePicker, true, null); imagePicker.FinishedPickingMedia += (sender, e) => { UIImage originalImage = e.Info[UIImagePickerController.EditedImage] as UIImage; if (originalImage != null) { var pngImage = originalImage.AsPNG(); byte[] myByteArray = new byte[pngImage.Length]; System.Runtime.InteropServices.Marshal.Copy(pngImage.Bytes, myByteArray, 0, Convert.ToInt32(pngImage.Length)); set2 = new Set2(); set2.Galleryimage(myByteArray); } Device.BeginInvokeOnMainThread(() => { vc.DismissViewController(true, null); }); }; imagePicker.Canceled += (sender, e) => vc.DismissViewController(true, null); }
private async Task <string> UploadToImgur(UIImage image, CancellationToken token) { try { NSUrlSession session; session = NSUrlSession.FromConfiguration( NSUrlSessionConfiguration.EphemeralSessionConfiguration, new NSUrlSessionTaskDelegate() as INSUrlSessionDelegate, new NSOperationQueue() ); NSUrl uploadHandleUrl = NSUrl.FromString("https://api.imgur.com/3/image"); NSMutableUrlRequest request = new NSMutableUrlRequest(uploadHandleUrl) { HttpMethod = "POST", Headers = NSDictionary.FromObjectsAndKeys( new [] { "Client-ID " + APIKeys.ImgurClientID }, new [] { "Authorization" } ) }; request["Content-Type"] = "text/paint"; var png = image.AsPNG(); string base64Image = png?.GetBase64EncodedString(NSDataBase64EncodingOptions.SixtyFourCharacterLineLength); request.Body = $"{base64Image}"; var dataTask = session.CreateDataTaskAsync(request); var dataTaskCancellable = Task.Run(async() => await dataTask, token); if (await Task.WhenAny(dataTaskCancellable, Task.Delay(HttpService.TimeOut)) == dataTaskCancellable) { var dataTaskRequest = await dataTaskCancellable; string result = new NSString(dataTaskRequest.Data, NSStringEncoding.UTF8); Regex reg = new Regex("link\":\"(.*?)\""); Match match = reg.Match(result); return(match.ToString().Replace("link\":\"", "").Replace("\"", "").Replace("\\/", "/")); } } catch { } return(null); }
Picture SavePicture(UIImage withImage, string withExtension) { NSData imageData = null; NSError err = null; Random random = new Random(); int randomPrefix = random.Next(100, 1000); int imgCode = withImage.GetHashCode(); string strImgCode = $"{randomPrefix}{imgCode}"; string ShortFileName = strImgCode; FileName = Path.Combine(SandboxDir, strImgCode + $".{withExtension}"); // save if (withExtension == "JPG" || withExtension == "JPEG") { imageData = withImage.AsJPEG(); } else if (withExtension == "PNG") { imageData = withImage.AsPNG(); } if (imageData.Save(FileName, false, out err)) { Picture pic = new Picture(ShortFileName, withExtension, FileName); return(pic); } else { return(null); } }
private void NewElement_OnDrawBitmap(object sender, EventArgs e) { try { var formsView = Element; var rect = new CGRect(formsView.Bounds.X, formsView.Bounds.Y, formsView.Bounds.Width, formsView.Bounds.Height); var iOSView = ConvertFormsToNative(formsView, rect); UIImage image = ConvertViewToImage(iOSView); //var renderer = Xamarin.Forms.Platform.iOS.Platform.GetRenderer(formsView); //Xamarin.Forms.Platform.iOS.Platform.SetRenderer(formsView, renderer); //var viewGroup = renderer.NativeView; //UIImage image; //// UIGraphics.BeginImageContext(viewGroup.Bounds.Size); //viewGroup.DrawViewHierarchy(viewGroup.Bounds, true); // image = UIGraphics.GetImageFromCurrentImageContext(); //var view = sender as UIView; //UIGraphics.BeginImageContextWithOptions(view.Bounds.Size, opaque: true, scale: 0); //UIImage image; // view.DrawViewHierarchy(view.Bounds, afterScreenUpdates: true); // image = UIGraphics.GetImageFromCurrentImageContext(); //UIGraphics.EndImageContext(); if (image != null) { formsView.BarcodeUrl = image.AsPNG().GetBase64EncodedString(Foundation.NSDataBase64EncodingOptions.EndLineWithLineFeed); } } catch (Exception ex) { } }
string NewElement_SaveImageWithBackground() { UIGraphics.BeginImageContextWithOptions(Bounds.Size, false, 0f); using (var context = UIGraphics.GetCurrentContext()) { Layer.RenderInContext(context); using (UIImage img = UIGraphics.GetImageFromCurrentImageContext()) { UIGraphics.EndImageContext(); string folder = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string filename; do { filename = Path.Combine(folder, "Marking-" + DateTime.Now.Ticks + ".png"); }while (File.Exists(filename)); img.AsPNG().Save(filename, true); return(filename); } } }
public override void DidCropToImage(TOCropViewController cropViewController, UIImage image, CoreGraphics.CGRect cropRect, nint angle) { DidCrop = true; try { if (image != null) { App.CroppedImage = image.AsPNG().ToArray(); } } catch (Exception ex) { Debug.WriteLine(ex.Message); } finally { if (image != null) { image.Dispose(); image = null; } } parent.DismissViewController(true, () => { App.Current.MainPage.Navigation.PopModalAsync(); }); }
// public override void TouchesBegan(NSSet touches, UIEvent evt) { // base.TouchesBegan(touches, evt); // if (this.onResult == null) // this.DismissViewController(true, null); // } private static Stream GetImageStream(UIImage image, ImageFormatType formatType) { if (formatType == ImageFormatType.Jpg) return image.AsJPEG().AsStream(); return image.AsPNG().AsStream(); }
internal void AddToCache(string id, UIImage img) { string file = picDir + GenerateMD5 (id) + ".png"; if (!File.Exists(file)) { //Save it to disk NSError err = null; try { img.AsPNG().Save(file, false, out err); if (err != null) Console.WriteLine(err.Code.ToString() + " - " + err.LocalizedDescription); } catch (Exception ex) { Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace); } } }
static Stream ImageToStream(UIImage image) { var imageData = image.AsPNG(); return(imageData.AsStream()); }
public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); loadingpage(); ViewModel.GetProfilesDetails(); line.BackgroundColor = UIColor.DarkTextColor; line.TintColor = UIColor.DarkTextColor; line.Frame = new CGRect(0, 76, this.View.Frame.Width, 1f); this.View.Add(line); //this.View.BackgroundColor = UIColor.FromRGB(246, 194, 96); NavigationBarSetUp(); this.HidesBottomBarWhenPushed = true; this.NavigationController.NavigationBarHidden = false; ViewModel.ForPropertyChange(x => x.Profile_bubbles, y => { for (int a = 0; a < ViewModel.Profile_bubbles.Count; a++) { if (!string.IsNullOrEmpty(ViewModel.Profile_bubbles[a].icon) && a.Equals(0)) { bubble_1.Image = FromUrl(ViewModel.Profile_bubbles[a].icon); bubble_1.Hidden = false; } else if (!string.IsNullOrEmpty(ViewModel.Profile_bubbles[a].icon) && a.Equals(1)) { bubble_2.Image = FromUrl(ViewModel.Profile_bubbles[a].icon); bubble_2.Hidden = false; } else if (!string.IsNullOrEmpty(ViewModel.Profile_bubbles[a].icon) && a.Equals(2)) { bubble_3.Image = FromUrl(ViewModel.Profile_bubbles[a].icon); bubble_3.Hidden = false; } else if (!string.IsNullOrEmpty(ViewModel.Profile_bubbles[a].icon) && a.Equals(3)) { bubble_4.Image = FromUrl(ViewModel.Profile_bubbles[a].icon); bubble_4.Hidden = false; } else if (!string.IsNullOrEmpty(ViewModel.Profile_bubbles[a].icon) && a.Equals(4)) { bubble_5.Image = FromUrl(ViewModel.Profile_bubbles[a].icon); bubble_5.Hidden = false; } else if (!string.IsNullOrEmpty(ViewModel.Profile_bubbles[a].icon) && a.Equals(5)) { bubble_6.Image = FromUrl(ViewModel.Profile_bubbles[a].icon); bubble_6.Hidden = false; } else if (!string.IsNullOrEmpty(ViewModel.Profile_bubbles[a].icon) && a.Equals(6)) { bubble_7.Image = FromUrl(ViewModel.Profile_bubbles[a].icon); bubble_7.Hidden = false; } else if (!string.IsNullOrEmpty(ViewModel.Profile_bubbles[a].icon) && a.Equals(7)) { bubble_8.Image = FromUrl(ViewModel.Profile_bubbles[a].icon); bubble_8.Hidden = false; } else if (!string.IsNullOrEmpty(ViewModel.Profile_bubbles[a].icon) && a.Equals(8)) { bubble_9.Image = FromUrl(ViewModel.Profile_bubbles[a].icon); bubble_9.Hidden = false; } else if (!string.IsNullOrEmpty(ViewModel.Profile_bubbles[a].icon) && a.Equals(9)) { bubble_10.Image = FromUrl(ViewModel.Profile_bubbles[a].icon); bubble_10.Hidden = false; } } loading_View.Hide(); }); //TabBarController.TabBar.UnselectedItemTintColor = UIColor.White; //TabBarController.TabBar.SelectedImageTintColor = UIColor.White; if (pick_photo.image != null) { using (NSData imageData = pick_photo.image.AsPNG()) { var orientation = pick_photo.image.Orientation; var Orientation_picture = orientation.ToString(); Byte[] myByteArray = new Byte[imageData.Length]; System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, myByteArray, 0, Convert.ToInt32(imageData.Length)); //ViewModel.Bytes = myByteArray; if (!Orientation_picture.Equals("Up")) { UIImage rotated_image = ChangeOrientation(pick_photo.image); using (NSData image_Data = rotated_image.AsPNG()) { Byte[] myByte_Array = new Byte[image_Data.Length]; System.Runtime.InteropServices.Marshal.Copy(image_Data.Bytes, myByte_Array, 0, Convert.ToInt32(image_Data.Length)); } } ViewModel.Bytes = myByteArray; } profile_picture.Image = pick_photo.image; } }
public void Log( string tag, int level, UIImage image ) { if (image == null) { throw new ArgumentNullException("image"); } NSString ns_tag = null; IntPtr ptr_tag = IntPtr.Zero; if (tag != null) { ns_tag = new NSString(tag); ptr_tag = ns_tag.Handle; } using (ns_tag) { using (var png = image.AsPNG()) { LogImageData( logger, ptr_tag, level, (int) image.Size.Width, (int) image.Size.Height, png.Handle ); } } }
internal static bool SaveImageWithMetadata(UIImage image, float quality, NSDictionary meta, string path, string pathExtension) { if (UIDevice.CurrentDevice.CheckSystemVersion(13, 0)) { return(SaveImageWithMetadataiOS13(image, quality, meta, path, pathExtension)); } try { pathExtension = pathExtension.ToLowerInvariant(); var finalQuality = quality; var imageData = pathExtension == "jpg" ? image.AsJPEG(finalQuality) : image.AsPNG(); //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"); } var dataProvider = new CGDataProvider(imageData); var cgImageFromJpeg = CGImage.FromJPEG(dataProvider, null, false, CGColorRenderingIntent.Default); var imageWithExif = new NSMutableData(); var destination = CGImageDestination.Create(imageWithExif, UTType.JPEG, 1); var cgImageMetadata = new CGMutableImageMetadata(); var destinationOptions = new CGImageDestinationOptions(); if (meta.ContainsKey(ImageIO.CGImageProperties.Orientation)) { destinationOptions.Dictionary[ImageIO.CGImageProperties.Orientation] = meta[ImageIO.CGImageProperties.Orientation]; } if (meta.ContainsKey(ImageIO.CGImageProperties.DPIWidth)) { destinationOptions.Dictionary[ImageIO.CGImageProperties.DPIWidth] = meta[ImageIO.CGImageProperties.DPIWidth]; } if (meta.ContainsKey(ImageIO.CGImageProperties.DPIHeight)) { destinationOptions.Dictionary[ImageIO.CGImageProperties.DPIHeight] = meta[ImageIO.CGImageProperties.DPIHeight]; } if (meta.ContainsKey(ImageIO.CGImageProperties.ExifDictionary)) { destinationOptions.ExifDictionary = new CGImagePropertiesExif(meta[ImageIO.CGImageProperties.ExifDictionary] as NSDictionary); } if (meta.ContainsKey(ImageIO.CGImageProperties.TIFFDictionary)) { var existingTiffDict = meta[ImageIO.CGImageProperties.TIFFDictionary] as NSDictionary; if (existingTiffDict != null) { var newTiffDict = new NSMutableDictionary(); newTiffDict.SetValuesForKeysWithDictionary(existingTiffDict); newTiffDict.SetValueForKey(meta[ImageIO.CGImageProperties.Orientation], ImageIO.CGImageProperties.TIFFOrientation); destinationOptions.TiffDictionary = new CGImagePropertiesTiff(newTiffDict); } } if (meta.ContainsKey(ImageIO.CGImageProperties.GPSDictionary)) { destinationOptions.GpsDictionary = new CGImagePropertiesGps(meta[ImageIO.CGImageProperties.GPSDictionary] as NSDictionary); } if (meta.ContainsKey(ImageIO.CGImageProperties.JFIFDictionary)) { destinationOptions.JfifDictionary = new CGImagePropertiesJfif(meta[ImageIO.CGImageProperties.JFIFDictionary] as NSDictionary); } if (meta.ContainsKey(ImageIO.CGImageProperties.IPTCDictionary)) { destinationOptions.IptcDictionary = new CGImagePropertiesIptc(meta[ImageIO.CGImageProperties.IPTCDictionary] as NSDictionary); } destination.AddImageAndMetadata(cgImageFromJpeg, cgImageMetadata, destinationOptions); var success = destination.Close(); if (success) { var saved = imageWithExif.Save(path, true, out NSError error); if (error != null) { Debug.WriteLine($"Unable to save exif data: {error.ToString()}"); } imageWithExif.Dispose(); imageWithExif = null; } return(success); } catch (Exception ex) { Console.WriteLine($"Unable to save image with metadata: {ex}"); } return(false); }
void HandleImagePickerControllerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs e) { UIApplication.SharedApplication.InvokeOnMainThread(delegate { if (popover != null && popover.PopoverVisible) { popover.Dismiss(true); popover.Dispose(); } else { IPhoneServiceLocator.CurrentDelegate.MainUIViewController().DismissModalViewController(true); } }); SystemLogger.Log(SystemLogger.Module.PLATFORM, "FinishedPickingMedia " + e.Info); MediaMetadata mediaData = new MediaMetadata(); mediaData.Type = MediaType.NotSupported; try { NSString mediaType = (NSString)e.Info.ValueForKey(UIImagePickerController.MediaType); UIImage image = (UIImage)e.Info.ValueForKey(UIImagePickerController.OriginalImage); object url = e.Info.ValueForKey(UIImagePickerController.ReferenceUrl); NSUrl nsReferenceUrl = new NSUrl(url.ToString()); if (image != null && mediaType != null && mediaType == "public.image") // "public.image" is the default UTI (uniform type) for images. { mediaData.Type = MediaType.Photo; string fileExtension = Path.GetExtension(nsReferenceUrl.Path.ToLower()); mediaData.MimeType = MediaMetadata.GetMimeTypeFromExtension(fileExtension); mediaData.Title = this.GetImageMediaTitle(nsReferenceUrl.AbsoluteString); NSData imageData = null; if (mediaData.MimeType == "image/png" || mediaData.MimeType == "image/gif" || mediaData.MimeType == "image/tiff") { imageData = image.AsPNG(); } else if (mediaData.MimeType == "image/jpeg" || mediaData.MimeType == "image/jpg") { imageData = image.AsJPEG(); } if (imageData != null) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "Getting image data raw data..."); byte[] buffer = new byte[imageData.Length]; Marshal.Copy(imageData.Bytes, buffer, 0, buffer.Length); IFileSystem fileSystemService = (IFileSystem)IPhoneServiceLocator.GetInstance().GetService("file"); SystemLogger.Log(SystemLogger.Module.CORE, "Storing media file on application filesystem..."); mediaData.ReferenceUrl = fileSystemService.StoreFile(IPhoneMedia.ASSETS_PATH, mediaData.Title, buffer); } SystemLogger.Log(SystemLogger.Module.PLATFORM, mediaData.MimeType + ", " + mediaData.ReferenceUrl + ", " + mediaData.Title); } } catch (Exception ex) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "Error when extracting information from media file: " + ex.Message, ex); } IPhoneUtils.GetInstance().FireUnityJavascriptEvent("Appverse.Media.onFinishedPickingImage", mediaData); }
public void Save(string path, ImageFormat format) { if (path == null) throw new ArgumentNullException ("path"); if (NativeCGImage == null) throw new ObjectDisposedException ("cgimage"); using (var uiimage = new UIImage (NativeCGImage)){ NSError error; if (format == ImageFormat.Jpeg){ using (var data = uiimage.AsJPEG ()){ if (data.Save (path, NSDataWritingOptions.Atomic, out error)) return; throw new IOException ("Saving the file " + path + " " + error); } } else if (format == ImageFormat.Png){ using (var data = uiimage.AsPNG ()){ if (data.Save (path, NSDataWritingOptions.Atomic, out error)) return; throw new IOException ("Saving the file " + path + " " + error); } } else throw new ArgumentException ("Unsupported format, only Jpeg and Png are supported", "format"); } }
public static void Save(string path, UIImage image) { if(File.Exists(path)) { File.Delete(path); } NSError err = null; image.AsPNG().Save(path, true, out err); }
/// <summary> /// Adds to cache. /// </summary> /// <param name="id">Identifier.</param> /// <param name="img">Image.</param> internal void AddToCache(string id, UIImage img) { string cachedFilename = cachedImageDir + "/" + StringUtils.GenerateMD5 (id) + ".png"; if (!File.Exists (cachedFilename)) { // save it to disk NSError err = null; try { img.AsPNG ().Save (cachedFilename, false, out err); if (err != null) Console.WriteLine ("UrlImageStore: Error encoding file {0} to cache ({1} - {2})", cachedFilename, err.Code.ToString (), err.LocalizedDescription); } catch (Exception ex) { Console.WriteLine ("UrlImageStore: Error encoding file {0} to cache ({1})\n{2}", cachedFilename, ex.Message, ex.StackTrace); } } }
public static string[] SaveImage(string name, UIImage ourpic) { if (ourpic == null) return new string[2]{ "", "" }; Console.WriteLine ("Save"); UIImage thumbPic = ourpic.Scale (new SizeF (50, 50)); //measurements taken from CustomCell, alternatly 33x33 if (ourpic != null) { var documentsDirectory = Environment.GetFolderPath (Environment.SpecialFolder.Personal); var picname = name + ".png"; var thumbpicname = name + "_thumb.png"; string pngfileName = System.IO.Path.Combine (documentsDirectory, picname); string thumbpngfileName = System.IO.Path.Combine (documentsDirectory, thumbpicname); NSData imgData = ourpic.AsPNG (); NSData img2Data = thumbPic.AsPNG (); NSError err = null; if (imgData.Save (pngfileName, false, out err)) { Console.WriteLine ("saved as " + pngfileName); } else { Console.WriteLine ("NOT saved as " + pngfileName + " because" + err.LocalizedDescription); } err = null; if (img2Data.Save (thumbpngfileName, false, out err)) { Console.WriteLine ("saved as " + thumbpngfileName); string[] result = new string[2] { picname, thumbpicname }; return result; } else { Console.WriteLine ("NOT saved as " + thumbpngfileName + " because" + err.LocalizedDescription); return null; } } return new string[2]{ "", "" }; }
private string SaveTemporaly(UIImage image) { if (string.IsNullOrEmpty(IMAGE_FILE_NAME)) { DirectoryInfo tempDir = new DirectoryInfo(EnviromentDirectories.IOS_TEMP_DIRECTORY); FileInfo[] tempFiles = tempDir.GetFiles(); IMAGE_FILE_NAME = string.Format("{0}({1}).png", TEMP_IMAGE_NAME, tempFiles.Length); } string tempImagePath = Path.Combine(EnviromentDirectories.IOS_TEMP_DIRECTORY, IMAGE_FILE_NAME); NSData imageData = image.AsPNG(); NSError error = null; imageData.Save(tempImagePath, false, out error); return tempImagePath; }
public byte[] GetScreenshot(View[] views) { try { if (views == null || views?.Count() == 0) { return(null); } // Get each Picture from the given views List <UIImage> images = new List <UIImage>(); foreach (var view in views) { var image = ConvertFormsToUIImage(view); images.Add(image); } //calc the overall pictures size List <IVisualElementRenderer> renderers = new List <IVisualElementRenderer>(); int width = 0; int height = 0; for (int i = 0; i < views.Length; i++) { renderers.Add(Platform.GetRenderer(views[i])); if (i == 0) { width += Convert.ToInt32(renderers.Last().Element.Width); } height += Convert.ToInt32(renderers.Last().Element.Height); } CGSize s = new CGSize(width, height); byte[] bitmapData; nfloat oldViewHeight = 0; //create a big picture containing all pictures underneath each other using (var context = UIGraphics.GetCurrentContext()) { UIGraphics.BeginImageContext(s); foreach (var image in images) { image.Draw(new CGRect(0, oldViewHeight, image.Size.Width, image.Size.Height)); oldViewHeight = image.Size.Height; } UIImage uIImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); var nsData = uIImage.AsPNG(); bitmapData = nsData.ToArray(); } return(bitmapData); } catch (Exception ex) { //CrashTracker.Track(ex); return(null); } }
internal override Task <Stream> PlatformOpenReadAsync() { data ??= uiImage.AsPNG(); return(Task.FromResult(data.AsStream())); }
void PostNewAvatar(UIImage image) { NSData data = image.AsPNG (); byte[] dataBytes = new byte[data.Length]; System.Runtime.InteropServices.Marshal.Copy(data.Bytes, dataBytes, 0, Convert.ToInt32(data.Length)); Engine.Instance.AvatarAccess.PostNewAvatar (dataBytes, (result) => { if (result.Exceptin != null) { _controller.BeginInvokeOnMainThread (delegate { _controller.RefreshHeaderCell (); }); } }); }
static public async Task <bool> UploadImageToServer(UIImage image, string filename, string filepath, PheidiParams pheidiparams, bool displayAlert = true) { string p = ""; var dic = new Dictionary <string, string>(); var uploadId = (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds.ToString("F0"); var url = App.CurrentServer.Address + "/upload.ashx"; var parameters = new Dictionary <string, string> { { "uploadID", uploadId } }; var timeout = new TimeSpan(0, 0, 240); var handler = new HttpClientHandler() { CookieContainer = App.CookieManager.GetAllCookies() }; using (var httpClient = new HttpClient(handler, true)) { MultipartFormDataContent content = new MultipartFormDataContent(); content.Add(new StringContent(uploadId), "uploadID"); Stream imageStream = new MemoryStream(); imageStream = image.AsPNG().AsStream(); var streamContent = new StreamContent(imageStream); content.Add(streamContent, "Filedata", filename); content.Add(new StringContent(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")), "ModDate"); content.Add(new StringContent(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")), "CrDate"); content.Add(new StringContent("image"), "callType"); content.Add(new StringContent(pheidiparams["NOSEQ"]), "qfv"); content.Add(new StringContent("2"), "BD"); HttpResponseMessage response = null; try { HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Post, url); httpRequest.Content = content; httpRequest.Headers.Add("User-Agent", "Ipheidi " + Device.RuntimePlatform); httpRequest.Headers.Add("UserHostAddress", App.NetworkManager.GetIPAddress()); Debug.WriteLine(await httpRequest.Content.ReadAsStringAsync()); httpClient.Timeout = timeout; response = await httpClient.SendAsync(httpRequest); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(App.ಠ_ಠ); Debug.WriteLine(ex.Message + "\n\n" + ex.ToString()); App.NetworkManager.CheckHostServerState(); }; if (response != null) { if (response.StatusCode == HttpStatusCode.OK) { string responseContent = response.Content.ReadAsStringAsync().Result; Debug.WriteLine("Reponse:" + responseContent); if (responseContent == "1") { dic = new Dictionary <string, string>(); dic.Add("FIELD", pheidiparams["FIELD"]); dic.Add("NOSEQ", pheidiparams["NOSEQ"]); dic.Add("VALUE", "'" + uploadId + "'"); foreach (var d in dic) { p += d.Key + "**:**" + d.Value + "**,**"; } parameters = new Dictionary <string, string> { { "pheidiaction", "UpdateFieldValue" }, { "pheidiparams", p } }; response = null; response = await PheidiNetworkManager.SendHttpRequestAsync(parameters, new TimeSpan(0, 0, 30)); if (response != null) { if (response.StatusCode == HttpStatusCode.OK) { responseContent = response.Content.ReadAsStringAsync().Result; Debug.WriteLine("Reponse:" + responseContent); if (!responseContent.StartsWith("erreur", StringComparison.OrdinalIgnoreCase)) { if (displayAlert) { App.NotificationManager.DisplayAlert(AppResources.Alerte_EnvoiePhotoCompleteMessage, "Pheidi", "OK", () => { }); try { DeleteImageInDirectory(filename); } catch (Exception e) { Debug.WriteLine(e.Message); } } return(true); } } } } } } } return(false); }
bool GenerateImage(Dictionary <Page, eBriefingMobile.Annotation> dict1, Dictionary <Page, List <eBriefingMobile.Note> > dict2) { try { if (pageList != null) { nuint totalImageSize = 0; List <Note> notes = new List <eBriefingMobile.Note> (); foreach (var page in pageList) { String localPath = DownloadedFilesCache.BuildCachedFilePath(page.URL); var printItemDict = new Dictionary <UIImage, List <Note> >(); if (!String.IsNullOrEmpty(localPath)) { CGPDFDocument pdfDoc = CGPDFDocument.FromFile(localPath); if (pdfDoc != null) { CGPDFPage pdfPage = pdfDoc.GetPage(1); if (pdfPage != null) { CGRect pageRect = pdfPage.GetBoxRect(CGPDFBox.Media); UIImage pdfImg = ImageHelper.PDF2Image(pdfPage, pageRect.Width, scale); // Add annotation if option selected if (dict1.ContainsKey(page)) { Annotation annotation = dict1 [page]; if (annotation != null) { Dictionary <String, PSPDFInkAnnotation> coordinateDict = AnnotationsDataAccessor.GenerateAnnDictionary((UInt32)page.PageNumber - 1, annotation); if (coordinateDict != null) { foreach (KeyValuePair <String, PSPDFInkAnnotation> item in coordinateDict) { // Create full size annotation UIImage annImg = ImageHelper.DrawPSPDFAnnotation(item.Key, item.Value); if (annImg != null) { // Scale down the annotation image annImg = annImg.Scale(new CGSize(pdfImg.Size.Width, pdfImg.Size.Height)); // Overlap pdfImg and annImg pdfImg = ImageHelper.Overlap(pdfImg, annImg, CGPoint.Empty, CGPoint.Empty, scale); } } } } } // Create image from text bool printNote = false; UIImage noteImg = null; if (dict2.ContainsKey(page) && dict2 [page] != null) { printNote = true; notes = dict2 [page]; // Create image from text //noteImg = ImageHelper.Text2Image(_notesText, pdfImg.Size); } else { notes = null; } // Scale down and add to canvas // Used 900 and 1200 because couldn't control the paper margin // if (Orientation == ORIENTATION.PORTRAIT) // { // //if (printNote) // { // //pdfImg = ImageHelper.Scale(pdfImg, 500); // //pdfImg=ImageHelper.MaxResizeImage(pdfImg,1000,scale); // //pdfImg = ImageHelper.Add2Canvas(pdfImg, new CGPoint(0, (1024 / 2) - (pdfImg.Size.Height / 2)), scale); // // // Overlap pdfImg and noteImg // //pdfImg = ImageHelper.Overlap(pdfImg, noteImg, CGPoint.Empty, new CGPoint(500, 0), scale); // } // //else // { // //pdfImg=ImageHelper.MaxResizeImage(pdfImg,1000,scale); // //pdfImg = ImageHelper.Scale(pdfImg, 900); // //pdfImg = ImageHelper.Add2Canvas(pdfImg, new CGPoint((768 / 2) - (pdfImg.Size.Width / 2), (1024 / 2) - (pdfImg.Size.Height / 2)), scale); // } // } // else // { // //if (printNote) // { // //pdfImg=ImageHelper.MaxResizeImage(pdfImg,500,scale); // //pdfImg = ImageHelper.Scale(pdfImg, 500); // // pdfImg = ImageHelper.Add2Canvas(pdfImg, new CGPoint(0,0), scale*2, UIInterfaceOrientation.LandscapeLeft); // // Overlap pdfImg and noteImg // //pdfImg = ImageHelper.Overlap(pdfImg, noteImg, CGPoint.Empty, new CGPoint(756, 0), scale); // } // //else // { // //pdfImg=ImageHelper.MaxResizeImage(pdfImg,1000,scale); // //pdfImg = ImageHelper.Scale(pdfImg, 500); // ///pdfImg = ImageHelper.Add2Canvas(pdfImg, new CGPoint((1024 / 2) - (pdfImg.Size.Width / 2), (768 / 2) - (pdfImg.Size.Height / 2)), scale*2, UIInterfaceOrientation.LandscapeLeft); // } // // // Rotate canvas // //pdfImg = ImageHelper.Rotate(pdfImg); // } // Save // if (printItems == null) // { // printItems = new List<UIImage>(); // } // printItems.Add(pdfImg); if (dict == null) { dict = new Dictionary <int, Dictionary <UIImage, List <Note> > > (); } if (pdfImg != null) { printItemDict.Add(pdfImg, notes); dict.Add(page.PageNumber, printItemDict); var pngImage = pdfImg.AsPNG(); totalImageSize = pngImage.Length + totalImageSize; Console.WriteLine("Img : " + totalImageSize.ToString()); //image dispose pdfImg = null; if (CheckReachMemoryLimit(totalImageSize)) { PagesNum = dict.Count - 1; dict.Clear(); dict = null; return(false); } } } } } } PagesNum = dict.Count; return(true); } return(false); } catch (Exception ex) { return(false); } }
public Task <Stream> GetImageStreamAsync() { imagePicker = new UIImagePickerController { SourceType = UIImagePickerControllerSourceType.PhotoLibrary, MediaTypes = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.PhotoLibrary) }; imagePicker.FinishedPickingMedia += OnImagePickerFinishedPickingMedia; imagePicker.Canceled += OnImagePickerCancelled; UIWindow window = UIApplication.SharedApplication.KeyWindow; var viewController = window.RootViewController; viewController.PresentModalViewController(imagePicker, true); taskCompletionSource = new TaskCompletionSource <Stream>(); return(taskCompletionSource.Task); void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs args) { UIImage image = args.EditedImage ?? args.OriginalImage; if (image != null) { NSData data; if (args.ReferenceUrl.PathExtension.Equals("PNG") || args.ReferenceUrl.PathExtension.Equals("png")) { data = image.AsPNG(); } else { data = image.AsJPEG(1); } Stream stream = data.AsStream(); UnregisterEventHandlers(); taskCompletionSource.SetResult(stream); } else { UnregisterEventHandlers(); taskCompletionSource.SetResult(null); } imagePicker.DismissModalViewController(true); } void OnImagePickerCancelled(object sender, EventArgs args) { UnregisterEventHandlers(); taskCompletionSource.SetResult(null); imagePicker.DismissModalViewController(true); } void UnregisterEventHandlers() { imagePicker.FinishedPickingMedia -= OnImagePickerFinishedPickingMedia; imagePicker.Canceled -= OnImagePickerCancelled; } }
/// <summary> /// Opens the line. /// </summary> /// <returns><c>true</c>, if line was opened, <c>false</c> otherwise.</returns> /// <param name="image">Image.</param> public static bool OpenLine(UIImage image) { if (!CanOpenLine()) return false; var pasteboard = UIPasteboard.GetUnique(); pasteboard.SetData(image.AsPNG(), "public.png"); var pasteboardName = pasteboard.Name; var encoded = Uri.EscapeDataString(pasteboardName); var url = CreateNSUrl(LineUrlContentTypes.Image, encoded); var shareApp = UIApplication.SharedApplication; return shareApp.OpenUrl(url); }
UIImage ChangeOrientation(UIImage rotatedImage) { float width = rotatedImage.CGImage.Width; float height = rotatedImage.CGImage.Height; CGImage imgRef = rotatedImage.CGImage; CGAffineTransform transform = CGAffineTransform.MakeIdentity(); CGRect bounds = new CGRect(0, 0, width, height); float scaleRatio = (float)(bounds.Size.Width / width); CGSize imageSize = new CGSize(imgRef.Width, imgRef.Height); var orient = rotatedImage.Orientation; switch (orient) { case UIImageOrientation.Right: bounds.Size = new CGSize(bounds.Size.Height, bounds.Size.Width); transform = CGAffineTransform.MakeTranslation(imageSize.Height, 0.0f); transform = CGAffineTransform.Rotate(transform, (System.nfloat)(Math.PI / 2.0)); break; case UIImageOrientation.Up: //EXIF = 1 transform = CGAffineTransform.MakeIdentity(); break; case UIImageOrientation.UpMirrored: //EXIF = 2 transform = CGAffineTransform.MakeTranslation(imageSize.Width, 0.0f); transform = CGAffineTransform.Scale(transform, -1.0f, 1.0f); break; case UIImageOrientation.Down: //EXIF = 3 transform = CGAffineTransform.MakeTranslation(imageSize.Width, imageSize.Height); transform = CGAffineTransform.Rotate(transform, (System.nfloat)Math.PI); break; case UIImageOrientation.DownMirrored: //EXIF = 4 transform = CGAffineTransform.MakeTranslation(0.0f, imageSize.Height); transform = CGAffineTransform.Scale(transform, 1.0f, -1.0f); break; case UIImageOrientation.LeftMirrored: //EXIF = 5 bounds.Size = new CGSize(bounds.Size.Height, bounds.Size.Width); transform = CGAffineTransform.MakeTranslation(imageSize.Height, imageSize.Width); transform = CGAffineTransform.Scale(transform, -1.0f, 1.0f); transform = CGAffineTransform.Rotate(transform, (System.nfloat)(3.0 * Math.PI / 2.0)); break; case UIImageOrientation.Left: //EXIF = 6 bounds.Size = new CGSize(bounds.Size.Height, bounds.Size.Width); transform = CGAffineTransform.MakeTranslation(0.0f, imageSize.Width); transform = CGAffineTransform.Rotate(transform, (System.nfloat)(3.0 * Math.PI / 2.0)); break; case UIImageOrientation.RightMirrored: //EXIF = 7 bounds.Size = new CGSize(bounds.Size.Height, bounds.Size.Width); transform = CGAffineTransform.MakeScale(-1.0f, 1.0f); transform = CGAffineTransform.Rotate(transform, (System.nfloat)(Math.PI / 2.0)); break; } UIGraphics.BeginImageContext(bounds.Size); CGContext context = UIGraphics.GetCurrentContext(); if (orient == UIImageOrientation.Right || orient == UIImageOrientation.Left) { context.ScaleCTM(-scaleRatio, scaleRatio); context.TranslateCTM(-height, 0); } else { context.ScaleCTM(scaleRatio, -scaleRatio); context.TranslateCTM(0, -height); } context.ConcatCTM(transform); context.DrawImage(new CGRect(0, 0, width, height), imgRef); UIImage imageCopy = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); NSData str = imageCopy.AsPNG(); return(imageCopy); }
public virtual async Task <Tuple <Stream, LoadingResult, ImageInformation> > Resolve(string identifier, TaskParameter parameters, CancellationToken token) { NSBundle bundle = null; var filename = Path.GetFileNameWithoutExtension(identifier); var tmpPath = Path.GetDirectoryName(identifier).Trim('/'); var filenamePath = string.IsNullOrWhiteSpace(tmpPath) ? null : tmpPath + "/"; foreach (var fileType in fileTypes) { string file = null; var extension = Path.HasExtension(identifier) ? Path.GetExtension(identifier) : string.IsNullOrWhiteSpace(fileType) ? string.Empty : "." + fileType; token.ThrowIfCancellationRequested(); int scale = (int)ScaleHelper.Scale; if (scale > 1) { while (scale > 1) { token.ThrowIfCancellationRequested(); var tmpFile = string.Format("{0}@{1}x{2}", filename, scale, extension); bundle = NSBundle._AllBundles.FirstOrDefault(bu => { var path = string.IsNullOrWhiteSpace(filenamePath) ? bu.PathForResource(tmpFile, null) : bu.PathForResource(tmpFile, null, filenamePath); return(!string.IsNullOrWhiteSpace(path)); }); if (bundle != null) { file = tmpFile; break; } scale--; } } token.ThrowIfCancellationRequested(); if (file == null) { var tmpFile = string.Format(filename + extension); file = tmpFile; bundle = NSBundle._AllBundles.FirstOrDefault(bu => { var path = string.IsNullOrWhiteSpace(filenamePath) ? bu.PathForResource(tmpFile, null) : bu.PathForResource(tmpFile, null, filenamePath); return(!string.IsNullOrWhiteSpace(path)); }); } token.ThrowIfCancellationRequested(); if (bundle != null) { string path = !string.IsNullOrEmpty(filenamePath) ? bundle.PathForResource(file, null, filenamePath) : bundle.PathForResource(file, null); var stream = FileStore.GetInputStream(path, true); var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(path); return(new Tuple <Stream, LoadingResult, ImageInformation>( stream, LoadingResult.CompiledResource, imageInformation)); } token.ThrowIfCancellationRequested(); if (string.IsNullOrEmpty(fileType)) { //Asset catalog if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0)) { NSDataAsset asset = null; try { await MainThreadDispatcher.Instance.PostAsync(() => asset = new NSDataAsset(filename)).ConfigureAwait(false); } catch (Exception) { } if (asset != null) { token.ThrowIfCancellationRequested(); var stream = asset.Data?.AsStream(); var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(null); return(new Tuple <Stream, LoadingResult, ImageInformation>( stream, LoadingResult.CompiledResource, imageInformation)); } } UIImage image = null; try { await MainThreadDispatcher.Instance.PostAsync(() => image = UIImage.FromBundle(filename)).ConfigureAwait(false); } catch (Exception) { } if (image != null) { token.ThrowIfCancellationRequested(); var stream = image.AsPNG()?.AsStream(); var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(null); return(new Tuple <Stream, LoadingResult, ImageInformation>( stream, LoadingResult.CompiledResource, imageInformation)); } } } throw new FileNotFoundException(identifier); }