public UIImage ProcessedImage() { nfloat scale = UIScreen.MainScreen.Scale; CGImage imageRef = _originalImage.CGImage; if (imageRef == null) { return(null); } var bytesPerRow = 0; var bitsPerComponent = imageRef.BitsPerComponent; CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB(); var bitmapInfo = imageRef.BitmapInfo; CGBitmapContext context = new CGBitmapContext(null, (nint)(_targetSize.Width * scale), (nint)(_targetSize.Height * scale), bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo); colorSpace.Dispose(); if (context == null) { imageRef.Dispose(); return(null); } CGRect targetFrame = LocalCropFrame(); context.InterpolationQuality = CGInterpolationQuality.High; context.SetBlendMode(CGBlendMode.Copy); context.DrawImage(targetFrame, imageRef); var contextImage = context.ToImage(); UIImage finalImage = null; context.Dispose(); if (contextImage != null) { finalImage = UIImage.FromImage(contextImage, scale, UIImageOrientation.Up); contextImage.Dispose(); } imageRef.Dispose(); return(finalImage); }
/// <summary> /// Creates grayscaled image from existing image. /// </summary> /// <param name="oldImage">Image to convert.</param> /// <returns>Returns grayscaled image.</returns> public static UIImage GrayscaleImage(UIImage oldImage) { var imageRect = new RectangleF(PointF.Empty, (SizeF)oldImage.Size); CGImage grayImage; // Create gray image. using (CGColorSpace colorSpace = CGColorSpace.CreateDeviceGray()) { using (var context = new CGBitmapContext(IntPtr.Zero, (int)imageRect.Width, (int)imageRect.Height, 8, 0, colorSpace, CGImageAlphaInfo.None)) { context.DrawImage(imageRect, oldImage.CGImage); grayImage = context.ToImage(); } } // Create mask for transparent areas. using (var context = new CGBitmapContext(IntPtr.Zero, (int)imageRect.Width, (int)imageRect.Height, 8, 0, CGColorSpace.Null, CGBitmapFlags.Only)) { context.DrawImage(imageRect, oldImage.CGImage); CGImage alphaMask = context.ToImage(); var newImage = new UIImage(grayImage.WithMask(alphaMask)); grayImage.Dispose(); alphaMask.Dispose(); return(newImage); } }
public static UIImage CropByX(this UIImage image, nfloat x) { UIGraphics.BeginImageContextWithOptions(new CGSize(image.Size.Width - x, image.Size.Height), false, 0); UIImage result = null; using (CGContext context = UIGraphics.GetCurrentContext()) { context.TranslateCTM(0, image.Size.Height); context.ScaleCTM(1, -1); context.DrawImage(new CGRect(CGPoint.Empty, image.Size), image.CGImage); using (CGImage img = context.AsBitmapContext().ToImage()) { result = new UIImage(img, image.CurrentScale, UIImageOrientation.Up); img.Dispose(); } context.Dispose(); UIGraphics.EndImageContext(); } return(result); }
private void ReadTask() { results = barcodeReader.DecodeImage(uiImage, "", out error); if (results != null && results.Length > 0) { for (int i = 0; i < results.Length; i++) { if (i == 0) { result = "Code[1]: " + results[0].BarcodeText; } else { result = result + "\n\n" + "Code[" + (i + 1) + "]: " + results[i].BarcodeText; } } //Console.WriteLine(results[0].BarcodeText); } else { result = ""; } DispatchQueue.MainQueue.DispatchAsync(update); context.Dispose(); cgImage.Dispose(); uiImage.Dispose(); ready = true; }
public Image <Bgr, byte>?Grab() { _handle = IntPtr.Zero; try { _handle = CGDisplayCreateImage(_displayId); var cimg = new CGImage(_handle); var img = new Mat((int)cimg.Height, (int)cimg.Width, DepthType.Cv8U, 4); var output = new Mat((int)cimg.Height, (int)cimg.Width, DepthType.Cv8U, 3); var csRef = cimg.ColorSpace; var contextRef = new CGBitmapContext(img.DataPointer, cimg.Width, cimg.Height, 8, img.Step, csRef, CGImageAlphaInfo.PremultipliedLast); contextRef.DrawImage(new CGRect(0, 0, cimg.Width, cimg.Height), cimg); CvInvoke.CvtColor(img, output, ColorConversion.Rgba2Bgr); var ti = output.ToImage <Bgr, byte>(); output.Dispose(); img.Dispose(); cimg.Dispose(); if (_handle != IntPtr.Zero) { CFRelease(_handle); } var sized = ti.Resize(640, 480, Inter.Nearest); ti.Dispose(); return(sized); } catch (Exception e) { Log.Warning("Matt is exceptional: " + e); } return(null); } // End Sub CreateImage
public static UIImage MakeRoundCornerImage(UIImage img, int cornerWidth, int cornerHeight) { UIImage newImage = null; if (null != img) { var w = img.Size.Width; var h = img.Size.Height; CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB(); CGContext context = new CGBitmapContext(null, (int)w, (int)h, 8, (int)(4 * w), colorSpace, CGImageAlphaInfo.PremultipliedFirst); context.BeginPath(); var rect = new RectangleF(0, 0, img.Size.Width, img.Size.Height); AddRoundedRectToPath(context, rect, cornerWidth, cornerHeight); context.ClosePath(); context.Clip(); var cgImage = img.CGImage; context.DrawImage(new RectangleF(0, 0, w, h), cgImage); cgImage.Dispose(); CGImage imageMasked = ((CGBitmapContext)context).ToImage(); context.Dispose(); colorSpace.Dispose(); newImage = new UIImage(imageMasked); imageMasked.Dispose(); } return(newImage); }
void Apply(CGImage filteredImage, UIImage defaultImage, bool dirty) { if (filteredImage != null) { ImageView.Image = new UIImage(filteredImage); filteredImage.Dispose(); } else if (dirty) { ImageView.Image = defaultImage; } filtering = false; TryStopIndicatorForFilter(); if (needsFilter) { needsFilter = false; UpdateImage(true, false); } UpdateActivity(); UpdateConstraints(); UpdateZoom(); }
public override void LoadTexture(Texture t) { string path = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension(t.Name), "png"); CGDataProvider dataProvider = null; CGImage image = null; try { dataProvider = CGDataProvider.FromFile(path); image = CGImage.FromPNG(dataProvider, null, false, CGColorRenderingIntent.Default); LoadTextureFromImage(t, image); } catch (Exception) { t.Failed = true; return; } finally { if (dataProvider != null) { dataProvider.Dispose(); } if (image != null) { image.Dispose(); } } }
public void Dispose() { if (cgdata != null) { cgdata.Dispose(); cgdata = null; } if (cgimage != null) { cgimage.Dispose(); cgimage = null; } if (image != null) { image.Dispose(); image = null; } if (colorSpace != null) { colorSpace.Dispose(); colorSpace = null; } //if (bits != IntPtr.Zero) // Marshal.FreeHGlobal (bits); bits = null; }
internal static async Task <StorageItemThumbnail> CreateVideoThumbnailAsync(StorageFile file) { AVAsset asset = AVUrlAsset.FromUrl(NSUrl.FromFilename(file.Path)); AVAssetImageGenerator generator = AVAssetImageGenerator.FromAsset(asset); generator.AppliesPreferredTrackTransform = true; NSError error; CMTime actualTime; CMTime time = CMTime.FromSeconds(asset.Duration.Seconds / 2, asset.Duration.TimeScale); CGImage image = generator.CopyCGImageAtTime(time, out actualTime, out error); #if __MAC__ NSMutableData buffer = new NSMutableData(); CGImageDestination dest = CGImageDestination.Create(buffer, UTType.JPEG, 1, null); dest.AddImage(image); return(new StorageItemThumbnail(buffer.AsStream())); #else UIImage image2 = UIImage.FromImage(image); image.Dispose(); UIImage image3 = image2.Scale(new CGSize(240, 240)); image2.Dispose(); return(new StorageItemThumbnail(image3.AsJPEG().AsStream())); #endif }
public static UIImage MakeUIImageFromCIImage(this CIImage ciImage) { CIContext context = CIContext.Create(); CGImage cgImage = context.CreateCGImage(ciImage, ciImage.Extent);//[context createCGImage: ciImage fromRect:[ciImage extent]]; UIImage uiImage = new UIImage(cgImage); cgImage.Dispose(); return(uiImage); }
public void Dispose() { if (!disposed) { if (cgImage != null) { cgImage.Dispose(); } disposed = true; } }
protected override void Dispose(bool disposing) { if (disposing) { if (NativeCGImage != null) { NativeCGImage.Dispose(); NativeCGImage = null; } bitmapBlock = IntPtr.Zero; } base.Dispose(disposing); }
private void Dispose(bool disposing) { if (!disposed) { if (disposing) { if (cgImage != null) { cgImage.Dispose(); } } disposed = true; } }
public void Dispose() { if (Address == IntPtr.Zero) { return; } var nfo = (int)CGBitmapFlags.ByteOrder32Big | (int)CGImageAlphaInfo.PremultipliedLast; CGImage image = null; try { using (var colorSpace = CGColorSpace.CreateDeviceRGB()) using (var bContext = new CGBitmapContext(Address, Width, Height, 8, Width * 4, colorSpace, (CGImageAlphaInfo)nfo)) image = bContext.ToImage(); lock (_view.SyncRoot) { if (!_isDeferred) { using (var nscontext = NSGraphicsContext.CurrentContext) using (var context = nscontext.GraphicsPort) { context.SetFillColor(255, 255, 255, 255); context.FillRect(new CGRect(default(CGPoint), _view.LogicalSize)); context.TranslateCTM(0, _view.LogicalSize.Height - _logicalSize.Height); context.DrawImage(new CGRect(default(CGPoint), _logicalSize), image); context.Flush(); nscontext.FlushGraphics(); } } } } finally { if (image != null) { if (!_isDeferred) { image.Dispose(); } else { _view.SetBackBufferImage(new SavedImage(image, _logicalSize)); } } Marshal.FreeHGlobal(Address); Address = IntPtr.Zero; } }
private void BackgroundAnimationUp() { if (_mainBackground != null) { _view.BackgroundColor = _mainBackground; _mainBackground.Dispose(); _mainBackground = null; } else if (_mainBackgroundImage != null) { _view.Layer.Contents = _mainBackgroundImage; _mainBackgroundImage.Dispose(); _mainBackgroundImage = null; } }
public static byte[] grabScreenAsPNG(CGPoint containing) { // Grab screen // Mac stuff from http://stackoverflow.com/questions/18851247/screen-capture-on-osx-using-monomac NSScreen screen = NSScreen.MainScreen; if ((containing.X >= 0) && (containing.Y >= 0)) { int idx = 0; bool found = false; while (!found && (idx < NSScreen.Screens.Length)) { if (NSScreen.Screens[idx].Frame.Contains(containing)) { found = true; screen = NSScreen.Screens[idx]; } idx++; } } //System.Drawing.RectangleF bounds = new RectangleF(0,0,screen.Frame.GetMaxX(),screen.Frame.GetMaxY()); CGRect bounds = new CGRect((float)screen.Frame.GetMinX(), (float)screen.Frame.GetMinY(), (float)screen.Frame.GetMaxX(), (float)screen.Frame.GetMaxY()); //System.Drawing.Image si2; //NSImage si2; // CGImage screenImage = MonoMac.CoreGraphics.CGImage.ScreenImage(0,bounds); screenImage = ScreenImage2(0, bounds, CGWindowListOption.All, CGWindowImageOption.Default); #pragma warning disable XS0001 // Find usages of mono todo items /*using(NSBitmapImageRep imageRep = new NSBitmapImageRep(screenImage)) * { * NSDictionary properties = NSDictionary.FromObjectAndKey(new NSNumber(1.0), new NSString("NSImageCompressionFactor")); * using(NSData tiffData = imageRep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png, properties)) * { * * using (var ms = new MemoryStream()) * * { * tiffData.AsStream().CopyTo(ms); * si2 = NSImage.FromStream(ms); * //si2 = System.Drawing.Image.FromStream (ms, true); * } * } * }*/ NSBitmapImageRep si2 = new NSBitmapImageRep(screenImage); int newHeight = (int)((si2.Size.Height * imgWidth) / si2.Size.Width); CGSize destSize = new CGSize(imgWidth, newHeight); NSImage resized2 = new NSImage(destSize); resized2.LockFocus(); CGRect sz = new CGRect(0, 0, imgWidth, newHeight); //si2.DrawInRect(sz, new CGRect(0, 0, si2.Size.Width, si2.Size.Height), NSCompositingOperation.SourceOver, 1); si2.DrawInRect(sz); resized2.UnlockFocus(); resized2.Size = destSize; //Bitmap resized = new Bitmap(imgWidth, newHeight, PixelFormat.Format24bppRgb); //Graphics g = Graphics.FromImage (resized); //g.DrawImage (si2, 0, 0, imgWidth, newHeight); NSBitmapImageRep newRep = new NSBitmapImageRep(resized2.AsCGImage(ref sz, null, null)); NSData pngData = newRep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png); screenImage.Dispose(); byte[] result = null; result = pngData.ToArray(); //using (MemoryStream stream = new MemoryStream()) //{ // // // resized.Save(stream, ImageFormat.Png); // result = stream.ToArray(); //} return(result); }
void SetFrozenImageNeedsUpdate() { frozenImage?.Dispose(); frozenImage = null; }
private void dispose(bool disposing) { _uiImage?.Dispose(); _cgImage?.Dispose(); }
void Apply(CGImage filteredImage, UIImage defaultImage, bool dirty) { if (filteredImage != null) { ImageView.Image = new UIImage (filteredImage); filteredImage.Dispose (); } else if (dirty) { ImageView.Image = defaultImage; } filtering = false; TryStopIndicatorForFilter (); if (needsFilter) { needsFilter = false; UpdateImage (true, false); } UpdateActivity (); UpdateConstraints (); UpdateZoom (); }
/// <summary> /// Scales the and rotate image view. /// </summary> /// <returns>The and rotate image view.</returns> /// <param name="imageIn">Image in.</param> /// <param name="orIn">Or in.</param> public static UIImage ScaleAndRotateImageView(UIImage imageIn, UIImageOrientation orIn) { float kMaxResolution = 1024; UIImage imageCopy = imageIn; try { CGImage imgRef = imageIn.CGImage; imageIn.Dispose(); imageIn = null; float width = imgRef.Width; float height = imgRef.Height; Debug.WriteLine(string.Format("ScaleAndRotateImageView - line# {0}", 29)); CGAffineTransform transform = CGAffineTransform.MakeIdentity(); RectangleF bounds = new RectangleF(0, 0, width, height); if (width > kMaxResolution || height > kMaxResolution) { float ratio = width / height; if (ratio > 1) { bounds.Width = kMaxResolution; bounds.Height = bounds.Width / ratio; } else { bounds.Height = kMaxResolution; bounds.Width = bounds.Height * ratio; } } float scaleRatio = bounds.Width / width; SizeF imageSize = new SizeF(width, height); UIImageOrientation orient = orIn; float boundHeight; Debug.WriteLine(string.Format("ScaleAndRotateImageView - line# {0}", 53)); switch (orient) { case UIImageOrientation.Up: //EXIF = 1 transform = CGAffineTransform.MakeIdentity(); break; case UIImageOrientation.UpMirrored: //EXIF = 2 transform = CGAffineTransform.MakeTranslation(imageSize.Width, 0f); transform = CGAffineTransform.MakeScale(-1.0f, 1.0f); break; case UIImageOrientation.Down: //EXIF = 3 transform = CGAffineTransform.MakeTranslation(imageSize.Width, imageSize.Height); transform = CGAffineTransform.Rotate(transform, (float)Math.PI); break; case UIImageOrientation.DownMirrored: //EXIF = 4 transform = CGAffineTransform.MakeTranslation(0f, imageSize.Height); transform = CGAffineTransform.MakeScale(1.0f, -1.0f); break; case UIImageOrientation.LeftMirrored: //EXIF = 5 boundHeight = bounds.Height; bounds.Height = bounds.Width; bounds.Width = boundHeight; transform = CGAffineTransform.MakeTranslation(imageSize.Height, imageSize.Width); transform = CGAffineTransform.MakeScale(-1.0f, 1.0f); transform = CGAffineTransform.Rotate(transform, 3.0f * (float)Math.PI / 2.0f); break; case UIImageOrientation.Left: //EXIF = 6 boundHeight = bounds.Height; bounds.Height = bounds.Width; bounds.Width = boundHeight; transform = CGAffineTransform.MakeTranslation(0.0f, imageSize.Width); transform = CGAffineTransform.Rotate(transform, 3.0f * (float)Math.PI / 2.0f); break; case UIImageOrientation.RightMirrored: //EXIF = 7 boundHeight = bounds.Height; bounds.Height = bounds.Width; bounds.Width = boundHeight; transform = CGAffineTransform.MakeScale(-1.0f, 1.0f); transform = CGAffineTransform.Rotate(transform, (float)Math.PI / 2.0f); break; case UIImageOrientation.Right: //EXIF = 8 boundHeight = bounds.Height; bounds.Height = bounds.Width; bounds.Width = boundHeight; transform = CGAffineTransform.MakeTranslation(imageSize.Height, 0.0f); transform = CGAffineTransform.Rotate(transform, (float)Math.PI / 2.0f); break; default: //throw new Exception("Invalid image orientation"); Debug.WriteLine(string.Format("ScaleAndRotateImageView Invalid image orientation - line# {0}", 110)); break; } try { Debug.WriteLine(string.Format("ScaleAndRotateImageView - line# {0}", 115)); 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); } Debug.WriteLine(string.Format("ScaleAndRotateImageView - line# {0}", 130)); context.ConcatCTM(transform); context.DrawImage(new RectangleF(0, 0, width, height), imgRef); // added context dispose - to free memory used by picture image imgRef.Dispose(); imgRef = null; imageCopy.Dispose(); imageCopy = null; imageCopy = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); // added context dispose - to free memory used by the graphics context context.Dispose(); context = null; imageIn = null; } catch (Exception ex) { Debug.WriteLine("Exception Occured in ScaleAndRotateImageView - line # 164 method due to " + ex.Message); } } catch (Exception ex) { Debug.WriteLine("Exception Occured in ScaleAndRotateImageView - line # 169 method due to " + ex.Message); } return(imageCopy); }
public void SetOriginalImage(UIImage originalImage, CGRect cropFrame) { LoadIndicator.StartAnimating(); InvokeOnMainThread(() => { CGImage imageRef = originalImage.CGImage; UIImageOrientation imageOrientation = originalImage.Orientation; if (imageRef == null) { return; } var bytesPerRow = 0; var width = imageRef.Width; var height = imageRef.Height; var bitsPerComponent = imageRef.BitsPerComponent; CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB(); CGBitmapFlags bitmapInfo = imageRef.BitmapInfo; switch (imageOrientation) { case UIImageOrientation.RightMirrored: case UIImageOrientation.LeftMirrored: case UIImageOrientation.Right: case UIImageOrientation.Left: width = imageRef.Height; height = imageRef.Width; break; default: break; } CGSize imageSize = new CGSize(width, height); CGBitmapContext context = new CGBitmapContext(null, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo); colorSpace.Dispose(); if (context == null) { imageRef.Dispose(); return; } switch (imageOrientation) { case UIImageOrientation.RightMirrored: case UIImageOrientation.Right: context.TranslateCTM(imageSize.Width / 2, imageSize.Height / 2); context.RotateCTM(-((nfloat)Math.PI / 2)); context.TranslateCTM(-imageSize.Height / 2, -imageSize.Width / 2); break; case UIImageOrientation.LeftMirrored: case UIImageOrientation.Left: context.TranslateCTM(imageSize.Width / 2, imageSize.Height / 2); context.RotateCTM((nfloat)(Math.PI / 2)); context.TranslateCTM(-imageSize.Height / 2, -imageSize.Width / 2); break; case UIImageOrientation.Down: case UIImageOrientation.DownMirrored: context.TranslateCTM(imageSize.Width / 2, imageSize.Height / 2); context.RotateCTM((nfloat)Math.PI); context.TranslateCTM(-imageSize.Width / 2, -imageSize.Height / 2); break; default: break; } context.InterpolationQuality = CGInterpolationQuality.High; context.SetBlendMode(CGBlendMode.Copy); context.DrawImage(new CGRect(0, 0, imageRef.Width, imageRef.Height), imageRef); CGImage contextImage = context.ToImage(); context.Dispose(); if (contextImage != null) { _originalImage = UIImage.FromImage(contextImage, originalImage.CurrentScale, UIImageOrientation.Up); contextImage.Dispose(); } imageRef.Dispose(); BeginInvokeOnMainThread(() => { CGSize convertedImageSize = new CGSize(_originalImage.Size.Width / _cropSizeRatio, _originalImage.Size.Height / _cropSizeRatio); ImageView.Alpha = 0; ImageView.Image = _originalImage; CGSize sampleImageSize = new CGSize(Math.Max(convertedImageSize.Width, ScrollView.Frame.Size.Width), Math.Max(convertedImageSize.Height, ScrollView.Frame.Size.Height)); ScrollView.MinimumZoomScale = 1; ScrollView.MaximumZoomScale = 1; ScrollView.ZoomScale = 1; ImageView.Frame = new CGRect(0, 0, convertedImageSize.Width, convertedImageSize.Height); nfloat zoomScale = 1; if (convertedImageSize.Width < convertedImageSize.Height) { zoomScale = (ScrollView.Frame.Size.Width / convertedImageSize.Width); } else { zoomScale = (ScrollView.Frame.Size.Height / convertedImageSize.Height); } ScrollView.ContentSize = sampleImageSize; if (zoomScale < 1) { ScrollView.MinimumZoomScale = zoomScale; ScrollView.MaximumZoomScale = 1; ScrollView.ZoomScale = zoomScale; } else { ScrollView.MinimumZoomScale = zoomScale; ScrollView.MaximumZoomScale = zoomScale; ScrollView.ZoomScale = zoomScale; } ScrollView.ContentInset = UIEdgeInsets.Zero; ScrollView.ContentOffset = new CGPoint((ImageView.Frame.Size.Width - ScrollView.Frame.Size.Width) / 2, (ImageView.Frame.Size.Height - ScrollView.Frame.Size.Height) / 2); if (cropFrame.Size.Width > 0 && cropFrame.Size.Height > 0) { nfloat scale = UIScreen.MainScreen.Scale; nfloat newZoomScale = (_targetSize.Width * scale) / cropFrame.Size.Width; ScrollView.ZoomScale = newZoomScale; nfloat heightAdjustment = (_targetSize.Height / _cropSizeRatio) - ScrollView.ContentSize.Height; nfloat offsetY = cropFrame.Y + (heightAdjustment * _cropSizeRatio * scale); ScrollView.ContentOffset = new CGPoint(cropFrame.X / scale / _cropSizeRatio, (offsetY / scale / _cropSizeRatio) - heightAdjustment); } ScrollView.SetNeedsLayout(); UIView.Animate(0.3, () => { LoadIndicator.Alpha = 0; ImageView.Alpha = 1; }, () => { LoadIndicator.StopAnimating(); }); }); }); }