public IImage LoadImage(Stream stream) { var mem = new MemoryStream((int)stream.Length); stream.CopyTo(mem); unsafe { #if NET45 fixed(byte *x = mem.GetBuffer()) #else ArraySegment <byte> segment; if (!mem.TryGetBuffer(out segment)) { throw new Exception("Could not get buffer from stream."); } fixed(byte *x = segment.Array) #endif { var provider = new CGDataProvider(new IntPtr(x), (int)mem.Length, false); var image = CGImage.FromPNG(provider, null, false, CGColorRenderingIntent.Default) ?? CGImage.FromJPEG(provider, null, false, CGColorRenderingIntent.Default); return(new CGImageImage(image, 1)); } } }
// ReSharper disable once UnusedMember.Local private void PhotoCaptureComplete(AVCapturePhotoOutput captureOutput, CMSampleBuffer finishedPhotoBuffer, CMSampleBuffer previewPhotoBuffer, AVCaptureResolvedPhotoSettings resolvedSettings, AVCaptureBracketedStillImageSettings bracketSettings, NSError error) { try { if (error != null) { _cameraModule.ErrorMessage = error.ToString(); } else if (finishedPhotoBuffer != null) { LockPictureSpecificSettingsIfNothingCaptured(); using (var image = AVCapturePhotoOutput.GetJpegPhotoDataRepresentation(finishedPhotoBuffer, previewPhotoBuffer)) using (var imgDataProvider = new CGDataProvider(image)) using (var cgImage = CGImage.FromJPEG(imgDataProvider, null, false, CGColorRenderingIntent.Default)) using (var uiImage = UIImage.FromImage(cgImage, 1, GetOrientationForCorrection())) { _cameraModule.CapturedImage = uiImage.AsJPEG().ToArray(); } } } catch (Exception e) { _cameraModule.ErrorMessage = e.ToString(); } }
private static void SaveTempImage(CIImage fullimage, UIImage image, string outputFilename, int quality, bool rotate) { var imageData = image.AsJPEG(quality); 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 options = new CGImageDestinationOptions(); if (fullimage.Properties.DPIWidthF != null) { options.Dictionary[ImageIO.CGImageProperties.DPIWidth] = new NSNumber((nfloat)fullimage.Properties.DPIWidthF); } if (fullimage.Properties.DPIWidthF != null) { options.Dictionary[ImageIO.CGImageProperties.DPIHeight] = new NSNumber((nfloat)fullimage.Properties.DPIHeightF); } options.ExifDictionary = fullimage.Properties?.Exif ?? new CGImagePropertiesExif(); options.TiffDictionary = fullimage.Properties?.Tiff ?? new CGImagePropertiesTiff(); options.GpsDictionary = fullimage.Properties?.Gps ?? new CGImagePropertiesGps(); options.JfifDictionary = fullimage.Properties?.Jfif ?? new CGImagePropertiesJfif(); options.IptcDictionary = fullimage.Properties?.Iptc ?? new CGImagePropertiesIptc(); if (rotate) { options.Dictionary[ImageIO.CGImageProperties.Orientation] = new NSString(UIImageOrientation.Up.ToString()); var tiffDict = new CGImagePropertiesTiff(); foreach (KeyValuePair <NSObject, NSObject> x in options.TiffDictionary.Dictionary) { tiffDict.Dictionary.SetValueForKey(x.Value, x.Key as NSString); } tiffDict.Dictionary.SetValueForKey(new NSNumber(1), new NSString("Orientation")); options.TiffDictionary = tiffDict; } else { if (fullimage.Properties.Orientation != null) { options.Dictionary[ImageIO.CGImageProperties.Orientation] = new NSString(image.Orientation.ToString()); } } destination.AddImageAndMetadata(cgImageFromJpeg, cgImageMetadata, options); var success = destination.Close(); if (success) { imageWithExif.Save(outputFilename, true); } else { imageData.Save(outputFilename, true); } }
public void TestCreateBitmapFromCGImage() { // Load CGImage var path = @"../../data/SetupLogo.jpg"; Debug.WriteLine(System.IO.Path.GetFullPath(path)); var provider = new CGDataProvider(path); var cgImage = CGImage.FromJPEG(provider, null, false, CGColorRenderingIntent.Default); // Convert it to System.Drawing.Bitmap using Bitmap's internal constructor var bitmap = cgImage.ToBitmap(); Assert.AreEqual(cgImage.Width, bitmap.Width); }
public IImage LoadImage(string path) { var provider = new CGDataProvider(path); CGImage image; if (System.IO.Path.GetExtension(path).ToLowerInvariant() == ".png") { image = CGImage.FromPNG(provider, null, false, CGColorRenderingIntent.Default); } else { image = CGImage.FromJPEG(provider, null, false, CGColorRenderingIntent.Default); } return(new CGImageImage(image, 1)); }
public IImage LoadImage(Stream stream) { var mem = new MemoryStream((int)stream.Length); stream.CopyTo(mem); unsafe { fixed(byte *x = mem.GetBuffer()) { var provider = new CGDataProvider(new IntPtr(x), (int)mem.Length, false); var image = CGImage.FromPNG(provider, null, false, CGColorRenderingIntent.Default) ?? CGImage.FromJPEG(provider, null, false, CGColorRenderingIntent.Default); return(new CGImageImage(image, 1)); } } }
private bool SaveImageWithMetadata(UIImage image, float quality, NSDictionary meta, string path) { var imageData = image.AsJPEG(quality); 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.ExifDictionary)) { destinationOptions.ExifDictionary = new CGImagePropertiesExif(meta[ImageIO.CGImageProperties.ExifDictionary] as NSDictionary); } if (meta.ContainsKey(ImageIO.CGImageProperties.TIFFDictionary)) { destinationOptions.TiffDictionary = new CGImagePropertiesTiff(meta[ImageIO.CGImageProperties.TIFFDictionary] as NSDictionary); } 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) { imageWithExif.Save(path, true); } return(success); }
public BitmapImplementation(Stream stream) { byte[] data; using (var ms = new MemoryStream()) { stream.CopyTo(ms); data = ms.ToArray(); } cgImage = CGImage.FromPNG(new CGDataProvider(data), null, false, CGColorRenderingIntent.Default); if (cgImage == null) { cgImage = CGImage.FromJPEG(new CGDataProvider(data), null, false, CGColorRenderingIntent.Default); } var alphaInfo = cgImage.AlphaInfo; HasAlpha = alphaInfo != CGImageAlphaInfo.None && alphaInfo != CGImageAlphaInfo.NoneSkipFirst && alphaInfo != CGImageAlphaInfo.NoneSkipLast; }
// ReSharper disable once UnusedMember.Local private void PhotoCaptureComplete(AVCapturePhotoOutput captureOutput, CMSampleBuffer finishedPhotoBuffer, CMSampleBuffer previewPhotoBuffer, AVCaptureResolvedPhotoSettings resolvedSettings, AVCaptureBracketedStillImageSettings bracketSettings, NSError error) { try { if (error != null) { _cameraModule.ErrorMessage = error.ToString(); } else if (finishedPhotoBuffer != null) { if (!(_cameraModule.BluetoothOperator.PairStatus == PairStatus.Connected && !_cameraModule.BluetoothOperator.IsPrimary)) { LockPictureSpecificSettingsIfApplicable(); } using (var image = AVCapturePhotoOutput.GetJpegPhotoDataRepresentation(finishedPhotoBuffer, previewPhotoBuffer)) using (var imgDataProvider = new CGDataProvider(image)) using (var cgImage = CGImage.FromJPEG(imgDataProvider, null, false, CGColorRenderingIntent.Default)) using (var uiImage = UIImage.FromImage(cgImage, 1, GetOrientationForCorrection())) { var imageBytes = uiImage.AsJPEG().ToArray(); if (_cameraModule.BluetoothOperator.PairStatus == PairStatus.Connected && !_cameraModule.BluetoothOperator.IsPrimary) { _cameraModule.BluetoothOperator.SendCapture(imageBytes); } else { _cameraModule.CapturedImage = imageBytes; } } } } catch (Exception e) { _cameraModule.ErrorMessage = e.ToString(); } }
private bool SaveImageWithMetadata(UIImage image, float quality, NSDictionary meta, string path) { try { 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"); } 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)) { destinationOptions.TiffDictionary = new CGImagePropertiesTiff(meta[ImageIO.CGImageProperties.TIFFDictionary] as NSDictionary); } 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) { imageWithExif.Save(path, true); } return(success); } catch (Exception ex) { Console.WriteLine($"Unable to save image with metadata: {ex}"); } return(false); }
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); }
/// <summary> /// Creates a composited image from a list of source images /// </summary> /// <param name="paths">The paths of the images, in order of lowest z-index to highest, to composite together</param> /// <param name="saveLocation">Where to save the composited image</param> /// <param name="overwrite"><c>true</c> to overwrite an existing file; otherwise <c>false</c>.</param> public void CreateCompositeImage(List <string> paths, string saveLocation, bool overwrite) { if (!overwrite && Device.File.Exists(saveLocation)) { return; } paths = paths.Where(path => path != null && Device.File.Exists(path)).ToList(); if (paths.Count == 0) { return; } try { var metric = System.DateTime.UtcNow; Device.File.EnsureDirectoryExists(saveLocation); using (new NSAutoreleasePool()) { var images = new List <CGImage>(paths.Count); images.AddRange(paths.Select <string, CGImage>(path => path.EndsWith(".png", StringComparison.InvariantCultureIgnoreCase) ? CGImage.FromPNG(CGDataProvider.FromFile(path), null, false, CGColorRenderingIntent.Default) : CGImage.FromJPEG(CGDataProvider.FromFile(path), null, false, CGColorRenderingIntent.Default))); nint width = images[0].Width; nint height = images[0].Height; var bounds = new RectangleF(0, 0, width, height); CGBitmapContext g = new CGBitmapContext( System.IntPtr.Zero, width, height, images[0].BitsPerComponent, images[0].Width * 4, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedLast ); foreach (var cgImage in images) { g.DrawImage(bounds, cgImage); } lock (padlock) { // UIImage.AsPNG() should be safe to run on a background thread, but MT 6.2.6.6 says otherwise. // Xamarin confirmed that this was unintentional and that MT 6.2.7 will remove the UI check. UIApplication.CheckForIllegalCrossThreadCalls = false; NSError err = null; UIImage.FromImage(g.ToImage()).AsPNG().Save(saveLocation, true, out err); UIApplication.CheckForIllegalCrossThreadCalls = true; } } Device.Log.Metric("ImageEngine icon creation", System.DateTime.UtcNow.Subtract(metric).TotalMilliseconds); } catch (Exception e) { Device.Log.Error("An error occurred while compositing the image", e); } }
private bool SaveImageWithMetadata(UIImage image, float quality, NSDictionary meta, string path) { try { var imageData = GetImageWithQuality(quality, image); 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.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)) { destinationOptions.TiffDictionary = new CGImagePropertiesTiff(meta[ImageIO.CGImageProperties.TIFFDictionary] as NSDictionary); } 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); } if (options.RotateImage) { if (meta.ContainsKey(ImageIO.CGImageProperties.Orientation)) destinationOptions.Dictionary[ImageIO.CGImageProperties.Orientation] = new NSString(UIImageOrientation.Up.ToString()); destinationOptions.TiffDictionary.Orientation = CoreImage.CIImageOrientation.TopLeft; } else { if (meta.ContainsKey(ImageIO.CGImageProperties.Orientation)) destinationOptions.Dictionary[ImageIO.CGImageProperties.Orientation] = meta[ImageIO.CGImageProperties.Orientation]; } destination.AddImageAndMetadata(cgImageFromJpeg, cgImageMetadata, destinationOptions); var success = destination.Close(); if (success) { imageWithExif.Save(path, true); } return success; } catch (Exception ex) { Console.WriteLine($"Unable to save image with metadata: {ex}"); } return false; }
private static CGImage CGImageFromJPEGFile(string filename) { var provider = new CGDataProvider(filename); return(CGImage.FromJPEG(provider, null, false, CGColorRenderingIntent.AbsoluteColorimetric)); }