public Task <string> CreateThumbnailAsync(string videoPath) { return(Task.Run(() => { var url = NSUrl.FromFilename(videoPath); var asset = AVAsset.FromUrl(url); var assetImageGenerator = AVAssetImageGenerator.FromAsset(asset); assetImageGenerator.AppliesPreferredTrackTransform = true; var time = CMTime.FromSeconds(1, 1); using (var img = assetImageGenerator.CopyCGImageAtTime(time, out CMTime _, out NSError __)) { if (img == null) { Debug.WriteLine($"Could not find file at url: {videoPath}"); return string.Empty; } var outputPath = Path.ChangeExtension(videoPath, ".png"); var fileUrl = NSUrl.FromFilename(outputPath); using (var imageDestination = CGImageDestination.Create(fileUrl, UTType.PNG, 1)) { imageDestination.AddImage(img); imageDestination.Close(); } return outputPath; } })); }
public void SaveTo(Stream stream, CompressionFormat compression) { var data = new NSMutableData(); CGImageDestination dest = null; switch (compression) { case CompressionFormat.Jpeg: dest = CGImageDestination.Create(data, MobileCoreServices.UTType.JPEG, imageCount: 1); break; case CompressionFormat.Png: dest = CGImageDestination.Create(data, MobileCoreServices.UTType.PNG, imageCount: 1); break; } if (dest != null) { dest.AddImage(cgImage); dest.Close(); using (var bitmapStream = data.AsStream()) { bitmapStream.CopyTo(stream); } data.Dispose(); } }
public void FromData_BadITU() { using (NSMutableData destData = new NSMutableData()) { Assert.Null(CGImageDestination.Create(destData, BadUti, 1), "FromData-1"); Assert.Null(CGImageDestination.Create(destData, BadUti, 1, new CGImageDestinationOptions()), "FromData-2"); } }
internal static async Task <StorageItemThumbnail> CreatePhotoThumbnailAsync(StorageFile file) { #if __MAC__ NSImage image = NSImage.FromStream(await file.OpenStreamForReadAsync()); double ratio = image.Size.Width / image.Size.Height; NSImage newImage = new NSImage(new CGSize(240, 240 * ratio)); newImage.LockFocus(); image.Size = newImage.Size; image.Draw(new CGPoint(0, 0), new CGRect(0, 0, newImage.Size.Width, newImage.Size.Height), NSCompositingOperation.Copy, 1.0f); newImage.UnlockFocus(); NSMutableData buffer = new NSMutableData(); CGImageDestination dest = CGImageDestination.Create(buffer, UTType.JPEG, 1); dest.AddImage(newImage.CGImage); return(new StorageItemThumbnail(buffer.AsStream())); #else UIImage image = UIImage.FromFile(file.Path); UIImage image2 = image.Scale(new CGSize(240, 240)); image.Dispose(); return(new StorageItemThumbnail(image2.AsJPEG().AsStream())); #endif }
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 void Create_DataConsumer_BadUTI() { using (NSMutableData destData = new NSMutableData()) using (var consumer = new CGDataConsumer(destData)) { Assert.Null(CGImageDestination.Create(consumer, BadUti, 1), "Create-1"); Assert.Null(CGImageDestination.Create(consumer, BadUti, 1, new CGImageDestinationOptions()), "Create-2"); } }
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); } }
/// <summary> /// imageをPNGデータに変換します /// </summary> private static NSData ConvertImageToPng(CGImage image) { var storage = new NSMutableData(); var dest = CGImageDestination.Create(storage, MobileCoreServices.UTType.PNG, imageCount: 1); dest.AddImage(image); dest.Close(); return(storage); }
public void FromUrl_BadITU() { using (NSUrl url = NSUrl.FromString("file://local")) { #if XAMCORE_2_0 // FromUrl => Create Assert.Null(CGImageDestination.Create(url, BadUti, 1), "FromUrl-1"); #else Assert.Null(CGImageDestination.FromUrl(url, BadUti, 1), "FromUrl-1"); Assert.Null(CGImageDestination.FromUrl(url, BadUti, 1, new CGImageDestinationOptions()), "FromUrl-2"); #endif } }
public void FromData_GoodITU() { using (NSMutableData destData = new NSMutableData()) { using (var id = CGImageDestination.Create(destData, GoodUti, 1)) { Assert.That(id.Handle, Is.Not.EqualTo(IntPtr.Zero), "handle-1"); } using (var id = CGImageDestination.Create(destData, GoodUti, 1, new CGImageDestinationOptions())) { Assert.That(id.Handle, Is.Not.EqualTo(IntPtr.Zero), "handle-2"); } } }
private static void Save(CGImage screenshot, string path) { var fileURL = new NSUrl(path, false); using (var dataConsumer = new CGDataConsumer(fileURL)) { var imageDestination = CGImageDestination.Create(dataConsumer, imageFormat, 1); imageDestination.AddImage(screenshot); imageDestination.Close(); } }
private NSData GetDataWriteMetadata(UIImage originalImage, NSDictionary imageMetadata, float compress) { //return originalImage.AsJPEG(compress); // turn off efix CGImageSource imgSrc = CGImageSource.FromData(originalImage.AsJPEG(compress)); NSMutableData outImageData = new NSMutableData(); CGImageDestination dest = CGImageDestination.Create(outImageData, MobileCoreServices.UTType.JPEG, 1, new CGImageDestinationOptions()); dest.AddImage(imgSrc, 0, imageMetadata); dest.Close(); return(outImageData); }
public void FromData_BadITU() { using (NSMutableData destData = new NSMutableData()) { #if XAMCORE_2_0 // FromData => Create Assert.Null(CGImageDestination.Create(destData, BadUti, 1), "FromData-1"); Assert.Null(CGImageDestination.Create(destData, BadUti, 1, new CGImageDestinationOptions()), "FromData-2"); #else Assert.Null(CGImageDestination.FromData(destData, BadUti, 1), "FromData-1"); Assert.Null(CGImageDestination.FromData(destData, BadUti, 1, new CGImageDestinationOptions()), "FromData-2"); #endif } }
public void Create_DataConsumer_GoodUTI() { using (NSMutableData destData = new NSMutableData()) using (var consumer = new CGDataConsumer(destData)) { using (var id = CGImageDestination.Create(consumer, GoodUti, 1)) { Assert.That(id.Handle, Is.Not.EqualTo(IntPtr.Zero), "handle-1"); } using (var id = CGImageDestination.Create(consumer, GoodUti, 1, new CGImageDestinationOptions())) { Assert.That(id.Handle, Is.Not.EqualTo(IntPtr.Zero), "handle-2"); } } }
public void CopyImageSource() { TestRuntime.AssertXcodeVersion(5, 0); using (NSData data = NSData.FromFile(NSBundle.MainBundle.PathForResource("xamarin2", "png"))) using (var source = CGImageSource.FromData(data)) using (NSMutableData destData = new NSMutableData()) using (var id = CGImageDestination.Create(destData, GoodUti, 1)) { 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 new void Save(string path, ImageFormat format) { if (path == null) { throw new ArgumentNullException("path"); } // Obtain a URL file path to be passed NSUrl url = NSUrl.FromFilename(path); // Create an image destination that saves into the path that is passed in using (var dest = CGImageDestination.Create(url, GetTypeIdentifier(format), frameCount)) Save(dest); }
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()) { var fileOptions = new CGImageDestinationOptions { GifDictionary = new NSMutableDictionary() }; fileOptions.GifDictionary[ImageIO.CGImageProperties.GIFLoopCount] = new NSString("0"); //options.GifDictionary[ImageIO.CGImageProperties.GIFHasGlobalColorMap] = new NSString("true"); using (var destintation = CGImageDestination.Create(mutableData, MobileCoreServices.UTType.GIF, decoded.AnimatedImages.Length, fileOptions)) { for (var i = 0; i < decoded.AnimatedImages.Length; i++) { var options = new CGImageDestinationOptions { GifDictionary = new NSMutableDictionary() }; options.GifDictionary[ImageIO.CGImageProperties.GIFUnclampedDelayTime] = new NSString(decoded.AnimatedImages[i].Delay.ToString()); destintation.AddImage(decoded.AnimatedImages[i].Image.CGImage, options); } destintation.Close(); } result = new PImage(mutableData); // TODO I really don't know why representations count is 1, anyone? // var test = result.Representations(); } #endif } else { result = decoded.Image; } return(Task.FromResult(result)); }
public void SaveAsPng(string path) { if (string.IsNullOrEmpty(path)) { throw new ArgumentException("path"); } using (var dest = CGImageDestination.Create(NSUrl.FromFilename(path), "public.png", 1)) { if (dest == null) { throw new InvalidOperationException(string.Format("Could not create image destination {0}.", path)); } dest.AddImage(image); dest.Close(); } }
public void AddImage() { 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) using (var id = CGImageDestination.Create(destData, GoodUti, 1)) { id.AddImage(img, (NSDictionary)null); } }
public void AddImage() { 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 id.AddImage(img, (NSDictionary)null); } }
public new void Save(Stream stream, ImageFormat format) { if (stream == null) { throw new ArgumentNullException("stream"); } using (var imageData = new NSMutableData()) { using (var dest = CGImageDestination.Create(imageData, GetTypeIdentifier(format), frameCount)) Save(dest); using (var ms = imageData.AsStream()) ms.CopyTo(stream); } }
private async Task <OperationResult <MediaModel> > UploadPhoto(UIImage photo, NSDictionary metadata) { Stream stream = null; try { var compression = 1f; var maxCompression = 0.1f; int maxFileSize = _photoSize * 1024; var byteArray = photo.AsJPEG(compression); while (byteArray.Count() > maxFileSize && compression > maxCompression) { compression -= 0.1f; byteArray = photo.AsJPEG(compression); } if (metadata != null) { //exif setup var editedExifData = RemakeMetadata(metadata, photo); var newImageDataWithExif = new NSMutableData(); var imageDestination = CGImageDestination.Create(newImageDataWithExif, "public.jpeg", 0); imageDestination.AddImage(new UIImage(byteArray).CGImage, editedExifData); imageDestination.Close(); stream = newImageDataWithExif.AsStream(); } else { stream = byteArray.AsStream(); } var request = new UploadMediaModel(AppSettings.User.UserInfo, stream, ImageExtension); return(await _presenter.TryUploadMedia(request)); } catch (Exception ex) { AppSettings.Reporter.SendCrash(ex); return(new OperationResult <MediaModel>(new AppError(LocalizationKeys.PhotoProcessingError))); } finally { stream?.Flush(); stream?.Dispose(); } }
public void AddImageAndMetadata() { TestRuntime.AssertXcodeVersion(5, 0); 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 string CreateGif(string frame1Path, string frame2Path, string frame3Path, string frame4Path, string webId, string path = "") { List <UIImage> listOfFrame = new List <UIImage>(); UIImage image1 = new UIImage(frame1Path); listOfFrame.Add(image1); UIImage image2 = new UIImage(frame2Path); listOfFrame.Add(image2); UIImage image3 = new UIImage(frame3Path); listOfFrame.Add(image3); UIImage image4 = new UIImage(frame4Path); listOfFrame.Add(image4); NSMutableDictionary fileProperties = new NSMutableDictionary { { CGImageProperties.GIFLoopCount, new NSNumber(1) } }; NSUrl documentsDirectoryUrl = NSFileManager.DefaultManager.GetUrl(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User, null, true, out _); NSUrl fileUrl = documentsDirectoryUrl.Append(webId + ".gif", false); var destination = CGImageDestination.Create(fileUrl, MobileCoreServices.UTType.GIF, 4); destination.SetProperties(fileProperties); foreach (var frame in listOfFrame) { //difference is here, i create a var option and i set the //GifDictionary var options = new CGImageDestinationOptions(); options.GifDictionary = new NSMutableDictionary(); options.GifDictionary[CGImageProperties.GIFDelayTime] = new NSNumber(1f); var cgImage = frame.CGImage; if (cgImage != null) { destination.AddImage(cgImage, options); } } if (!destination.Close()) { Console.WriteLine("Failed to finalize the image destination"); } return(fileUrl.Path); }
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); } }
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); }
private void CaptureInMouse() { if ((NSEvent.CurrentMouseLocation.X - mPreCursorPos.X) * (NSEvent.CurrentMouseLocation.X - mPreCursorPos.X) + (NSEvent.CurrentMouseLocation.Y - mPreCursorPos.Y) * (NSEvent.CurrentMouseLocation.Y - mPreCursorPos.Y) < 0.1f * 0.1f) { return; } mPreCursorPos = NSEvent.CurrentMouseLocation; // var pos = NSEvent.CurrentMouseLocation; using (var cgScreenImage = ScreenCapture.CreateImage(mScreenDeviceId)) { // 保存到本地 var fileRootPath = "/Users/match/Documents/Temp/WowMonsterNamePics/monster_name_"; var filePath = fileRootPath + mFileNameId + ".png"; while (File.Exists(filePath)) { mFileNameId++; filePath = fileRootPath + mFileNameId + ".png"; } using (var url = new NSUrl("file", "localhost", filePath)) using (var destination = CGImageDestination.Create(url, "public.png", 1)) { destination.AddImage(cgScreenImage); destination.Close(); } if (Thread.CurrentThread.ManagedThreadId != mMainThreadId) { return; // 不在主线程,所以不能更新下面的界面显示 } // var rect = new CoreGraphics.CGRect(pos.X / 1920f * 3840f, (1f - pos.Y / 1080) * 2160f, 100f / 1920.0f * 3840, 100f / 1080f * 2160f); //using (var cgImage = cgScreenImage.WithImageInRect(rect)) var cgImage = cgScreenImage; using (var nsImage = new NSImage(cgImage, new SizeF(cgImage.Width, cgImage.Height))) { ImageView.Image = nsImage; } } }
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"); } }
// static CCVerticalTextAlignment vertical; // static CCTextAlignment horizontal; // Used for debuggin purposes internal static void SaveToFile(string fileName, CGBitmapContext bitmap) { if (bitmap == null) { throw new ObjectDisposedException("cgimage"); } // With MonoTouch we can use UTType from CoreMobileServices but since // MonoMac does not have that yet (or at least can not find it) I will // use the string version of those for now. I did not want to add another // #if #else in here. // for now we will just default this to png var typeIdentifier = "public.png"; // * NOTE * we only support one image for right now. //NSMutableData imgData = new NSMutableData(); NSUrl url = NSUrl.FromFilename(fileName); // Create an image destination that saves into the imgData #if IOS CGImageDestination dest = CGImageDestination.Create(url, typeIdentifier, 1); #else CGImageDestination dest = CGImageDestination.FromUrl(url, typeIdentifier, 1); #endif // Add an image to the destination dest.AddImage(bitmap.GetImage(), (NSDictionary)null); // Finish the export //bool success = dest.Close (); // if (success == false) // Console.WriteLine("did not work"); // else // Console.WriteLine("did work: " + path); dest.Dispose(); dest = null; }
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)); }