void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs args) { UIImage image = args.EditedImage ?? args.OriginalImage; if (image != null) { // Convert UIImage to .NET Stream object NSData data = image.AsJPEG(1); imagePath = Path.Combine(documentsDirectory + "/imageSelected.jpg"); NSError err = null; if (!data.Save(imagePath, false, out err)) { Console.WriteLine("Errore salvataggio foto temporanea, impossibile proseguire " + " Path " + imagePath); } Stream stream = data.AsStream(); // Set the Stream as the completion of the Task taskCompletionSource.SetResult(stream); } else { taskCompletionSource.SetResult(null); } imagePicker.DismissModalViewController(true); }
public FoundationResponse(NSData responseData, NSHttpUrlResponse urlResponse) { statusCode = urlResponse.StatusCode; var mutableData = responseData as NSMutableData; if (mutableData != null) { unsafe { stream = new UnmanagedMemoryStream((byte *)mutableData.Bytes, mutableData.Length); } } else { stream = responseData.AsStream(); } headers = new Dictionary <string, string> (); var hs = urlResponse.AllHeaderFields; foreach (var k in hs.Keys) { headers[k.ToString()] = hs.ObjectForKey(k).ToString(); } }
private void PlatformSaveAsJpeg(Stream stream, int width, int height) { #if MONOMAC || WINDOWS SaveAsImage(stream, width, height, ImageFormat.Jpeg); #elif ANDROID SaveAsImage(stream, width, height, Bitmap.CompressFormat.Jpeg); #elif IOS int mByteWidth = width * 4; // Assume 4 bytes/pixel for now mByteWidth = (mByteWidth + 3) & ~3; // Align to 4 bytes CGImage imageRef = GenerateRGBImageFromBufferData(mByteWidth, width, height); NSError err; using (UIImage img = UIImage.FromImage(imageRef)) { using (NSData imgData = img.AsJPEG()) { using (var imgJpeg = imgData.AsStream()) { imgJpeg.CopyTo(stream); } } //img.AsPNG().Save(filename, true, out err); // TODO - check err } #else throw new NotImplementedException(); #endif }
private void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs args) { string targetPath = null; UIImage image = args.EditedImage ?? args.OriginalImage; if (image != null) { // Convert UIImage to .NET Stream object NSData data = image.AsJPEG(1); using (System.IO.Stream stream = data.AsStream()) { string extension = ".jpg"; string fullFileName = FileNameWithoutExtension + extension; targetPath = System.IO.Path.Combine(CopyToDirectory, fullFileName); // copy the file to the destination and set the completion of the Task using (var copiedFileStream = new System.IO.FileStream(targetPath, System.IO.FileMode.OpenOrCreate)) { stream.CopyTo(copiedFileStream); } TaskCompletionSource.SetResult(fullFileName); // we'll reconstruct the path at runtime } } else { TaskCompletionSource.SetResult(null); } ImagePicker.DismissViewController(true, null); }
void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs args) { image = args.EditedImage ?? args.OriginalImage; if (image != null) { // Convert UIImage to .NET Stream object NSData data = image.AsJPEG(1); Stream stream = data.AsStream(); UnregisterEventHandlers(); // Set the Stream as the completion of the Task taskCompletionSource.SetResult(stream); } else { UnregisterEventHandlers(); taskCompletionSource.SetResult(null); } imagePicker.DismissModalViewController(true); this.view.ViewWillAppear(false); }
void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs args) { UIImage image = args.EditedImage ?? args.OriginalImage; if (image != null) { // Convert UIImage to .NET Stream object NSData data = image.AsJPEG(1); Stream stream = data.AsStream(); UnregisterEventHandlers(); // Set the Stream as the completion of the Task taskCompletionSource.SetResult(stream); //get path usage //var url = (NSUrl)args.Info.ValueForKey(new NSString("UIImagePickerControllerImageURL")); //taskCompletionSource.SetResult(url.Path); } else { //UnregisterEventHandlers(); taskCompletionSource.SetResult(null); } imagePicker.DismissModalViewController(true); }
public static StarInventory FromCloudData(NSData savedData) { var serializer = new DataContractJsonSerializer(typeof(CloudData)); var cloud = (CloudData)serializer.ReadObject(savedData.AsStream()); return(new StarInventory(cloud)); }
private void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs args) { // This is called when the user has finished making their selection. // Get the image - either with edits or without. UIImage image = args.EditedImage ?? args.OriginalImage; // Get the name of the file. _filename = args.ImageUrl.LastPathComponent; UnregisterEventHandlers(); if (image != null) { // Convert iOS image to .NET Stream. NSData data = image.AsJPEG(1); Stream stream = data.AsStream(); // Set the Stream as the completion of the Task. _taskCompletionSource.SetResult(stream); } else { _taskCompletionSource.SetResult(null); } // Hide the picker view. _imagePicker.DismissModalViewController(true); }
void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs args) { UIImage image = args.EditedImage ?? args.OriginalImage; if (image != null) { // Convert UIImage to .NET Stream object NSData data = image.AsJPEG(1); Stream stream = data.AsStream(); UnregisterEventHandlers(); // Set the Stream as the completion of the Task taskCompletionSource.SetResult( new Tuple <Stream, string, Services.MGFileType> (stream, args.ImageUrl.AbsoluteString, Services.MGFileType.Photo)); } else if (args.MediaUrl != null) { NSData data = NSData.FromUrl(args.MediaUrl); Stream stream = data.AsStream(); UnregisterEventHandlers(); taskCompletionSource.SetResult( new Tuple <Stream, string, Services.MGFileType> (stream, args.MediaUrl.AbsoluteString, Services.MGFileType.Video)); } else { UnregisterEventHandlers(); taskCompletionSource.SetResult(null); } imagePicker.DismissViewController(true, null); }
public byte[] ToByte(NSData data) { MemoryStream ms = new MemoryStream(); data.AsStream().CopyTo(ms); return(ms.ToArray()); }
public Response <UIImage> Load(Uri uri, bool localCacheOnly) { NSUrl url = NSUrl.FromString(uri.AbsoluteUri); var cachePolicy = localCacheOnly ? NSUrlRequestCachePolicy.ReturnCacheDataDoNotLoad : NSUrlRequestCachePolicy.ReturnCacheDataElseLoad; var request = new NSUrlRequest(url, cachePolicy, 20); NSCachedUrlResponse cachedResponse = NSUrlCache.SharedCache.CachedResponseForRequest(request); if (cachedResponse != null) { return(new Response <UIImage>(cachedResponse.Data.AsStream(), true, cachedResponse.Data.Length)); } NSUrlResponse response; NSError error; NSData data = NSUrlConnection.SendSynchronousRequest(request, out response, out error); if (error != null || data == null) { return(null); } cachedResponse = new NSCachedUrlResponse(response, data, null, NSUrlCacheStoragePolicy.Allowed); NSUrlCache.SharedCache.StoreCachedResponse(cachedResponse, request); return(new Response <UIImage>(data.AsStream(), false, data.Length)); }
public Stream DrawImage(Stream msSrc, Stream msDst, float xDest, float yDest) { using (CGImage src = UIImage.LoadFromData(NSData.FromStream(msSrc)).CGImage) { using (CGImage dst = UIImage.LoadFromData(NSData.FromStream(msDst)).CGImage) { UIGraphics.BeginImageContext(new SizeF((float)src.Width, (float)src.Height)); using (CGContext context = UIGraphics.GetCurrentContext()) { context.TranslateCTM(0, dst.Height); context.ScaleCTM(1, -1); context.DrawImage(new CGRect(0, 0, dst.Width, dst.Height), dst); context.DrawImage(new CGRect(xDest, yDest, src.Width, src.Height), src); var resultImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); NSData data = resultImage.AsPNG(); msDst = data.AsStream(); } } return(msDst); } }
public void SaveAsPng(Stream stream, int width, int height) { int mByteWidth = width * 4; // Assume 4 bytes/pixel for now mByteWidth = (mByteWidth + 3) & ~3; // Align to 4 bytes CGImage imageRef = createRGBImageFromBufferData(mByteWidth, width, height); // CGImageDestination dest = CGImageDestination.FromUrl (url, "public.tiff", 1, null); // dest.AddImage (imageRef, null); // // bool success = dest.Close (); // if (success == false) // Console.WriteLine("did not work"); // else // Console.WriteLine("did work"); // *** NOTE ** CGImageDestination is not working for some reason // so we will write this out using .net // get an NSBitmapImageRep of the CGImage NSBitmapImageRep rep = new NSBitmapImageRep(imageRef); // obtain the NSData as Tiff image format NSData data = rep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png, new NSDictionary()); // write the Tiff formatted data as a stream to the out file. WriteImageToStream(data.AsStream(), stream); }
internal static T DeserializeObject <T>(NSData data) { using (var stream = data.AsStream()) { Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes"); return((T) new BinaryFormatter().Deserialize(stream)); } }
public override async Task <int> ReadAsync(byte [] buffer, int offset, int count, CancellationToken cancellationToken) { // try to throw on enter ThrowIfNeeded(cancellationToken); while (current == null) { lock (dataLock) { if (data.Count == 0 && receivedAllData && position == length) { return(0); } if (data.Count > 0 && current == null) { current = data.Peek(); currentStream = current.AsStream(); break; } } await Task.Delay(50).ConfigureAwait(false); } // try to throw again before read ThrowIfNeeded(cancellationToken); var d = currentStream; var bufferCount = Math.Min(count, (int)(d.Length - d.Position)); var bytesRead = await d.ReadAsync(buffer, offset, bufferCount, cancellationToken).ConfigureAwait(false); // add the bytes read from the pointer to the position position += bytesRead; // remove the current primary reference if the current position has reached the end of the bytes if (d.Position == d.Length) { lock (dataLock) { // this is the same object, it was done to make the cleanup data.Dequeue(); currentStream?.Dispose(); // We cannot use current?.Dispose. The reason is the following one: // In the DidReceiveResponse, if iOS realizes that a buffer can be reused, // because the data is the same, it will do so. Such a situation does happen // between requests, that is, request A and request B will get the same NSData // (buffer) in the delegate. In this case, we cannot dispose the NSData because // it might be that a different request received it and it is present in // its NSUrlSessionDataTaskStream stream. We can only trust the gc to do the job // which is better than copying the data over. current = null; currentStream = null; } } return(bytesRead); }
private string WriteToTemporaryFile(NSData data) { var path = Path.GetTempFileName(); using (var stream = File.OpenWrite(path)) { data.AsStream().CopyTo(stream); } return(path); }
public Stream GetFilledCircleWithCenteredText(int imgSize, string rgbCircleColor, string txt, string rgbTextColor, string fontFamilyName, int fontSize) { Stream result = null; using (UIImage image = new UIImage()) { UIGraphics.BeginImageContext(new SizeF(imgSize, imgSize)); CGRect rect = new CGRect(0, 0, imgSize, imgSize); image.Draw(rect); using (CGContext g = UIGraphics.GetCurrentContext()) { float x = (float)(rect.X + (rect.Width / 2)); float y = (float)(rect.Y + (rect.Height / 2)); // Draws the circle UIColor background = FromHexString(rgbCircleColor); g.SetLineWidth(1); g.SetFillColor(background.CGColor); g.SetStrokeColor(background.CGColor); CGPath path = new CGPath(); path.AddArc(x, y, NMath.Min(rect.Width, rect.Height) / 2 - 1f, 0, 2.0f * (float)Math.PI, true); g.AddPath(path); g.DrawPath((CGPathDrawingMode.FillStroke)); // Draws the text g.SetFillColor(FromHexString(rgbTextColor).CGColor); var attributedString = new NSAttributedString(txt, new CoreText.CTStringAttributes { ForegroundColorFromContext = true, Font = new CoreText.CTFont(fontFamilyName, fontSize * 2) }); using (var textLine = new CoreText.CTLine(attributedString)) { g.TranslateCTM(x - (textLine.GetBounds(CoreText.CTLineBoundsOptions.UseGlyphPathBounds).Width / 2), y + (textLine.GetBounds(CoreText.CTLineBoundsOptions.UseGlyphPathBounds).Height / 2)); g.ScaleCTM(1, -1); textLine.Draw(g); } } var resultImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); NSData data = resultImage.AsPNG(); result = data.AsStream(); } return(result); }
public Stream GetArcPartFromSquareImage(Stream ms, int partNumber, int nbParts) { Stream result = null; int diameter = 0; using (UIImage image = UIImage.LoadFromData(NSData.FromStream(ms))) { diameter = (int)image.Size.Width; } float arcAngle = 360 / nbParts; float arcStart = 90 + (partNumber - 1) * arcAngle; if (nbParts > 2) { arcStart += (180 / nbParts); } float x = (float)(diameter / 2 - ((diameter * Math.Cos(DegreeToRadian(arcStart + arcAngle / 2)) + diameter) / 2)) / 2; float y = (float)(diameter / 2 - ((diameter * Math.Sin(DegreeToRadian(arcStart + arcAngle / 2)) + diameter) / 2)) / 2; float startX = (float)((diameter * Math.Cos(DegreeToRadian(arcStart)) + diameter) / 2); float startY = (float)((diameter * Math.Sin(DegreeToRadian(arcStart)) + diameter) / 2); ms.Seek(0, SeekOrigin.Begin); Stream moved = GetTranslated(ms, -x, y); using (UIImage temp = UIImage.LoadFromData(NSData.FromStream(moved))) { UIGraphics.BeginImageContext(new SizeF(temp.CGImage.Width, temp.CGImage.Height)); using (UIBezierPath path = new UIBezierPath()) { path.MoveTo(new CGPoint(diameter / 2, diameter / 2)); path.AddLineTo(new CGPoint(startX, startY)); path.AddArc(new CGPoint(diameter / 2, diameter / 2), diameter / 2, DegreeToRadian(arcStart), DegreeToRadian(arcStart + arcAngle), true); path.AddLineTo(new CGPoint(diameter / 2, diameter / 2)); path.AddClip(); temp.Draw(new Rectangle(0, 0, (int)temp.CGImage.Width, (int)temp.CGImage.Height)); var resultImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); NSData data = resultImage.AsPNG(); result = data.AsStream(); } } return(result); }
public override async Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { // try to throw on enter ThrowIfNeeded(cancellationToken); while (current == null) { lock (dataLock) { if (data.Count == 0 && receivedAllData && position == length) { return(0); } if (data.Count > 0 && current == null) { current = data.Peek(); currentStream = current.AsStream(); break; } } await Task.Delay(50).ConfigureAwait(false); } // try to throw again before read ThrowIfNeeded(cancellationToken); var d = currentStream; var bufferCount = Math.Min(count, (int)(d.Length - d.Position)); var bytesRead = await d.ReadAsync(buffer, offset, bufferCount, cancellationToken).ConfigureAwait(false); // add the bytes read from the pointer to the position position += bytesRead; // remove the current primary reference if the current position has reached the end of the bytes if (d.Position == d.Length) { lock (dataLock) { // this is the same object, it was done to make the cleanup data.Dequeue(); current?.Dispose(); currentStream?.Dispose(); current = null; currentStream = null; } } return(bytesRead); }
public override Stream GetResponseStream() { var mutableData = data as NSMutableData; if (mutableData != null) { unsafe { return(new UnmanagedMemoryStream((byte *)mutableData.Bytes, mutableData.Length)); } } else { return(data.AsStream()); } }
void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs args) { UIImage image = args.EditedImage ?? args.OriginalImage; if (image != null) { // Convert UIImage to .NET Stream object NSData data = image.AsJPEG(1); Stream stream = data.AsStream(); ExecuteCallBack(new PhotoPicturePickerModel { ImageStream = stream }); } imagePicker.DismissModalViewController(true); }
private void ItemLoadCompletedUrl(NSObject url) { log.Debug("ItemLoadCompletedUrl called of type: " + url.GetType().ToString()); try { NSUrl fileUrl = url as NSUrl; if (fileUrl != null) { log.Debug("Loading Attachment: " + fileUrl.ToString()); NSData data = null; string path = fileUrl.Path; DateTime creationDate = DateTime.Now; string fileName = Path.GetFileName(path); string extension = Path.GetExtension(fileUrl.Path); if (string.IsNullOrWhiteSpace(fileName)) { try { NSFileAttributes attributes = NSFileManager.DefaultManager.GetAttributes(fileUrl.Path); creationDate = (DateTime)attributes.CreationDate; } catch (Exception ex) { log.Debug(ex, "Unable to get Attributes for path: " + fileUrl.Path); } fileName = "FILE_" + creationDate.ToString("yyyyMMddTHHmmssFFF") + extension; } data = NSData.FromUrl(fileUrl); Stream stream = data.AsStream(); attachments.Add(stream); log.Info("Added Stream for File: " + fileName); } } catch (Exception ex) { log.Error(ex, "Error loading Attachment: " + url.ToString()); } this.totalNumberOfAttachmentsLoaded++; CheckAttachmentsProcessed(); }
protected override Task <AmazonUploadInfo> PerformUploadPhotoToAmazon(UploadRequest request) { return(base.ExecuteFunctionAsync("PerformUploadPhotoToAmazon", async delegate() { if (request.UploadInfo != null && request.UploadInfo.Success) { return request.UploadInfo; } UIImage image = request.NativeData as UIImage; if (image == null) { return new AmazonUploadInfo() { Success = false }; } string directory = Path.Combine(System.IO.Path.GetTempPath(), "StencilNative", "tmpupload"); Container.FileStore.EnsureFolderExists(directory); string path = Path.Combine(directory, "uploadtemp.jpg"); NSData data = image.AsJPEG(0.9f); using (var inputStream = data.AsStream()) { using (var fileStream = Container.FileStore.OpenWrite(path)) { CoreUtility.CopyStream(inputStream, fileStream); } } bool uploaded = await this.UploadDirect(path, request.FileName, request.OnUploadProgressChanged); if (!uploaded) { return new AmazonUploadInfo() { Success = false }; } request.UploadInfo = new AmazonUploadInfo() { Success = true, AmazonKey = request.FileName }; return request.UploadInfo; })); }
public ITexture GetTexture(string path) { if (path.IsNullOrWhiteSpace()) { return(TexturePool.Instance.GetTexture(null)); } FileAttributes attr = File.GetAttributes(path); bool isDirectory = (attr & FileAttributes.Directory) == FileAttributes.Directory; if (isDirectory && directoryTexture != null) { return(directoryTexture); } var ext = Path.GetExtension(path); if (ext == null) { return(TexturePool.Instance.GetTexture(null)); } if (textureCache.ContainsKey(ext)) { return(textureCache[ext]); } var icon = NSWorkspace.SharedWorkspace.IconForFileType(isDirectory ? NSFileTypeForHFSTypeCode.FinderIcon : ext); using (var stream = new MemoryStream()) using (var representation = new NSBitmapImageRep(icon.CGImage)) { NSData data = null; data = representation.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png); //, new NSDictionary()); using (var bitmapStream = data.AsStream()) { bitmapStream.CopyTo(stream); } data.Dispose(); var texture = new Texture2D(); texture.LoadImage(stream); if (isDirectory) { directoryTexture = texture; } else { textureCache.Add(ext, texture); } return(texture); } }
public Stream GetSquareAndScaled(Stream ms, int imgSize) { Stream result = null; using (UIImage image = UIImage.LoadFromData(NSData.FromStream(ms))) { UIGraphics.BeginImageContext(new SizeF(imgSize, imgSize)); image.Draw(new RectangleF(0, 0, imgSize, imgSize)); var resultImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); NSData data = resultImage.AsPNG(); result = data.AsStream(); } return(result); }
public Stream GetTranslated(Stream ms, float x, float y) { Stream result = null; using (UIImage image = UIImage.LoadFromData(NSData.FromStream(ms))) { UIGraphics.BeginImageContext(new SizeF((float)image.Size.Width, (float)image.Size.Height)); image.Draw(new RectangleF(x, -y, (float)image.Size.Width, (float)image.Size.Height)); var resultImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); NSData data = resultImage.AsPNG(); result = data.AsStream(); } return(result); }
public Stream GetScaled(Stream stream, int width, int height) { Stream result; using (UIImage image = UIImage.LoadFromData(NSData.FromStream(stream))) { UIGraphics.BeginImageContext(new SizeF(width, height)); image.Draw(new RectangleF(0, 0, width, height)); var resultImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); NSData data = resultImage.AsPNG(); result = data.AsStream(); } return(result); }
private void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs e) { UIImage image = e.EditedImage ?? e.OriginalImage; if (image != null) { NSData data = image.AsJPEG(1); Stream stream = data.AsStream(); _taskCompletionSource.SetResult(stream); } else { _taskCompletionSource.SetResult(null); } _imagePicker.DismissModalViewController(true); }
void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs args) { UIImage image = args.EditedImage ?? args.OriginalImage; if (image != null) { NSData data = image.AsJPEG(1); Stream stream = data.AsStream(); UnregisterEventHandlers(); taskCompletionSource.SetResult(stream); } else { UnregisterEventHandlers(); taskCompletionSource.SetResult(null); } imagePicker.DismissModalViewController(true); }
public override bool ReadFromData(NSData data, string typeName, out NSError?outError) { try { using (var s = data.AsStream()) using (var r = new StreamReader(s)) { Code = r.ReadToEnd(); encoding = r.CurrentEncoding; } outError = null; BeginInvokeOnMainThread(() => CodeChanged?.Invoke(this, EventArgs.Empty)); return(true); } catch (Exception ex) { Console.WriteLine(ex); outError = NSError.FromDomain(new NSString("CEditor"), 101); return(false); } }
public override void ReceivedData(NSUrlConnection connection, NSData data) { try { using (var dataStream = data.AsStream()) { byte[] bytes = new byte[dataStream.Length]; int offset = 0; int read = 0; do { read = dataStream.Read(bytes, offset, bytes.Length - offset); } while(read > 0); stream.AddByteArray(bytes); } } catch(Exception) { } }