public CGDataConsumer(NSMutableData data) { // not it's a __nullable parameter but it would return nil (see unit tests) and create an invalid instance if (data == null) throw new ArgumentNullException ("data"); handle = CGDataConsumerCreateWithCFData (data.Handle); }
public override void ReceivedData(NSUrlConnection connection, NSData data) { if (this.tempData == null) { this.tempData = new NSMutableData(); } this.tempData.AppendData(data); }
public static NSData ToPdf(this UIView view, RectangleF rect) { var data = new NSMutableData(); UIGraphics.BeginPDFContext(data, rect, null); UIGraphics.BeginPDFPage(); view.Draw(rect); UIGraphics.EndPDFContent(); return data; }
private void allocateMemoryWithLoopSize(UInt32 loopSize, UInt32 blockSize) { for (UInt32 i = 0; i < loopSize; i++) { NSData data = new NSMutableData(blockSize); NSArray array = new NSMutableArray((Int32)blockSize); NSSet set = new NSMutableSet((Int32)blockSize); this.dataProp = data; this.arrayProp = array; this.setProp = set; } }
public override void FinishedLoading(NSUrlConnection connection) { var downloadedImage = UIImage.LoadFromData(this.tempData); this.tempData = null; this.InvokeOnMainThread(() => { var imageView = this.tableView.CellAt(this.index).ViewWithTag(IncidentImageTag) as UIImageView; // check if the row was deallocated when the user scrolled away. ignore. if (imageView != null) { imageView.Image = downloadedImage; } }); }
NSData CreatePDF (string text, float w, float h) { NSMutableData data = new NSMutableData (); UIGraphics.BeginPDFContext (data, new RectangleF (0, 0, w, h), null); UIGraphics.BeginPDFPage (); CGContext gctx = UIGraphics.GetCurrentContext (); gctx.ScaleCTM (1, -1); gctx.TranslateCTM (0, -25f); gctx.SelectFont ("Helvetica", 25f, CGTextEncoding.MacRoman); gctx.ShowText (text); UIGraphics.EndPDFContent (); return data; }
void DrawPDFInMemory () { //data buffer to hold the PDF NSMutableData data = new NSMutableData (); //create a PDF with empty rectangle, which will configure it for 8.5x11 inches UIGraphics.BeginPDFContext (data, CGRect.Empty, null); //start a PDF page UIGraphics.BeginPDFPage (); using (CGContext g = UIGraphics.GetCurrentContext ()) { g.ScaleCTM (1, -1); g.TranslateCTM (0, -25); g.SelectFont ("Helvetica", 25, CGTextEncoding.MacRoman); g.ShowText ("Hello Core Graphics"); } //complete a PDF page UIGraphics.EndPDFContent (); }
void LectureEID() { FIDSmartCard card; FIDBelgianEidCard beid; string strNom = ""; string strAdresse = ""; Identity = new NSMutableData(); Adresse = new NSMutableData(); if (eID != null) { status = eID.Open(); if (status == FIDStatusCode.OK) { card = new FIDSmartCard(); card = eID.GetCard(status,true); if (status == FIDStatusCode.OK) { beid = new FIDBelgianEidCard(card); beid.ReadIdentityFile(Identity); beid.ReadAddressFile(Adresse); strNom = FIDBelgianEidCard.GetLastNameFromID((NSData)Identity); strAdresse = FIDBelgianEidCard.GetStreetAndNumberFromAddress((NSData)Adresse) + " " + FIDBelgianEidCard.GetMunicipalityFromAddress((NSData)Adresse); msg = new UIAlertView() { Title = "MEDINECT2020", Message = strNom + " " + strAdresse }; msg.AddButton("OK"); msg.Show(); } } eID.Close(); } }
public static SKIndex FromMutableData(NSMutableData data, string indexName) { if (data == null) { throw new ArgumentNullException("data"); } if (indexName == null) { throw new ArgumentNullException("indexName"); } using (var cfstr = new NSString(indexName)) { var h = SKIndexOpenWithMutableData(data.Handle, cfstr.Handle); if (h == IntPtr.Zero) { return(null); } return(new SKIndex(h)); } }
public static SKIndex CreateWithMutableData(NSMutableData data, string indexName, SKIndexType type, SKTextAnalysis analysisProperties) { if (data == null) { throw new ArgumentNullException("data"); } if (indexName == null) { throw new ArgumentNullException("indexName"); } using (var cfstr = new NSString(indexName)) { var h = SKIndexCreateWithMutableData(data.Handle, cfstr.Handle, type, analysisProperties == null ? IntPtr.Zero : analysisProperties.Dictionary.Handle); if (h == IntPtr.Zero) { return(null); } return(new SKIndex(h)); } }
public void SaveAsPng(Stream stream) { if (stream == null) { throw new ArgumentNullException(); } using (var data = new NSMutableData()) { using (var dest = CGImageDestination.Create(data, "public.png", 1)) { if (dest == null) { throw new InvalidOperationException(string.Format("Could not create image destination from {0}.", stream)); } dest.AddImage(image); dest.Close(); } data.AsStream().CopyTo(stream); } }
public void Create(int width, int height, PixelFormat pixelFormat) { switch (pixelFormat) { case PixelFormat.Format32bppRgb: { int numComponents = 4; int bitsPerComponent = 8; int bitsPerPixel = numComponents * bitsPerComponent; int bytesPerPixel = bitsPerPixel / 8; bytesPerRow = bytesPerPixel * width; Data = new NSMutableData((uint)(bytesPerRow * height)); provider = new CGDataProvider(Data.MutableBytes, (int)Data.Length, false); cgimage = new CGImage(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, CGColorSpace.CreateDeviceRGB(), CGBitmapFlags.ByteOrder32Little | CGBitmapFlags.PremultipliedFirst, provider, null, true, CGColorRenderingIntent.Default); Control = UIImage.FromImage(cgimage); break; } case PixelFormat.Format24bppRgb: { int numComponents = 3; int bitsPerComponent = 8; int bitsPerPixel = numComponents * bitsPerComponent; int bytesPerPixel = bitsPerPixel / 8; bytesPerRow = bytesPerPixel * width; Data = new NSMutableData((uint)(bytesPerRow * height)); provider = new CGDataProvider(Data.MutableBytes, (int)Data.Length, false); cgimage = new CGImage(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, CGColorSpace.CreateDeviceRGB(), CGBitmapFlags.ByteOrder32Little | CGBitmapFlags.PremultipliedFirst, provider, null, true, CGColorRenderingIntent.Default); Control = UIImage.FromImage(cgimage); break; } /*case PixelFormat.Format16bppRgb555: * control = new Gdk.Pixbuf(Gdk.Colorspace.Rgb, false, 5, width, height); * break;*/ default: throw new ArgumentOutOfRangeException("pixelFormat", pixelFormat, "Not supported"); } }
public override void OnStartPrint(PrintDocument document, PrintEventArgs e) { if (!document.PrinterSettings.IsValid) { throw new InvalidPrinterException(document.PrinterSettings); } /* maybe we should reuse the images, and clear them? */ //foreach (PreviewPageInfo pi in pageInfoList) // pi.Image.Dispose (); //pageInfoList.Clear (); previewData = new NSMutableData(); #if XAMARINMAC context = new CGContextPDF(new CGDataConsumer(previewData)); #elif MONOMAC context = new CGContextPDF(new CGDataConsumer(previewData), new CGRect(), new CGPDFInfo()); #endif }
void ReadData() { nuint bufferSize = 128; byte[] buffer = new byte[bufferSize]; while (_session.InputStream.HasBytesAvailable()) { nint bytesRead = _session.InputStream.Read(buffer, bufferSize); if (_readData == null) { _readData = new NSMutableData(); } _readData.AppendBytes(buffer, 0, bytesRead); Console.WriteLine(buffer); } NSNotificationCenter.DefaultCenter.PostNotificationName(SessionDataReceivedNotification, this); }
public new void Save(Stream stream, ImageFormat format) { if (stream == null) { throw new ArgumentNullException("stream"); } using (var imageData = new NSMutableData()) { #if !XAMARINMAC using (var dest = CGImageDestination.FromData(imageData, GetTypeIdentifier(format), frameCount)) #else using (var dest = CGImageDestination.Create(imageData, GetTypeIdentifier(format), frameCount)) #endif Save(dest); using (var ms = imageData.AsStream()) ms.CopyTo(stream); } }
public NSMutableData PrintToPdf() { var pdfData = new NSMutableData(); // Second parameter (CGRect bounds) of BeginPDFContext controls the size of the page onto which the content is rendered ... but not the content size. // So the content (if bigger) will be clipped (both vertically and horizontally). // Also, pagenation is determinted by the content - independent of the below CGRect bounds. UIGraphics.BeginPDFContext(pdfData, PaperRect, null); //UIGraphics.BeginPDFContext(pdfData, new CGRect(0, 0, 200, 300), null); PrepareForDrawingPages(new NSRange(0, NumberOfPages)); var rect = UIGraphics.PDFContextBounds; for (int i = 0; i < NumberOfPages; i++) { UIGraphics.BeginPDFPage(); DrawPage(i, rect); } UIGraphics.EndPDFContent(); return(pdfData); }
//Download File public void DownloadFile(CRCloudMetaData metaData) { new System.Threading.Thread(new System.Threading.ThreadStart(() => { InvokeOnMainThread(() => { CloudStorageLogic cloudStorageLogic = new CloudStorageLogic(); NSInputStream inputStream = cloudStorageLogic.DownloadFileWithPath(_cloudStorage, metaData.Path); NSMutableData data = new NSMutableData(); inputStream.Open(); var int32Value = metaData.Size.Int32Value; var intValue = metaData.Size.NIntValue; var buffer = new byte[1024]; while (inputStream.HasBytesAvailable()) { var len = inputStream.Read(buffer, 1024); data.AppendBytes(buffer); } if (inputStream.HasBytesAvailable() == false) { inputStream.Close(); var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var bytes = data.Bytes; string localFilename = metaData.Name; string localPath = Path.Combine(documents, localFilename); byte[] managedArray = new byte[intValue]; Marshal.Copy(bytes, managedArray, 0, int32Value); File.WriteAllBytes(localPath, managedArray); helper.Alert("Download Completed", "File downloaded and saved to file sharing", _controller); } }); })).Start(); }
public void CopyImageSource() { if (!TestRuntime.CheckSystemAndSDKVersion(7, 0)) { Assert.Ignore("Requires iOS 7+"); } using (NSData data = NSData.FromFile("xamarin2.png")) using (var source = CGImageSource.FromData(data)) using (NSMutableData destData = new NSMutableData()) #if XAMCORE_2_0 // FromData => Create using (var id = CGImageDestination.Create(destData, GoodUti, 1)) { #else using (var id = CGImageDestination.FromData(destData, GoodUti, 1)) { #endif NSError err; // testing that null is allowed (no crash) so the fact that is return false and an error does not matter Assert.False(id.CopyImageSource(source, (NSDictionary)null, out err), "CopyImageSource"); Assert.NotNull(err, "NSError"); } }
public static CGImageDestination?Create(NSMutableData data, string typeIdentifier, int imageCount, CGImageDestinationOptions?options = null) { if (data is null) { throw new ArgumentNullException(nameof(data)); } if (typeIdentifier is null) { throw new ArgumentNullException(nameof(typeIdentifier)); } using var dict = options?.ToDictionary(); var typeId = CFString.CreateNative(typeIdentifier); try { IntPtr p = CGImageDestinationCreateWithData(data.Handle, typeId, imageCount, dict.GetHandle()); return(p == IntPtr.Zero ? null : new CGImageDestination(p, true)); } finally { CFString.ReleaseNative(typeId); } }
public void AddImageAndMetadata() { if (!TestRuntime.CheckSystemAndSDKVersion(7, 0)) { Assert.Ignore("Requires iOS 7+"); } string file = Path.Combine(NSBundle.MainBundle.ResourcePath, "basn3p08.png"); using (NSMutableData destData = new NSMutableData()) using (var uiimg = UIImage.FromFile(file)) using (var img = uiimg.CGImage) #if XAMCORE_2_0 // FromData => Create using (var id = CGImageDestination.Create(destData, GoodUti, 1)) #else using (var id = CGImageDestination.FromData(destData, GoodUti, 1)) #endif using (var mutable = new CGMutableImageMetadata()) { id.AddImageAndMetadata(img, mutable, (NSDictionary)null); } }
public void RedrawPrePlumbingPDF(bool ThereAndBack, bool DocumentSigned) { if (ThereAndBack) { _navWorkflow.PopToRootViewController(false); } // render created preview in PDF context NSMutableData pdfData = new NSMutableData(); UIGraphics.BeginPDFContext(pdfData, _generatedPdfView.Bounds, null); UIGraphics.BeginPDFPage(); _generatedPdfView.Layer.RenderInContext(UIGraphics.GetCurrentContext()); UIGraphics.EndPDFContent(); // save the rendered context to disk NSError err; string pdfFileName; string pdfID = _navWorkflow._tabs._jobRunTable.CurrentCustomer.CustomerNumber.ToString() + "_PrePlumbingPDF"; if (DocumentSigned) { pdfFileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), pdfID + "_Signed.pdf"); } else { pdfFileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), pdfID + "_Not_Signed.pdf"); } pdfData.Save(pdfFileName, true, out err); err = null; pdfData = null; // load the content into Signing view controller _navWorkflow._tabs.SignPre.PDFView.MultipleTouchEnabled = true; _navWorkflow._tabs.SignPre.PDFView.ScalesPageToFit = true; _navWorkflow._tabs.SignPre.PDFView.LoadRequest(new NSUrlRequest(NSUrl.FromFilename(pdfFileName))); pdfPrePlumbingFileName = pdfFileName; // if (ThereAndBack) _navWorkflow.PushViewController (_navWorkflow._tabs._signView, true); }
public void AddImageAndMetadata() { TestRuntime.AssertXcodeVersion(5, 0); string file = Path.Combine(NSBundle.MainBundle.ResourcePath, "basn3p08.png"); using (NSMutableData destData = new NSMutableData()) #if MONOMAC using (var uiimg = new NSImage(NSBundle.MainBundle.PathForResource("basn3p08", "png"))) #else using (var uiimg = UIImage.FromFile(file)) #endif using (var img = uiimg.CGImage) #if XAMCORE_2_0 // FromData => Create using (var id = CGImageDestination.Create(destData, GoodUti, 1)) #else using (var id = CGImageDestination.FromData(destData, GoodUti, 1)) #endif using (var mutable = new CGMutableImageMetadata()) { id.AddImageAndMetadata(img, mutable, (NSDictionary)null); } }
/// <summary> /// Generates the pdf contents. /// </summary> /// <returns>The pdf in NSMutable data format.</returns> public NSMutableData GeneratePDF() { // data buffer to hold the PDF var data = new NSMutableData(); // create a PDF with empty rectangle, which will configure it for 8.5x11 inches UIGraphics.BeginPDFContext(data, CGRect.Empty, null); // configure the image size according to page size of PDF file DrawImageWithBoundingBox(_resultImage.ToCGImage()); // draw table table grids for categories in observation DrawCategorySummary(); // draw table table grids for all observations DrawObservationTable(); // complete a PDF page UIGraphics.EndPDFContent(); return(data); }
/// <summary> /// Exports the image as a PDF with the given file name. /// </summary> /// <param name="filename">Filename.</param> public static void ExportAsPDF(this UIImage image, string filename, CGPDFInfo info, double horizRes = 96, double vertRes = 96) { var width = (double)image.Size.Width * (double)image.CurrentScale * 72 * horizRes; var height = (double)image.Size.Height * (double)image.CurrentScale * 72 * vertRes; var pdfFile = new NSMutableData(); pdfFile.Init(); var pdfConsumer = new CGDataConsumer(pdfFile); var mediaBox = new CGRect(0, 0, width, height); using (var context = new CGContextPDF(pdfConsumer, mediaBox, info)) { context.BeginPage(new CGPDFPageInfo()); context.DrawImage(mediaBox, image.CGImage); context.EndPage(); } var attrs = new NSFileAttributes(); NSFileManager.DefaultManager.CreateFile(filename, pdfFile, attrs); }
private NSData PrintToPDFWithRenderer(UIPrintPageRenderer renderer, CGRect paperRect) { NSMutableData pdfData = new NSMutableData(); try { UIGraphics.BeginPDFContext(pdfData, paperRect, null); renderer.PrepareForDrawingPages(new NSRange(0, renderer.NumberOfPages)); for (int i = 0; i < renderer.NumberOfPages; i++) { UIGraphics.BeginPDFPage(); renderer.DrawPage(i, paperRect); } UIGraphics.EndPDFContent(); } catch { PDFToHtml.Status = PDFEnum.Failed; } return(pdfData); }
public void CopyImageSource() { TestRuntime.AssertXcodeVersion(5, 0); #if MONOMAC using (NSData data = NSData.FromFile(NSBundle.MainBundle.PathForResource("xamarin2", "png"))) #else using (NSData data = NSData.FromFile("xamarin2.png")) #endif using (var source = CGImageSource.FromData(data)) using (NSMutableData destData = new NSMutableData()) #if XAMCORE_2_0 // FromData => Create using (var id = CGImageDestination.Create(destData, GoodUti, 1)) { #else using (var id = CGImageDestination.FromData(destData, GoodUti, 1)) { #endif NSError err; // testing that null is allowed (no crash) so the fact that is return false and an error does not matter Assert.False(id.CopyImageSource(source, (NSDictionary)null, out err), "CopyImageSource"); Assert.NotNull(err, "NSError"); } }
protected override Task <PImage> GenerateImageFromDecoderContainerAsync(IDecodedImage <PImage> decoded, ImageInformation imageInformation, bool isPlaceholder) { PImage result; if (decoded.IsAnimated) { #if __IOS__ result = PImage.CreateAnimatedImage(decoded.AnimatedImages .Select(v => v.Image) .Where(v => v?.CGImage != null).ToArray(), decoded.AnimatedImages.Sum(v => v.Delay) / 100.0); #elif __MACOS__ using (var mutableData = NSMutableData.Create()) { using (var destintation = CGImageDestination.Create(mutableData, MobileCoreServices.UTType.GIF, decoded.AnimatedImages.Length)) { for (int i = 0; i < decoded.AnimatedImages.Length; i++) { var options = new CGImageDestinationOptions(); options.GifDictionary = new NSMutableDictionary(); options.GifDictionary[ImageIO.CGImageProperties.GIFDelayTime] = NSNumber.FromDouble(decoded.AnimatedImages[i].Delay / 100.0d); destintation.AddImage(decoded.AnimatedImages[i].Image.CGImage, options); } destintation.Close(); } // TODO I really don't know why it's not working. Anyone? result = new PImage(mutableData); } #endif } else { result = decoded.Image; } return(Task.FromResult(result)); }
public static SKIndex?CreateWithMutableData(NSMutableData data, string indexName, SKIndexType type, SKTextAnalysis analysisProperties) { if (data is null) { throw new ArgumentNullException(nameof(data)); } if (indexName is null) { throw new ArgumentNullException(nameof(indexName)); } var indexNameHandle = CFString.CreateNative(indexName); try { var handle = SKIndexCreateWithMutableData(data.Handle, indexNameHandle, type, analysisProperties.GetHandle()); if (handle == IntPtr.Zero) { return(null); } return(new SKIndex(handle, true)); } finally { CFString.ReleaseNative(indexNameHandle); } }
public static SKIndex?FromMutableData(NSMutableData data, string indexName) { if (data is null) { throw new ArgumentNullException(nameof(data)); } if (indexName is null) { throw new ArgumentNullException(nameof(indexName)); } var indexNameHandle = CFString.CreateNative(indexName); try { var handle = SKIndexOpenWithMutableData(data.Handle, indexNameHandle); if (handle == IntPtr.Zero) { return(null); } return(new SKIndex(handle, true)); } finally { CFString.ReleaseNative(indexNameHandle); } }
void UpdateTextHtml() { if (IsElementOrControlEmpty) { return; } string text = Element.Text ?? string.Empty; var attr = GetNSAttributedStringDocumentAttributes(); #if __MOBILE__ NSError nsError = null; Control.AttributedText = new NSAttributedString(text, attr, ref nsError); #else var htmlData = new NSMutableData(); htmlData.SetData(text); Control.AttributedStringValue = new NSAttributedString(htmlData, attr, out _); #endif _perfectSizeValid = false; }
public static CGImageDestination Create(NSMutableData data, string typeIdentifier, int imageCount, CGImageDestinationOptions options = null) { if (data == null) { throw new ArgumentNullException("data"); } if (typeIdentifier == null) { throw new ArgumentNullException("typeIdentifier"); } var dict = options == null ? null : options.ToDictionary(); var typeId = NSString.CreateNative(typeIdentifier); IntPtr p = CGImageDestinationCreateWithData(data.Handle, typeId, imageCount, dict == null ? IntPtr.Zero : dict.Handle); NSString.ReleaseNative(typeId); var ret = p == IntPtr.Zero ? null : new CGImageDestination(p, true); if (dict != null) { dict.Dispose(); } return(ret); }
public SKSurface CreateSurface(CGRect contentsBounds, nfloat scale, out SKImageInfo info) { // apply a scale contentsBounds.Width *= scale; contentsBounds.Height *= scale; // get context details Info = info = CreateInfo((int)contentsBounds.Width, (int)contentsBounds.Height); // if there are no pixels, clean up and return if (info.Width == 0 || info.Height == 0) { Dispose(); return(null); } // if the memory size has changed, then reset the underlying memory if (bitmapData?.Length != (nuint)info.BytesSize) { FreeBitmap(); } // allocate a memory block for the drawing process if (bitmapData == null) { bitmapData = NSMutableData.FromLength(info.BytesSize); dataProvider = new CGDataProvider(bitmapData.MutableBytes, info.BytesSize, Dummy); void Dummy(IntPtr data) { // do nothing as we manage the memory separately } } return(SKSurface.Create(info, bitmapData.MutableBytes, info.RowBytes)); }
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); }
public UrlDelegate(string name, Action<UIImage> success, Action<NSError> failure, NSUrlCredential credential) { _name = name; imgCallback = success; _credential = credential; _failure = failure; data = new NSMutableData(); }
public UrlDelegate(string name, Action<UIImage> success) { _name = name; imgCallback = success; data = new NSMutableData(); }
public void SaveAsPng(Stream stream) { if (stream == null) throw new ArgumentNullException (); using (var data = new NSMutableData ()) { using (var dest = CGImageDestination.Create (data, "public.png", 1)) { if (dest == null) { throw new InvalidOperationException (string.Format ("Could not create image destination from {0}.", stream)); } dest.AddImage (image); dest.Close (); } data.AsStream ().CopyTo (stream); } }
public ConnectionDelegate (Action<Stream,NSError> callback) { this.callback = callback; buffer = new NSMutableData (); }
public CGDataConsumer(NSMutableData data) { handle = CGDataConsumerCreateWithCFData(data.Handle); }
public static void BeginPDFContext(NSMutableData data, CGRect bounds, NSDictionary documentInfo) { UIGraphicsBeginPDFContextToData (data.Handle, bounds, documentInfo == null ? IntPtr.Zero: documentInfo.Handle); }
public override void FinishedLoading(NSUrlConnection connection) { _imageSetter(imageData); imageData.Dispose(); imageData = null; }
public UrlDelegate(string name, Action<string> success, Action failure, Action<NSUrlConnection, NSUrlAuthenticationChallenge> challenge) { _Name = name; _SuccessAction = success; _FailureAction = failure; _ChallengeAction = challenge; _Data = new NSMutableData(); }
void SignatureEID() { FIDSmartCard card; FIDBelgianEidCard beid; FIDPinDialogDescription pinDialog; string strNom = ""; string strAdresse = ""; Identity = new NSMutableData(); Adresse = new NSMutableData(); digest = new NSMutableData(); int intEssai = 0; NSData strSignature; if (eID != null) { status = eID.Open(); if (status == FIDStatusCode.OK) { statusSign = FIDStatusCode.WRONG_PIN; card = new FIDSmartCard(); card = eID.GetCard(status,true); if (status == FIDStatusCode.OK) { beid = new FIDBelgianEidCard(card); nsTexte = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; pinDialog = new FIDPinDialogDescription(); pinDialog.Lang = FIDPinDialogLang.French; pinDialog.PinMaxLength = 4; pinDialog.PinMinLength = 4; //pinDialog.Controller = this; strSignature = beid.SignData(nsTexte,FIDHashMethod.SHA1, ref statusSign, ref intEssai,digest,pinDialog); InvokeOnMainThread (delegate { if (statusSign == FIDStatusCode.OK) { msg = new UIAlertView() { Title = "MEDINECT", Message = strSignature.ToString() }; msg.AddButton("OK"); msg.Show(); } else { msg = new UIAlertView() { Title = "MEDINECT", Message = "Erreur : " + intEssai }; msg.AddButton("OK"); msg.Show(); } }); } } eID.Close(); } }
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); }
public NativeUrlDelegate (Action<string> success, Action<string> failure) { success_callback = success; failure_callback = failure; data = new NSMutableData(); }
public CGDataConsumer(NSMutableData data){ handle = CGDataConsumerCreateWithCFData(data.Handle); }
private CGImage CreateImage (CMSampleBuffer sampleBuffer) { CGImage image = null; CMFormatDescription formatDescription = sampleBuffer.GetFormatDescription (); var subType = formatDescription.MediaSubType; CMBlockBuffer blockBuffer = sampleBuffer.GetDataBuffer (); if (blockBuffer != null) { if (subType != (int)CMVideoCodecType.JPEG) throw new Exception ("Block buffer must be JPEG encoded."); var jpegData = new NSMutableData (); jpegData.Length = blockBuffer.DataLength; blockBuffer.CopyDataBytes (0, blockBuffer.DataLength, jpegData.Bytes); using (var imageSource = CGImageSource.FromData (jpegData)) { var decodeOptions = new CGImageOptions { ShouldAllowFloat = false, ShouldCache = false }; image = imageSource.CreateImage (0, decodeOptions); } } else { if (subType != (int)CVPixelFormatType.CV32BGRA) throw new Exception ("Image buffer must be BGRA encoded."); CVImageBuffer imageBuffer = sampleBuffer.GetImageBuffer (); using (var colorSpace = CGColorSpace.CreateDeviceRGB ()) using (var bitmapContext = new CGBitmapContext (imageBuffer.Handle, (int)imageBuffer.DisplaySize.Width, (int)imageBuffer.DisplaySize.Height, 8, 0, colorSpace, CGImageAlphaInfo.NoneSkipFirst)) { image = bitmapContext.ToImage (); } } return image; }
public void Save(Stream stream, ImageFormat format) { if (stream == null) throw new ArgumentNullException ("stream"); if (NativeCGImage == null) throw new ObjectDisposedException ("cgimage"); // for now we will just default this to png var typeIdentifier = "public.png"; // Get the correct type identifier if (format == ImageFormat.Bmp) typeIdentifier = "com.microsoft.bmp"; // else if (format == ImageFormat.Emf) // typeIdentifier = "image/emf"; // else if (format == ImageFormat.Exif) // typeIdentifier = "image/exif"; else if (format == ImageFormat.Gif) typeIdentifier = "com.compuserve.gif"; else if (format == ImageFormat.Icon) typeIdentifier = "com.microsoft.ico"; else if (format == ImageFormat.Jpeg) typeIdentifier = "public.jpeg"; else if (format == ImageFormat.Png) typeIdentifier = "public.png"; else if (format == ImageFormat.Tiff) typeIdentifier = "public.tiff"; else if (format == ImageFormat.Wmf) typeIdentifier = "com.adobe.pdf"; // Not sure what this is yet else if (format == ImageFormat.MemoryBmp) throw new NotImplementedException("ImageFormat.MemoryBmp not supported"); using (var imageData = new NSMutableData ()) { using (var dest = CGImageDestination.Create (imageData, typeIdentifier, frameCount)) { dest.AddImage (NativeCGImage, (NSDictionary)null); dest.Close (); } using (var ms = new MemoryStream (imageData.ToArray())) { ms.WriteTo (stream); stream.Seek (0,System.IO.SeekOrigin.Begin); } } }
/// <summary> /// Use this URL delegate if it is neeed to have more control over the connection /// </summary> /// <param name="success"></param> /// <param name="failure"></param> public NativeUrlDelegate(Action<NSMutableData, int> success, Action<string, int> failure) { _successCallback = success; _failureCallback = failure; _data = new NSMutableData(); }
// binding mistake -> NSMutableData, not NSData // naming mistake -> it's not From since it will write into (not read from) 'data' #if XAMCORE_2_0 public static CGImageDestination Create (NSMutableData data, string typeIdentifier, int imageCount, CGImageDestinationOptions options = null)
NSData NSDataFromDescription(string hexString) { hexString = hexString.Trim('<', '>').Replace(" ", string.Empty); NSMutableData data = new NSMutableData(); byte[] hexAsBytes = new byte[hexString.Length / 2]; for (int index = 0; index < hexAsBytes.Length; index++) { string byteValue = hexString.Substring(index * 2, 2); hexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture); } data.AppendBytes(hexAsBytes); return data; }
public UrlDelegate(string name, Action<string> success) { _name = name; strCallback = success; data = new NSMutableData(); }
public override void FailedWithError(NSUrlConnection connection, NSError error) { _data = null; }
public UrlDelegate(string name, Action<string> success, Action<NSError> failure) { _name = name; strCallback = success; _failure = failure; data = new NSMutableData(); }
public override void FinishedLoading(NSUrlConnection connection) { if (_data == null) return; var scriptNotifyAndContent = ScriptNotify; scriptNotifyAndContent += NSString.FromData(_data, NSStringEncoding.UTF8).ToString(); _data = null; _controller._webView.LoadHtmlString(scriptNotifyAndContent, _controller.Url); }
public ConnectionDelegate(Action <Stream, NSError> callback) { this.callback = callback; buffer = new NSMutableData(); }
public CommsDelegate(string name, Action<string> success, Action failure) { _name = name; callback = success; _failure = failure; data = new NSMutableData (); }
protected INativeObject GetINativeInstance(Type t) { var ctor = t.GetConstructor(Type.EmptyTypes); if ((ctor != null) && !ctor.IsAbstract) { return(ctor.Invoke(null) as INativeObject); } if (!NativeObjectInterfaceType.IsAssignableFrom(t)) { throw new ArgumentException("t"); } switch (t.Name) { case "CFAllocator": return(CFAllocator.SystemDefault); case "CFBundle": var bundles = CFBundle.GetAll(); if (bundles.Length > 0) { return(bundles [0]); } else { throw new InvalidOperationException(string.Format("Could not create the new instance for type {0}.", t.Name)); } case "CFNotificationCenter": return(CFNotificationCenter.Darwin); case "CFReadStream": case "CFStream": CFReadStream readStream; CFWriteStream writeStream; CFStream.CreatePairWithSocketToHost("www.google.com", 80, out readStream, out writeStream); return(readStream); case "CFWriteStream": CFStream.CreatePairWithSocketToHost("www.google.com", 80, out readStream, out writeStream); return(writeStream); case "CFUrl": return(CFUrl.FromFile("/etc")); case "CFPropertyList": return(CFPropertyList.FromData(NSData.FromString("<string>data</string>")).PropertyList); case "DispatchData": return(DispatchData.FromByteBuffer(new byte [] { 1, 2, 3, 4 })); case "AudioFile": var path = Path.GetFullPath("1.caf"); var af = AudioFile.Open(CFUrl.FromFile(path), AudioFilePermission.Read, AudioFileType.CAF); return(af); case "CFHTTPMessage": return(CFHTTPMessage.CreateEmpty(false)); case "CFMutableString": return(new CFMutableString("xamarin")); case "CGBitmapContext": byte[] data = new byte [400]; using (CGColorSpace space = CGColorSpace.CreateDeviceRGB()) { return(new CGBitmapContext(data, 10, 10, 8, 40, space, CGBitmapFlags.PremultipliedLast)); } case "CGContextPDF": var filename = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + "/t.pdf"; using (var url = new NSUrl(filename)) return(new CGContextPDF(url)); case "CGColorConversionInfo": var cci = new GColorConversionInfoTriple() { Space = CGColorSpace.CreateGenericRgb(), Intent = CGColorRenderingIntent.Default, Transform = CGColorConversionInfoTransformType.ApplySpace }; return(new CGColorConversionInfo((NSDictionary)null, cci, cci, cci)); case "CGDataConsumer": using (NSMutableData destData = new NSMutableData()) { return(new CGDataConsumer(destData)); } case "CGDataProvider": filename = "xamarin1.png"; return(new CGDataProvider(filename)); case "CGFont": return(CGFont.CreateWithFontName("Courier New")); case "CGPattern": return(new CGPattern( new RectangleF(0, 0, 16, 16), CGAffineTransform.MakeIdentity(), 16, 16, CGPatternTiling.NoDistortion, true, (cgc) => {})); case "CMBufferQueue": return(CMBufferQueue.CreateUnsorted(2)); case "CTFont": CTFontDescriptorAttributes fda = new CTFontDescriptorAttributes() { FamilyName = "Courier", StyleName = "Bold", Size = 16.0f }; using (var fd = new CTFontDescriptor(fda)) return(new CTFont(fd, 10)); case "CTFontCollection": return(new CTFontCollection(new CTFontCollectionOptions())); case "CTFontDescriptor": fda = new CTFontDescriptorAttributes(); return(new CTFontDescriptor(fda)); case "CTTextTab": return(new CTTextTab(CTTextAlignment.Left, 2)); case "CTTypesetter": return(new CTTypesetter(new NSAttributedString("Hello, world", new CTStringAttributes() { ForegroundColorFromContext = true, Font = new CTFont("ArialMT", 24) }))); case "CTFrame": var framesetter = new CTFramesetter(new NSAttributedString("Hello, world", new CTStringAttributes() { ForegroundColorFromContext = true, Font = new CTFont("ArialMT", 24) })); var bPath = UIBezierPath.FromRect(new RectangleF(0, 0, 3, 3)); return(framesetter.GetFrame(new NSRange(0, 0), bPath.CGPath, null)); case "CTFramesetter": return(new CTFramesetter(new NSAttributedString("Hello, world", new CTStringAttributes() { ForegroundColorFromContext = true, Font = new CTFont("ArialMT", 24) }))); case "CTGlyphInfo": return(new CTGlyphInfo("copyright", new CTFont("ArialMY", 24), "Foo")); case "CTLine": return(new CTLine(new NSAttributedString("Hello, world", new CTStringAttributes() { ForegroundColorFromContext = true, Font = new CTFont("ArialMT", 24) }))); case "CGImageDestination": var storage = new NSMutableData(); return(CGImageDestination.Create(new CGDataConsumer(storage), "public.png", 1)); case "CGImageMetadataTag": using (NSString name = new NSString("tagName")) using (var value = new NSString("value")) return(new CGImageMetadataTag(CGImageMetadataTagNamespaces.Exif, CGImageMetadataTagPrefixes.Exif, name, CGImageMetadataType.Default, value)); case "CGImageSource": filename = "xamarin1.png"; return(CGImageSource.FromUrl(NSUrl.FromFilename(filename))); case "SecPolicy": return(SecPolicy.CreateSslPolicy(false, null)); case "SecIdentity": using (var options = NSDictionary.FromObjectAndKey(new NSString("farscape"), SecImportExport.Passphrase)) { NSDictionary[] array; var result = SecImportExport.ImportPkcs12(farscape_pfx, options, out array); if (result != SecStatusCode.Success) { throw new InvalidOperationException(string.Format("Could not create the new instance for type {0} due to {1}.", t.Name, result)); } return(new SecIdentity(array [0].LowlevelObjectForKey(SecImportExport.Identity.Handle))); } case "SecTrust": X509Certificate x = new X509Certificate(mail_google_com); using (var policy = SecPolicy.CreateSslPolicy(true, "mail.google.com")) return(new SecTrust(x, policy)); case "SslContext": return(new SslContext(SslProtocolSide.Client, SslConnectionType.Stream)); case "UIFontFeature": return(new UIFontFeature(CTFontFeatureNumberSpacing.Selector.ProportionalNumbers)); case "NetworkReachability": return(new NetworkReachability(IPAddress.Loopback, null)); case "VTCompressionSession": case "VTSession": return(VTCompressionSession.Create(1024, 768, CMVideoCodecType.H264, (sourceFrame, status, flags, buffer) => { }, null, (CVPixelBufferAttributes)null)); case "VTFrameSilo": return(VTFrameSilo.Create()); case "VTMultiPassStorage": return(VTMultiPassStorage.Create()); case "CFString": return(new CFString("test")); case "DispatchBlock": return(new DispatchBlock(() => { })); case "DispatchQueue": return(new DispatchQueue("com.example.subsystem.taskXYZ")); case "DispatchGroup": return(DispatchGroup.Create()); case "CGColorSpace": return(CGColorSpace.CreateDeviceCmyk()); case "CGGradient": CGColor[] cArray = { UIColor.Black.CGColor, UIColor.Clear.CGColor, UIColor.Blue.CGColor }; return(new CGGradient(null, cArray)); case "CGImage": filename = "xamarin1.png"; using (var dp = new CGDataProvider(filename)) return(CGImage.FromPNG(dp, null, false, CGColorRenderingIntent.Default)); case "CGColor": return(UIColor.Black.CGColor); case "CMClock": return(CMClock.HostTimeClock); case "CMTimebase": return(new CMTimebase(CMClock.HostTimeClock)); case "CVPixelBufferPool": return(new CVPixelBufferPool( new CVPixelBufferPoolSettings(), new CVPixelBufferAttributes(CVPixelFormatType.CV24RGB, 100, 50) )); case "SecCertificate": using (var cdata = NSData.FromArray(mail_google_com)) return(new SecCertificate(cdata)); case "SecCertificate2": using (var cdata = NSData.FromArray(mail_google_com)) return(new SecCertificate2(new SecCertificate(cdata))); case "SecTrust2": X509Certificate x2 = new X509Certificate(mail_google_com); using (var policy = SecPolicy.CreateSslPolicy(true, "mail.google.com")) return(new SecTrust2(new SecTrust(x2, policy))); case "SecIdentity2": using (var options = NSDictionary.FromObjectAndKey(new NSString("farscape"), SecImportExport.Passphrase)) { NSDictionary[] array; var result = SecImportExport.ImportPkcs12(farscape_pfx, options, out array); if (result != SecStatusCode.Success) { throw new InvalidOperationException(string.Format("Could not create the new instance for type {0} due to {1}.", t.Name, result)); } return(new SecIdentity2(new SecIdentity(array [0].LowlevelObjectForKey(SecImportExport.Identity.Handle)))); } case "SecKey": SecKey private_key; SecKey public_key; using (var record = new SecRecord(SecKind.Key)) { record.KeyType = SecKeyType.RSA; record.KeySizeInBits = 512; // it's not a performance test :) SecKey.GenerateKeyPair(record.ToDictionary(), out public_key, out private_key); return(private_key); } case "SecAccessControl": return(new SecAccessControl(SecAccessible.WhenPasscodeSetThisDeviceOnly)); default: throw new InvalidOperationException(string.Format("Could not create the new instance for type {0}.", t.Name)); } }
public EscozUrlStreamDelegate(string name, Action<Stream> success) { _name = name; callback = success; data = new NSMutableData(); }
public static void BeginPDFContext(NSMutableData data, CGRect bounds, NSDictionary documentInfo) { UIGraphicsBeginPDFContextToData(data.Handle, bounds, documentInfo == null ? IntPtr.Zero: documentInfo.Handle); }
public override void ReceivedData (NSUrlConnection connection, NSData data) { if (imageData==null) imageData = new NSMutableData(); imageData.AppendData(data); }