public static async Task <TLPhotoSizeBase> GetFileThumbnailAsync(StorageFile file) { //file = await Package.Current.InstalledLocation.GetFileAsync("Assets\\Thumb.jpg"); var imageProps = await file.Properties.GetImagePropertiesAsync(); var videoProps = await file.Properties.GetVideoPropertiesAsync(); if (imageProps.Width > 0 || videoProps.Width > 0) { using (var thumb = await file.GetThumbnailAsync(ThumbnailMode.SingleItem, 96, ThumbnailOptions.ResizeThumbnail)) { if (thumb != null) { var randomStream = thumb as IRandomAccessStream; var originalWidth = (int)thumb.OriginalWidth; var originalHeight = (int)thumb.OriginalHeight; if (thumb.ContentType != "image/jpeg") { var memoryStream = new InMemoryRandomAccessStream(); var bitmapDecoder = await BitmapDecoder.CreateAsync(thumb); var pixelDataProvider = await bitmapDecoder.GetPixelDataAsync(); var bitmapEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, memoryStream); bitmapEncoder.SetPixelData(bitmapDecoder.BitmapPixelFormat, BitmapAlphaMode.Ignore, bitmapDecoder.PixelWidth, bitmapDecoder.PixelHeight, bitmapDecoder.DpiX, bitmapDecoder.DpiY, pixelDataProvider.DetachPixelData()); await bitmapEncoder.FlushAsync(); randomStream = memoryStream; } var fileLocation = new TLFileLocation { VolumeId = TLLong.Random(), LocalId = TLInt.Random(), Secret = TLLong.Random(), DCId = 0 }; var desiredName = string.Format("{0}_{1}_{2}.jpg", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret); var desiredFile = await CreateTempFileAsync(desiredName); var buffer = new Windows.Storage.Streams.Buffer(Convert.ToUInt32(randomStream.Size)); var buffer2 = await randomStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None); using (var stream = await desiredFile.OpenAsync(FileAccessMode.ReadWrite)) { await stream.WriteAsync(buffer2); stream.Dispose(); } var result = new TLPhotoSize { W = originalWidth, H = originalHeight, Size = (int)randomStream.Size, Type = string.Empty, Location = fileLocation }; randomStream.Dispose(); return(result); } } } return(null); }
private async void GetImageAutomatic_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrWhiteSpace(Protocol.Text)) { EmptyTip.Target = Protocol; EmptyTip.IsOpen = true; return; } switch (Type) { case QuickStartType.Application: { if (Uri.TryCreate(Protocol.Text, UriKind.Absolute, out Uri Result)) { if (Result.IsFile) { if (await FileSystemStorageItemBase.CheckExistAsync(Protocol.Text)) { try { StorageFile ExecuteFile = await StorageFile.GetFileFromPathAsync(Protocol.Text); IDictionary <string, object> PropertiesDictionary = await ExecuteFile.Properties.RetrievePropertiesAsync(new string[] { "System.FileDescription" }); string ExtraAppName = string.Empty; if (PropertiesDictionary.TryGetValue("System.FileDescription", out object DescriptionRaw)) { ExtraAppName = Convert.ToString(DescriptionRaw); } DisplayName.Text = string.IsNullOrEmpty(ExtraAppName) ? ExecuteFile.DisplayName : ExtraAppName; StorageFile FileThumbnail = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("FileThumbnail.png", CreationCollisionOption.ReplaceExisting); if (await ExecuteFile.GetThumbnailRawStreamAsync() is IRandomAccessStream ThumbnailStream) { BitmapDecoder Decoder = await BitmapDecoder.CreateAsync(ThumbnailStream); using (SoftwareBitmap SBitmap = await Decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied)) using (SoftwareBitmap ResizeBitmap = ComputerVisionProvider.ResizeToActual(SBitmap)) using (InMemoryRandomAccessStream ResizeBitmapStream = new InMemoryRandomAccessStream()) { BitmapEncoder Encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ResizeBitmapStream); Encoder.SetSoftwareBitmap(ResizeBitmap); await Encoder.FlushAsync(); BitmapImage Image = new BitmapImage(); Icon.Source = Image; await Image.SetSourceAsync(ResizeBitmapStream); ResizeBitmapStream.Seek(0); using (Stream TransformStream = ResizeBitmapStream.AsStreamForRead()) using (Stream FileStream = await FileThumbnail.OpenStreamForWriteAsync()) { await TransformStream.CopyToAsync(FileStream); } } } else { Uri PageUri = AppThemeController.Current.Theme == ElementTheme.Dark ? new Uri("ms-appx:///Assets/Page_Solid_White.png") : new Uri("ms-appx:///Assets/Page_Solid_Black.png"); StorageFile PageFile = await StorageFile.GetFileFromApplicationUriAsync(PageUri); using (IRandomAccessStream PageStream = await PageFile.OpenAsync(FileAccessMode.Read)) { BitmapImage Image = new BitmapImage(); Icon.Source = Image; await Image.SetSourceAsync(PageStream); PageStream.Seek(0); using (Stream TransformStream = PageStream.AsStreamForRead()) using (Stream FileStream = await FileThumbnail.OpenStreamForWriteAsync()) { await TransformStream.CopyToAsync(FileStream); } } } ImageFile = FileThumbnail; } catch { FailureTips.IsOpen = true; } } else { FailureTips.IsOpen = true; } } else { if ((await Launcher.FindUriSchemeHandlersAsync(Result.Scheme)).ToList().FirstOrDefault() is AppInfo App) { DisplayName.Text = App.DisplayInfo.DisplayName; StorageFile FileThumbnail = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("FileThumbnail.png", CreationCollisionOption.ReplaceExisting); using (IRandomAccessStreamWithContentType LogoStream = await App.DisplayInfo.GetLogo(new Windows.Foundation.Size(120, 120)).OpenReadAsync()) { BitmapDecoder Decoder = await BitmapDecoder.CreateAsync(LogoStream); using (SoftwareBitmap SBitmap = await Decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied)) using (SoftwareBitmap ResizeBitmap = ComputerVisionProvider.ResizeToActual(SBitmap)) using (InMemoryRandomAccessStream ResizeBitmapStream = new InMemoryRandomAccessStream()) { BitmapEncoder Encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ResizeBitmapStream); Encoder.SetSoftwareBitmap(ResizeBitmap); await Encoder.FlushAsync(); BitmapImage Source = new BitmapImage(); Icon.Source = Source; await Source.SetSourceAsync(ResizeBitmapStream); ResizeBitmapStream.Seek(0); using (Stream FileStream = await FileThumbnail.OpenStreamForWriteAsync()) { await ResizeBitmapStream.AsStreamForRead().CopyToAsync(FileStream); } } } ImageFile = FileThumbnail; } else { FormatErrorTip.IsOpen = true; } } } else { using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController()) { if (await Exclusive.Controller.GetInstalledApplicationAsync(Protocol.Text) is InstalledApplication Pack) { StorageFile FileThumbnail = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("FileThumbnail.png", CreationCollisionOption.ReplaceExisting); if (Pack.CreateStreamFromLogoData() is Stream LogoStream) { try { BitmapDecoder Decoder = await BitmapDecoder.CreateAsync(LogoStream.AsRandomAccessStream()); using (SoftwareBitmap SBitmap = await Decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied)) using (SoftwareBitmap ResizeBitmap = ComputerVisionProvider.ResizeToActual(SBitmap)) using (InMemoryRandomAccessStream ResizeBitmapStream = new InMemoryRandomAccessStream()) { BitmapEncoder Encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ResizeBitmapStream); Encoder.SetSoftwareBitmap(ResizeBitmap); await Encoder.FlushAsync(); BitmapImage Image = new BitmapImage(); Icon.Source = Image; await Image.SetSourceAsync(ResizeBitmapStream); ResizeBitmapStream.Seek(0); using (Stream FileStream = await FileThumbnail.OpenStreamForWriteAsync()) { await ResizeBitmapStream.AsStreamForRead().CopyToAsync(FileStream); } } } finally { LogoStream.Dispose(); } } else { Uri PageUri = AppThemeController.Current.Theme == ElementTheme.Dark ? new Uri("ms-appx:///Assets/Page_Solid_White.png") : new Uri("ms-appx:///Assets/Page_Solid_Black.png"); StorageFile PageFile = await StorageFile.GetFileFromApplicationUriAsync(PageUri); using (IRandomAccessStream PageStream = await PageFile.OpenAsync(FileAccessMode.Read)) { BitmapImage Image = new BitmapImage(); Icon.Source = Image; await Image.SetSourceAsync(PageStream); PageStream.Seek(0); using (Stream TransformStream = PageStream.AsStreamForRead()) using (Stream FileStream = await FileThumbnail.OpenStreamForWriteAsync()) { await TransformStream.CopyToAsync(FileStream); } } } ImageFile = FileThumbnail; } else { FormatErrorTip.IsOpen = true; } } } break; } case QuickStartType.WebSite: { try { if (Uri.TryCreate(Protocol.Text, UriKind.Absolute, out Uri Result)) { Uri ImageUri = new Uri($"{Result.Scheme}://{Result.Host}/favicon.ico"); HttpWebRequest Request = WebRequest.CreateHttp(ImageUri); using (WebResponse Response = await Request.GetResponseAsync()) using (Stream WebImageStream = Response.GetResponseStream()) using (MemoryStream TemplateStream = new MemoryStream()) { await WebImageStream.CopyToAsync(TemplateStream); TemplateStream.Seek(0, SeekOrigin.Begin); if (TemplateStream.Length > 0) { BitmapImage Bitmap = new BitmapImage(); Icon.Source = Bitmap; await Bitmap.SetSourceAsync(TemplateStream.AsRandomAccessStream()); TemplateStream.Seek(0, SeekOrigin.Begin); StorageFile DownloadImage = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("DownloadFile.ico", CreationCollisionOption.ReplaceExisting); using (Stream LocalFileStream = await DownloadImage.OpenStreamForWriteAsync()) { await TemplateStream.CopyToAsync(LocalFileStream); } ImageFile = DownloadImage; } else { FailureTips.IsOpen = true; } } } else { FailureTips.IsOpen = true; } } catch { try { Uri QueryUrl = Globalization.CurrentLanguage == LanguageEnum.Chinese_Simplified ? new Uri($"http://statics.dnspod.cn/proxy_favicon/_/favicon?domain={new Uri(Protocol.Text).Host}") : new Uri($"http://www.google.com/s2/favicons?domain={new Uri(Protocol.Text).Host}"); HttpWebRequest Request = WebRequest.CreateHttp(QueryUrl); using (WebResponse Response = await Request.GetResponseAsync()) using (Stream WebImageStream = Response.GetResponseStream()) using (MemoryStream TemplateStream = new MemoryStream()) { await WebImageStream.CopyToAsync(TemplateStream); TemplateStream.Seek(0, SeekOrigin.Begin); if (TemplateStream.Length > 0) { BitmapImage Bitmap = new BitmapImage(); Icon.Source = Bitmap; await Bitmap.SetSourceAsync(TemplateStream.AsRandomAccessStream()); TemplateStream.Seek(0, SeekOrigin.Begin); StorageFile DownloadImage = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("DownloadFile.ico", CreationCollisionOption.ReplaceExisting); using (Stream LocalFileStream = await DownloadImage.OpenStreamForWriteAsync()) { await TemplateStream.CopyToAsync(LocalFileStream); } ImageFile = DownloadImage; } else { FailureTips.IsOpen = true; } } } catch { FailureTips.IsOpen = true; } } break; } } }
private async void UWPPickerTip_ActionButtonClick(Microsoft.UI.Xaml.Controls.TeachingTip sender, object args) { try { if (PackageListView.SelectedItem is InstalledApplication Package) { sender.IsOpen = false; PickAppFlyout.Hide(); DisplayName.Text = Package.AppName; Protocol.Text = Package.AppFamilyName; Icon.Source = Package.Logo; StorageFile FileThumbnail = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("FileThumbnail.png", CreationCollisionOption.ReplaceExisting); if (Package.CreateStreamFromLogoData() is Stream LogoStream) { try { BitmapDecoder Decoder = await BitmapDecoder.CreateAsync(LogoStream.AsRandomAccessStream()); using (SoftwareBitmap SBitmap = await Decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied)) using (SoftwareBitmap ResizeBitmap = ComputerVisionProvider.ResizeToActual(SBitmap)) using (InMemoryRandomAccessStream ResizeBitmapStream = new InMemoryRandomAccessStream()) { BitmapEncoder Encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ResizeBitmapStream); Encoder.SetSoftwareBitmap(ResizeBitmap); await Encoder.FlushAsync(); BitmapImage Source = new BitmapImage(); Icon.Source = Source; await Source.SetSourceAsync(ResizeBitmapStream); ResizeBitmapStream.Seek(0); using (Stream FileStream = await FileThumbnail.OpenStreamForWriteAsync()) { await ResizeBitmapStream.AsStreamForRead().CopyToAsync(FileStream); } } } finally { LogoStream.Dispose(); } } else { Uri PageUri = AppThemeController.Current.Theme == ElementTheme.Dark ? new Uri("ms-appx:///Assets/Page_Solid_White.png") : new Uri("ms-appx:///Assets/Page_Solid_Black.png"); StorageFile PageFile = await StorageFile.GetFileFromApplicationUriAsync(PageUri); using (IRandomAccessStream PageStream = await PageFile.OpenAsync(FileAccessMode.Read)) { BitmapImage Image = new BitmapImage(); Icon.Source = Image; await Image.SetSourceAsync(PageStream); PageStream.Seek(0); using (Stream TransformStream = PageStream.AsStreamForRead()) using (Stream FileStream = await FileThumbnail.OpenStreamForWriteAsync()) { await TransformStream.CopyToAsync(FileStream); } } } ImageFile = FileThumbnail; } } catch (Exception ex) { LogTracer.Log(ex); FailureTips.IsOpen = true; } }
private static void EditPic(string path) { try { string nPath = Path.Combine(Path.GetDirectoryName(path), "Edit", Path.GetFileName(path)); if (File.Exists(nPath)) { return; } byte[] oPixelData, nPixelData; byte[,,] oPixelMatrix, nPixelMatrix; BitmapSource oBmp = new BitmapImage(new Uri(path)); WriteableBitmap nBmp = new WriteableBitmap(leftWidth + middleWidth + rightWidth, height, oBmp.DpiX, oBmp.DpiY, oBmp.Format, null); int bytePerPixel = oBmp.Format.BitsPerPixel / 8; int oStride = oBmp.PixelWidth * bytePerPixel, nStride = nBmp.PixelWidth * bytePerPixel; int gapWidth = (completeWidth - (leftWidth + middleWidth + rightWidth)) / 2; if (oBmp.PixelWidth < 4720 || oBmp.PixelHeight < 1080 || File.Exists(nPath)) { return; } oPixelData = new byte[oStride * height]; nPixelData = new byte[nStride * height]; oBmp.CopyPixels(oPixelData, oStride, 0); oPixelMatrix = GetAsPixelDataMatrix(oPixelData, bytePerPixel); nPixelMatrix = new byte[leftWidth + middleWidth + rightWidth, height, bytePerPixel]; SetPixel(ref nPixelMatrix, 0, middleWidth, oPixelMatrix, leftWidth + gapWidth); SetPixel(ref nPixelMatrix, middleWidth, rightWidth, oPixelMatrix, leftWidth + gapWidth + middleWidth + gapWidth); SetPixel(ref nPixelMatrix, middleWidth + leftWidth, rightWidth, oPixelMatrix, 0); nPixelData = GetAsArray(nPixelMatrix); nBmp.WritePixels(new Int32Rect(0, 0, leftWidth + middleWidth + rightWidth, height), nPixelData, nStride, 0); if (!Directory.Exists(Path.GetDirectoryName(nPath))) { Directory.CreateDirectory(Path.GetDirectoryName(nPath)); } BitmapEncoder encoder = GetBitmapEncoder(nPath); encoder.Frames.Add(BitmapFrame.Create(nBmp)); using (var stream = new FileStream(nPath, FileMode.Create)) { encoder.Save(stream); } return; } catch { Console.WriteLine(path); } }
private async void SaveImage(object sender, RoutedEventArgs e) { if (imageCaptured == false) { return; } // location: // C:\Users\{USER}\AppData\Local\Packages\7042ff83-dc0c-4816-a1a0-107ef134b815_zx9gxz867859y\LocalState StorageFolder assetsFolder = Windows.Storage.ApplicationData.Current.LocalFolder; StorageFile file = null; try { file = await assetsFolder.CreateFileAsync("captured-photo.png", Windows.Storage.CreationCollisionOption.ReplaceExisting); } catch (Exception ex) { Debug.WriteLine(ex.Message); } RenderTargetBitmap targetBitmap = new RenderTargetBitmap(); await targetBitmap.RenderAsync(this.renderTarget); await CleanUp(); foreach (UIElement child in this.renderTarget.Children) { if (child != this.camView) { this.renderTarget.Children.Remove(child); } } this.renderTarget.Children.Remove(currentFilter); currentFilter = null; this.renderedImage.Source = targetBitmap; Image newImage = new Image(); newImage.Source = targetBitmap; this.renderTarget.Children.Add(newImage); if (file != null) { using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); IBuffer targetBuffer = await targetBitmap.GetPixelsAsync(); SoftwareBitmap softwareBitmap = new SoftwareBitmap(BitmapPixelFormat.Bgra8, targetBitmap.PixelWidth, targetBitmap.PixelHeight); softwareBitmap.CopyFromBuffer(targetBuffer); encoder.SetSoftwareBitmap(softwareBitmap); try { await encoder.FlushAsync(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } } }
public async static void SaveAndPin(FrameworkElement tile, UIElement smallTile, String ID) { SecondaryTile pinTile = null; try { if (smallTile != null) { RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(smallTile); //var xaml = await FileIO.ReadTextAsync(mediumTileFile); //Border mediumTile = (Border)XamlReader.Load(xaml); //mediumTile.DataContext = tile.DataContext; //await renderTargetBitmap.RenderAsync(mediumTile); var pixelBuffer = await renderTargetBitmap.GetPixelsAsync(); StorageFolder storageFolder = ApplicationData.Current.LocalFolder; var tileFile = await storageFolder.CreateFileAsync(ID + "_medium.png", CreationCollisionOption.OpenIfExists); // Encode the image to the selected file on disk using (var fileStream = await tileFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); } //if (pinTile == null) //{ // var tile2 = new SecondaryTile(ID, "a", "b", new Uri("ms-appdata:///local/" + ID + "_medium.png"), TileSize.Default); // tile2.VisualElements.Square150x150Logo = new Uri("ms-appdata:///local/" + ID + "_medium.png"); // pinTile = tile2; //} } if (tile != null) { RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(tile); var pixelBuffer = await renderTargetBitmap.GetPixelsAsync(); StorageFolder storageFolder = ApplicationData.Current.LocalFolder; var tileFile = await storageFolder.CreateFileAsync(ID + "_wide.png", CreationCollisionOption.ReplaceExisting); // Encode the image to the selected file on disk using (var fileStream = await tileFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); } //var tile2 = new SecondaryTile(ID, "a", "b", new Uri("ms-appdata:///local/" + ID + "_wide.png"), TileSize.Wide310x150); //pinTile.VisualElements.Wide310x150Logo = new Uri("ms-appdata:///local/" + ID + "_wide.png"); } //if (await pinTile.UpdateAsync()) //{ // await pinTile.RequestCreateAsync(); // } /*XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150Image); * * * XmlNodeList tileImageAttributes = tileXml.GetElementsByTagName("image"); * ((XmlElement)tileImageAttributes[0]).SetAttribute("src", "ms-appdata:///local/" + ID + "_wide.png"); * ((XmlElement)tileImageAttributes[0]).SetAttribute("alt", "tile"); * * * * TileNotification tileNotification = new TileNotification(tileXml); * * TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification); * * * * XmlDocument tileXml2 = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150Image); * * * XmlNodeList tileImageAttributes2 = tileXml2.GetElementsByTagName("image"); * ((XmlElement)tileImageAttributes2[0]).SetAttribute("src", "ms-appdata:///local/" + ID + "_medium.png"); * ((XmlElement)tileImageAttributes2[0]).SetAttribute("alt", "tile"); * * * * TileNotification tileNotification2 = new TileNotification(tileXml2);*/ //TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification2); Uri wideLogo = new Uri("ms-appdata:///local/" + ID + "_medium.png"); SecondaryTile secondaryTile = new SecondaryTile(ID.Substring(0, 10), "a", ID.Substring(0, 10), wideLogo, TileSize.Default); secondaryTile.VisualElements.Wide310x150Logo = new Uri("ms-appdata:///local/" + ID + "_wide.png"); await secondaryTile.RequestCreateAsync(); } catch (Exception ex) { int y = 0; } }
public static async Task <StorageFile> CropAsync(StorageFile sourceFile, StorageFile file, Rect cropRectangle, int min = 1280, int max = 0, double quality = 0.77, BitmapRotation rotation = BitmapRotation.None, BitmapFlip flip = BitmapFlip.None) { if (file == null) { file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("crop.jpg", CreationCollisionOption.ReplaceExisting); } using (var fileStream = await OpenReadAsync(sourceFile)) using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite)) { var decoder = await BitmapDecoder.CreateAsync(fileStream); var cropWidth = (double)decoder.PixelWidth; var cropHeight = (double)decoder.PixelHeight; if (decoder.PixelWidth > 1280 || decoder.PixelHeight > 1280) { double ratioX = (double)1280 / cropWidth; double ratioY = (double)1280 / cropHeight; double ratio = Math.Min(ratioX, ratioY); cropWidth = cropWidth * ratio; cropHeight = cropHeight * ratio; } cropRectangle = new Rect( cropRectangle.X * decoder.PixelWidth, cropRectangle.Y * decoder.PixelHeight, cropRectangle.Width * decoder.PixelWidth, cropRectangle.Height * decoder.PixelHeight); var(scaledCrop, scaledSize) = Scale(cropRectangle, new Size(decoder.PixelWidth, decoder.PixelHeight), new Size(cropWidth, cropHeight), min, max); var bounds = new BitmapBounds(); bounds.X = (uint)scaledCrop.X; bounds.Y = (uint)scaledCrop.Y; bounds.Width = (uint)scaledCrop.Width; bounds.Height = (uint)scaledCrop.Height; var transform = new BitmapTransform(); transform.ScaledWidth = (uint)scaledSize.Width; transform.ScaledHeight = (uint)scaledSize.Height; transform.Bounds = bounds; transform.InterpolationMode = BitmapInterpolationMode.Linear; transform.Rotation = rotation; transform.Flip = flip; var pixelData = await decoder.GetSoftwareBitmapAsync(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage); var propertySet = new BitmapPropertySet(); var qualityValue = new BitmapTypedValue(quality, PropertyType.Single); propertySet.Add("ImageQuality", qualityValue); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, outputStream); encoder.SetSoftwareBitmap(pixelData); await encoder.FlushAsync(); } return(file); }
/// <summary> /// Saves an image loaded from clipboard to disk OR if base64 is checked /// creates the base64 content. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_SaveImage(object sender, RoutedEventArgs e) { string imagePath = null; var bitmapSource = ImagePreview.Source as BitmapSource; if (bitmapSource == null) { MessageBox.Show("Unable to convert bitmap source.", "Bitmap conversion error", MessageBoxButton.OK, MessageBoxImage.Warning); return; } using (var bitMap = WindowUtilities.BitmapSourceToBitmap(bitmapSource)) { imagePath = AddinManager.Current.RaiseOnSaveImage(bitMap); if (PasteAsBase64Content) { Base64EncodeImage(bitMap); IsMemoryImage = false; return; } if (!string.IsNullOrEmpty(imagePath)) { TextImage.Text = imagePath; IsMemoryImage = false; return; } string initialFolder = null; if (!string.IsNullOrEmpty(Document.Filename) && Document.Filename != "untitled") { initialFolder = Path.GetDirectoryName(Document.Filename); } var sd = new SaveFileDialog { Filter = "Image files (*.png;*.jpg;*.gif;)|*.png;*.jpg;*.jpeg;*.gif|All Files (*.*)|*.*", FilterIndex = 1, Title = "Save Image from Clipboard as", InitialDirectory = initialFolder, CheckFileExists = false, OverwritePrompt = true, CheckPathExists = true, RestoreDirectory = true }; var result = sd.ShowDialog(); if (result != null && result.Value) { imagePath = sd.FileName; try { var ext = Path.GetExtension(imagePath)?.ToLower(); if (ext == ".jpg" || ext == ".jpeg") { ImageUtils.SaveJpeg(bitMap, imagePath, mmApp.Configuration.JpegImageCompressionLevel); } else { using (var fileStream = new FileStream(imagePath, FileMode.Create)) { BitmapEncoder encoder = null; if (ext == ".png") { encoder = new PngBitmapEncoder(); } else if (ext == ".gif") { encoder = new GifBitmapEncoder(); } encoder.Frames.Add(BitmapFrame.Create(ImagePreview.Source as BitmapSource)); encoder.Save(fileStream); if (ext == ".png") { mmFileUtils.OptimizePngImage(sd.FileName, 5); // async } } } } catch (Exception ex) { MessageBox.Show("Couldn't save file: \r\n" + ex.Message, mmApp.ApplicationName); return; } string relPath = Path.GetDirectoryName(sd.FileName); if (initialFolder != null) { try { relPath = FileUtils.GetRelativePath(sd.FileName, initialFolder); } catch (Exception ex) { mmApp.Log($"Failed to get relative path.\r\nFile: {sd.FileName}, Path: {imagePath}", ex); } imagePath = relPath; } if (imagePath.Contains(":\\")) { imagePath = "file:///" + imagePath; } imagePath = imagePath.Replace("\\", "/"); Image = imagePath; IsMemoryImage = false; } } }
/// <summary> /// Add text comment to image file /// </summary> /// <param name="path">Image file path</param> /// <param name="desc">Text to add as comment</param> public static void AddImageDescription(string path, string desc) { string fileDirectory = Path.GetDirectoryName(path); string fileName = Path.GetFileNameWithoutExtension(path); string fileExt = Path.GetExtension(path); BitmapEncoder encoder = null; string tempLocation = fileDirectory + @"\" + "temp.jpg"; bool added = false; string filePath = path; if (string.IsNullOrEmpty(fileExt)) { filePath = FileHelper.FindFile(fileDirectory, fileName); } if (!string.IsNullOrEmpty(filePath)) { if (File.Exists(filePath)) { path = filePath; var imageFormat = GetImageFormat(Image.FromFile(path)); var mimeType = imageFormat.ToString(); while (!added) { try { BitmapDecoder decoder; FileInfo tempImage; using (Stream fileStream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { var originalImage = File.Exists(path) ? new FileInfo(path) : null; if (File.Exists(tempLocation)) { File.Delete(tempLocation); } originalImage.CopyTo(tempLocation, true); tempImage = new FileInfo(tempLocation); fileStream.Seek(0, SeekOrigin.Begin); switch (mimeType) //find mime type of image based on extension { case "Jpeg": try { decoder = new JpegBitmapDecoder(fileStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad); encoder = new JpegBitmapEncoder(); } catch { try { fileStream.Seek(0, SeekOrigin.Begin); decoder = new JpegBitmapDecoder(fileStream, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.OnLoad); encoder = new JpegBitmapEncoder(); } catch { try { fileStream.Seek(0, SeekOrigin.Begin); decoder = new PngBitmapDecoder(fileStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad); encoder = new PngBitmapEncoder(); } catch { try { fileStream.Seek(0, SeekOrigin.Begin); decoder = new PngBitmapDecoder(fileStream, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.OnLoad); encoder = new PngBitmapEncoder(); } catch { decoder = null; } } } } break; case "Png": try { decoder = new PngBitmapDecoder(fileStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad); encoder = new PngBitmapEncoder(); } catch { try { fileStream.Seek(0, SeekOrigin.Begin); decoder = new PngBitmapDecoder(fileStream, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.OnLoad); encoder = new PngBitmapEncoder(); } catch { try { fileStream.Seek(0, SeekOrigin.Begin); decoder = new JpegBitmapDecoder(fileStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad); encoder = new JpegBitmapEncoder(); } catch { try { fileStream.Seek(0, SeekOrigin.Begin); decoder = new JpegBitmapDecoder(fileStream, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.OnLoad); encoder = new JpegBitmapEncoder(); } catch { decoder = null; } } } } break; default: // Not jpeg or png file - dont add the comments decoder = null; break; } } if (decoder != null && desc != null) { var metadata = (BitmapMetadata)decoder.Frames[0].Metadata.Clone(); if (mimeType == "Jpeg") { metadata.Comment = desc; metadata.SetQuery("/xmp/dc:description", desc); } else if (mimeType == "Png") { metadata.SetQuery("/xmp/dc:description", desc); } var fileFrame = BitmapFrame.Create(decoder.Frames[0], decoder.Frames[0].Thumbnail, metadata, decoder.Frames[0].ColorContexts); encoder.Frames.Add(fileFrame); using (Stream fileStreamOut = new FileStream(path, FileMode.Create)) { try { encoder?.Save(fileStreamOut); } catch { try { //fileStreamOut.Close(); tempImage.CopyTo(path, true); } catch { // ignored } } } } added = true; File.Delete(tempLocation); } catch (NotSupportedException) { added = true; } catch (FileFormatException) { added = true; } catch (IOException) { added = false; } } } } }
internal static async Task LoadTileImageInternalAsync(string imagePath) { string tileName = "dreaming"; uint MaxImageWidth = 360; uint MaxImageHeight = 600; StorageFile origFile = await ApplicationData.Current.LocalFolder.GetFileAsync(imagePath); // open file for the new tile image file StorageFile tileFile = await Windows.Storage.KnownFolders.PicturesLibrary.CreateFileAsync(tileName, CreationCollisionOption.GenerateUniqueName); using (IRandomAccessStream tileStream = await tileFile.OpenAsync(FileAccessMode.ReadWrite)) { // get width and height from the original image IRandomAccessStreamWithContentType stream = await origFile.OpenReadAsync(); ImageProperties properties = await origFile.Properties.GetImagePropertiesAsync(); uint width = properties.Width; uint height = properties.Height; // get proper decoder for the input file - jpg/png/gif BitmapDecoder decoder = await GetProperDecoder(stream, origFile); if (decoder == null) { return; // should not happen } // get byte array of actual decoded image PixelDataProvider data = await decoder.GetPixelDataAsync(); byte[] bytes = data.DetachPixelData(); // create encoder for saving the tile image BitmapPropertySet propertySet = new BitmapPropertySet(); // create class representing target jpeg quality - a bit obscure, but it works BitmapTypedValue qualityValue = new BitmapTypedValue(0.5, PropertyType.Single); propertySet.Add("ImageQuality", qualityValue); // create the target jpeg decoder BitmapEncoder be = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, tileStream, propertySet); be.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, width, height, 96.0, 96.0, bytes); // crop the image, if it's too big if (width > MaxImageWidth || height > MaxImageHeight) { BitmapBounds bounds = new BitmapBounds(); if (width > MaxImageWidth) { bounds.Width = MaxImageWidth; bounds.X = (width - MaxImageWidth) / 2; } else { bounds.Width = width; } if (height > MaxImageHeight) { bounds.Height = MaxImageHeight; bounds.Y = (height - MaxImageHeight) / 2; } else { bounds.Height = height; } be.BitmapTransform.Bounds = bounds; } // save the target jpg to the file await be.FlushAsync(); } }
public static async Task <IRandomAccessStream> ResizeImage(this IRandomAccessStream imageStream, int width, int height, InterpolationMode interpolationMode, bool useDipUnits, bool allowUpscale, ImageInformation imageInformation = null) { if (useDipUnits) { width = width.DpToPixels(); height = height.DpToPixels(); } IRandomAccessStream resizedStream = imageStream; var decoder = await BitmapDecoder.CreateAsync(imageStream); if ((height > 0 && decoder.PixelHeight > height) || (width > 0 && decoder.PixelWidth > width) || allowUpscale) { using (imageStream) { resizedStream = new InMemoryRandomAccessStream(); BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder); double widthRatio = (double)width / decoder.PixelWidth; double heightRatio = (double)height / decoder.PixelHeight; double scaleRatio = Math.Min(widthRatio, heightRatio); if (width == 0) { scaleRatio = heightRatio; } if (height == 0) { scaleRatio = widthRatio; } uint aspectHeight = (uint)Math.Floor(decoder.PixelHeight * scaleRatio); uint aspectWidth = (uint)Math.Floor(decoder.PixelWidth * scaleRatio); if (interpolationMode == InterpolationMode.None) { encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Cubic; } else if (interpolationMode == InterpolationMode.Low) { encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Linear; } else if (interpolationMode == InterpolationMode.Medium) { encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Cubic; } else if (interpolationMode == InterpolationMode.High) { encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant; } else { encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Cubic; } encoder.BitmapTransform.ScaledHeight = aspectHeight; encoder.BitmapTransform.ScaledWidth = aspectWidth; if (imageInformation != null) { imageInformation.SetOriginalSize((int)decoder.PixelWidth, (int)decoder.PixelHeight); imageInformation.SetCurrentSize((int)aspectWidth, (int)aspectHeight); } await encoder.FlushAsync(); resizedStream.Seek(0); } } return(resizedStream); }
public ImageMediaTransformer(IEnumerable <Func <BitmapSource, BitmapSource> > bitmapTransformChain, BitmapEncoder encoder, IFormatInfo formatInfo) { _bitmapTransformChain = bitmapTransformChain; _encoder = encoder; OutputFormat = formatInfo; }
public static async Task CropandScaleAsync(StorageFile source, StorageFile dest, Point startPoint, Size size, double m_scaleFactor) { uint startPointX = (uint)Math.Floor(startPoint.X); uint startPointY = (uint)Math.Floor(startPoint.Y); uint height = (uint)Math.Floor(size.Height); uint width = (uint)Math.Floor(size.Width); using (IRandomAccessStream sourceStream = await source.OpenReadAsync(), destStream = await dest.OpenAsync(FileAccessMode.ReadWrite)) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream); var m_displayHeightNonScaled = decoder.OrientedPixelHeight; var m_displayWidthNonScaled = decoder.OrientedPixelWidth; // Use the native (no orientation applied) image dimensions because we want to handle // orientation ourselves. BitmapTransform transform = new BitmapTransform(); BitmapBounds bounds = new BitmapBounds() { X = (uint)(startPointX * m_scaleFactor), Y = (uint)(startPointY * m_scaleFactor), Height = (uint)(height * m_scaleFactor), Width = (uint)(width * m_scaleFactor) }; transform.Bounds = bounds; // Scaling occurs before flip/rotation, therefore use the original dimensions // (no orientation applied) as parameters for scaling. transform.ScaledHeight = (uint)(decoder.PixelHeight * m_scaleFactor); transform.ScaledWidth = (uint)(decoder.PixelWidth * m_scaleFactor); transform.Rotation = BitmapRotation.None; // Fant is a relatively high quality interpolation mode. transform.InterpolationMode = BitmapInterpolationMode.Fant; BitmapPixelFormat format = decoder.BitmapPixelFormat; BitmapAlphaMode alpha = decoder.BitmapAlphaMode; // Set the encoder's destination to the temporary, in-memory stream. PixelDataProvider pixelProvider = await decoder.GetPixelDataAsync( format, alpha, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.ColorManageToSRgb ); byte[] pixels = pixelProvider.DetachPixelData(); Guid encoderID = Guid.Empty; switch (dest.FileType.ToLower()) { case ".png": encoderID = BitmapEncoder.PngEncoderId; break; case ".bmp": encoderID = BitmapEncoder.BmpEncoderId; break; default: encoderID = BitmapEncoder.JpegEncoderId; break; } // Write the pixel data onto the encoder. Note that we can't simply use the // BitmapTransform.ScaledWidth and ScaledHeight members as the user may have // requested a rotation (which is applied after scaling). var encoder = await BitmapEncoder.CreateAsync(encoderID, destStream); encoder.SetPixelData( format, alpha, (bounds.Width), (bounds.Height), decoder.DpiX, decoder.DpiY, pixels ); await encoder.FlushAsync(); } }
void Save(string filename) { try { BitmapEncoder enc = null; string ext = System.IO.Path.GetExtension(filename); switch (ext.ToLower()) { case ".bmp": enc = new BmpBitmapEncoder(); break; case ".gif": enc = new GifBitmapEncoder(); break; case ".xaml": using (StreamWriter sw = new StreamWriter(filename, false, System.Text.Encoding.UTF8)) { XamlWriter.Save(diagram, sw); } break; case ".xps": SaveXps(filename); break; case ".png": enc = new PngBitmapEncoder(); break; case ".jpg": enc = new JpegBitmapEncoder(); break; case ".dot": break; } if (enc != null) { // reset VisualOffset to (0,0). Size s = this.diagram.RenderSize; diagram.Arrange(new Rect(0, 0, s.Width, s.Height)); Transform t = this.diagram.LayoutTransform; Point p = t.Transform(new Point(s.Width, s.Height)); RenderTargetBitmap rmi = new RenderTargetBitmap((int)p.X, (int)p.Y, 1 / 96, 1 / 96, PixelFormats.Pbgra32); rmi.Render(this.diagram); // fix the VisualOffset so diagram doesn't move inside scroller. this.graphScroller.Content = null; this.graphScroller.Content = diagram; using (FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write)) { enc.Frames.Add(BitmapFrame.Create(rmi)); enc.Save(fs); } } } catch (System.Exception e) { MessageBox.Show(e.ToString(), "Save Failed", MessageBoxButton.OK, MessageBoxImage.Error); } }
private void Resize(string sourcePath, BitmapEncoder overrideEncoder = null) { Contract.Requires(!String.IsNullOrWhiteSpace(sourcePath)); Contract.Ensures(!String.IsNullOrWhiteSpace(Contract.Result <string>())); //string extension = Path.GetExtension(sourcePath).ToUpperInvariant(); string destinationPath = sourcePath; switch (_processingCmd.ActionToPerform) { case ManipulateAction.CopyAsThumbnail: _processingCmd.CreateNewFile = true; _processingCmd.PostFixFile = "_thumb"; break; } if (_processingCmd.CreateNewFile) { destinationPath = FileUtil.GenerateNewFileName(sourcePath, _processingCmd.PostFixFile); } BitmapDecoder decoder; BitmapEncoder encoder; using (var sourceStream = File.OpenRead(sourcePath)) { // NOTE: Using BitmapCacheOption.OnLoad here will read the entire file into // memory which allows us to dispose of the file stream immediately decoder = BitmapDecoder.Create(sourceStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); } //See if a destination file type is specified if (overrideEncoder == null) { encoder = BitmapEncoder.Create(decoder.CodecInfo.ContainerFormat); try { // NOTE: This will throw if the codec dose not support encoding var _ = encoder.CodecInfo; } catch (NotSupportedException) { // Fallback to JPEG encoder encoder = CreateEncoder(DefaultJpegEncoderType); } } else { encoder = overrideEncoder; } // TODO: Copy container-level metadata if codec supports it SetEncoderSettings(encoder); // NOTE: Only TIFF and GIF images support multiple frames foreach (var sourceFrame in decoder.Frames) { // Apply the transform var transform = GetTransform(sourceFrame); var transformedBitmap = new TransformedBitmap(sourceFrame, transform); // TODO: Optionally copy metadata // Create the destination frame var thumbnail = sourceFrame.Thumbnail; var metadata = sourceFrame.Metadata as BitmapMetadata; var colorContexts = sourceFrame.ColorContexts; var destinationFrame = BitmapFrame.Create(transformedBitmap, thumbnail, metadata, colorContexts); encoder.Frames.Add(destinationFrame); } var fileExists = File.Exists(destinationPath); var finalPath = destinationPath; var result = new ResizeResult(finalPath, FileUtil.CreateActionMessage(finalPath, _processingCmd)); result.SourceFileName = sourcePath; result.SizeBefore = new FileInfo(sourcePath).Length; if (fileExists) { destinationPath = Path.GetTempFileName(); } using (var destinationStream = File.OpenWrite(destinationPath)) { // Save the final image encoder.Save(destinationStream); } // Move any existing file to the Recycle Bin if (fileExists) { OnBeforeWritingFile(result); // TODO: Is there a better way to do this without a reference to Microsoft.VisualBasic? //FileSystem.DeleteFile(finalPath, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin); File.Delete(finalPath); File.Move(destinationPath, finalPath); } result.SizeAfter = new FileInfo(finalPath).Length; result.PercentSaved = result.SizeBefore > 0 ? Math.Round((result.SizeBefore - result.SizeAfter) / result.SizeBefore * 100, 2) : 0; OnProgress(new ResizerEventArgs(result)); }
private async void ImageSaveButton_Click(object sender, RoutedEventArgs e) { var renderedImage = await _inkBitmapRenderer.RenderAsync( _imageInkPresenter.StrokeContainer.GetStrokes(), ImageInkCanvas.ActualWidth, ImageInkCanvas.ActualHeight); if (renderedImage != null) { // Convert to a format appropriate for SoftwareBitmapSource. var convertedImage = SoftwareBitmap.Convert( renderedImage, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied ); await InkImageSource.SetBitmapAsync(convertedImage); var renderTargetBitmap = new RenderTargetBitmap(); var currentDpi = DisplayInformation.GetForCurrentView().LogicalDpi; // Prepare for RenderTargetBitmap by hiding the InkCanvas and displaying the // rasterized strokes instead. ImageInkCanvas.Visibility = Visibility.Collapsed; InkImage.Visibility = Visibility.Visible; await renderTargetBitmap.RenderAsync(InkingRoot); var pixelData = await renderTargetBitmap.GetPixelsAsync(); // Restore the original layout now that we have created the RenderTargetBitmap image. ImageInkCanvas.Visibility = Visibility.Visible; InkImage.Visibility = Visibility.Collapsed; // Create destination file for the new image var destFolder = await ViewModel.GetStorageFolderForSightFile(ViewModel.SelectedSightFile.Id); var file = await destFolder.CreateFileAsync($"{Guid.NewGuid().ToString("D")}.png", CreationCollisionOption.GenerateUniqueName); using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, currentDpi, currentDpi, pixelData.ToArray() ); await encoder.FlushAsync(); } // Update the SightFile in the database await ViewModel.UpdateSightFileImageUriAsync(file.GetUri()); // Erase all strokes. ImageInkCanvas.InkPresenter.StrokeContainer.Clear(); } }
private bool SaveImageFile(string fileName, string imageFileName, ImageEncoderType encoderType) { if (_drawing == null) { throw new InvalidOperationException( "There is no converted drawing for the saving operation."); } string outputExt = GetImageFileExtention(encoderType); string outputFileName = null; if (String.IsNullOrEmpty(imageFileName)) { string fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName); string workingDir = Path.GetDirectoryName(fileName); outputFileName = Path.Combine(workingDir, fileNameWithoutExt + outputExt); } else { string fileExt = Path.GetExtension(imageFileName); if (String.IsNullOrEmpty(fileExt)) { outputFileName = imageFileName + outputExt; } else if (!String.Equals(fileExt, outputExt, StringComparison.OrdinalIgnoreCase)) { outputFileName = Path.ChangeExtension(imageFileName, outputExt); } else { outputFileName = imageFileName; } } string outputFileDir = Path.GetDirectoryName(outputFileName); if (!Directory.Exists(outputFileDir)) { Directory.CreateDirectory(outputFileDir); } BitmapEncoder bitampEncoder = GetBitmapEncoder(outputExt, encoderType); // The image parameters... Rect drawingBounds = _drawing.Bounds; int pixelWidth = (int)drawingBounds.Width; int pixelHeight = (int)drawingBounds.Height; double dpiX = 96; double dpiY = 96; // The Visual to use as the source of the RenderTargetBitmap. DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); if (this.Background != null) { drawingContext.DrawRectangle(this.Background, null, _drawing.Bounds); } drawingContext.DrawDrawing(_drawing); drawingContext.Close(); // The BitmapSource that is rendered with a Visual. RenderTargetBitmap targetBitmap = new RenderTargetBitmap( pixelWidth, pixelHeight, dpiX, dpiY, PixelFormats.Pbgra32); targetBitmap.Render(drawingVisual); // Encoding the RenderBitmapTarget as an image file. bitampEncoder.Frames.Add(BitmapFrame.Create(targetBitmap)); using (FileStream stream = File.Create(outputFileName)) { bitampEncoder.Save(stream); } _imageFile = outputFileName; return(true); }
public static async Task <StorageFile> TakeScreenshot() { StackPanel sp = new StackPanel() { Background = new SolidColorBrush(Windows.UI.Colors.Teal), Width = 200, Height = 600, Orientation = Orientation.Vertical }; TextBlock txtLine1 = new TextBlock() { Text = "Text Line 1", Foreground = new SolidColorBrush(Windows.UI.Colors.White), Width = 200, Height = 30, FontSize = 32, TextAlignment = TextAlignment.Left, Margin = new Thickness(9, 3, 0, 3) }; TextBlock txtLine2 = new TextBlock { Text = "Text Line 2", Foreground = new SolidColorBrush(Windows.UI.Colors.White), Width = 200, Height = 30, FontSize = 32, TextAlignment = TextAlignment.Left, Margin = new Thickness(9, 3, 0, 3) }; sp.Children.Add(txtLine1); sp.Children.Add(txtLine2); sp.UpdateLayout(); sp.Measure(new Size(200, 200)); sp.Arrange(new Rect(0, 0, 200, 200)); sp.UpdateLayout(); //now lets render this stackpanel on image try { RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(sp, 200, 200); var pixelBuffer = await renderTargetBitmap.GetPixelsAsync(); StorageFolder storageFolder = ApplicationData.Current.LocalFolder; var tileFile = await storageFolder.CreateFileAsync("image.png", CreationCollisionOption.ReplaceExisting); // Encode the image to the selected file on disk using (var fileStream = await tileFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); } return(tileFile); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); //new MessageDialog(ex.Message, "Error").ShowAsync(); return(null); } }
private Task <StorageFile> GenerateThumbnailImageAsync(StorageFile file, StorageFile outputFile, Action <BitmapDecoder, BitmapEncoder> setupEncoder) { return(Task.Run(async() => { try { using (var stream = new InMemoryRandomAccessStream()) { var result = await(file.FileType switch { SupportedFileTypesHelper.ZipFileType => ZipFileThumbnailImageWriteToStreamAsync(file, stream.AsStreamForWrite()), SupportedFileTypesHelper.RarFileType => RarFileThumbnailImageWriteToStreamAsync(file, stream.AsStreamForWrite()), SupportedFileTypesHelper.PdfFileType => PdfFileThumbnailImageWriteToStreamAsync(file, stream.AsStreamForWrite()), SupportedFileTypesHelper.CbzFileType => ZipFileThumbnailImageWriteToStreamAsync(file, stream.AsStreamForWrite()), SupportedFileTypesHelper.CbrFileType => RarFileThumbnailImageWriteToStreamAsync(file, stream.AsStreamForWrite()), SupportedFileTypesHelper.SevenZipFileType => SevenZipFileThumbnailImageWriteToStreamAsync(file, stream.AsStreamForWrite()), SupportedFileTypesHelper.Cb7FileType => SevenZipFileThumbnailImageWriteToStreamAsync(file, stream.AsStreamForWrite()), SupportedFileTypesHelper.TarFileType => TarFileThumbnailImageWriteToStreamAsync(file, stream.AsStreamForWrite()), SupportedFileTypesHelper.JpgFileType => ImageFileThumbnailImageWriteToStreamAsync(file, stream.AsStreamForWrite()), SupportedFileTypesHelper.JpegFileType => ImageFileThumbnailImageWriteToStreamAsync(file, stream.AsStreamForWrite()), SupportedFileTypesHelper.PngFileType => ImageFileThumbnailImageWriteToStreamAsync(file, stream.AsStreamForWrite()), SupportedFileTypesHelper.BmpFileType => ImageFileThumbnailImageWriteToStreamAsync(file, stream.AsStreamForWrite()), SupportedFileTypesHelper.GifFileType => ImageFileThumbnailImageWriteToStreamAsync(file, stream.AsStreamForWrite()), SupportedFileTypesHelper.TifFileType => ImageFileThumbnailImageWriteToStreamAsync(file, stream.AsStreamForWrite()), SupportedFileTypesHelper.TiffFileType => ImageFileThumbnailImageWriteToStreamAsync(file, stream.AsStreamForWrite()), SupportedFileTypesHelper.SvgFileType => ImageFileThumbnailImageWriteToStreamAsync(file, stream.AsStreamForWrite()), SupportedFileTypesHelper.EPubFileType => EPubFileThubnailImageWriteToStreamAsync(file, stream.AsStreamForWrite()), _ => throw new NotSupportedException(file.FileType) }); if (!result || stream.Size == 0) { return null; } var decoder = await BitmapDecoder.CreateAsync(stream); using (var memStream = new InMemoryRandomAccessStream()) { var encoder = await BitmapEncoder.CreateForTranscodingAsync(memStream, decoder); // サムネイルサイズ情報を記録 _thumbnailImageInfoRepository.UpdateItem(new ThumbnailImageInfo() { Path = file.Path, ImageWidth = decoder.PixelWidth, ImageHeight = decoder.PixelHeight }); setupEncoder(decoder, encoder); Debug.WriteLine($"thumb out <{file.Path}> size: w= {encoder.BitmapTransform.ScaledWidth} h= {encoder.BitmapTransform.ScaledHeight}"); await encoder.FlushAsync(); memStream.Seek(0); using (var fileStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite)) { await RandomAccessStream.CopyAsync(memStream, fileStream); } } } return outputFile; }
private async void NavigationCompleteB(Windows.UI.Xaml.Controls.WebView webView, WebViewNavigationCompletedEventArgs args) { webView.NavigationCompleted -= NavigationCompleteB; webView.NavigationCompleted += NavigationCompleteC; IsMainPageChild(webView); using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream()) { System.Diagnostics.Debug.WriteLine("B webView.Size=[" + webView.Width + "," + webView.Height + "] IsOnMainThread=[" + P42.Utils.Environment.IsOnMainThread + "]"); try { var width = (int)webView.GetValue(PngWidthProperty); System.Diagnostics.Debug.WriteLine("B width=[" + width + "]"); var contentSize = await webView.WebViewContentSizeAsync(); System.Diagnostics.Debug.WriteLine("B contentSize=[" + contentSize + "]"); System.Diagnostics.Debug.WriteLine("B webView.Size=[" + webView.Width + "," + webView.Height + "] IsOnMainThread=[" + P42.Utils.Environment.IsOnMainThread + "]"); if (contentSize.Height != webView.Height || width != webView.Width) { webView.Width = contentSize.Width; webView.Height = contentSize.Height; System.Diagnostics.Debug.WriteLine("B webView.Size=[" + webView.Width + "," + webView.Height + "] IsOnMainThread=[" + P42.Utils.Environment.IsOnMainThread + "]"); webView.InvalidateMeasure(); System.Diagnostics.Debug.WriteLine("B webView.Size=[" + webView.Width + "," + webView.Height + "] IsOnMainThread=[" + P42.Utils.Environment.IsOnMainThread + "]"); } //await Task.Delay(2000); await webView.CapturePreviewToStreamAsync(ms); var decoder = await BitmapDecoder.CreateAsync(ms); var transform = new BitmapTransform { //ScaledHeight = (uint)decoder.PixelHeight, //ScaledWidth = (uint)decoder.PixelWidth ScaledHeight = (uint)Math.Ceiling(webView.Height), ScaledWidth = (uint)Math.Ceiling(webView.Width) }; var pixelData = await decoder.GetPixelDataAsync( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage); var bytes = pixelData.DetachPixelData(); var piclib = Windows.Storage.ApplicationData.Current.TemporaryFolder; var fileName = (string)webView.GetValue(PngFileNameProperty) + ".png"; var file = await piclib.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.GenerateUniqueName); using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, //(uint)decoder.PixelWidth, (uint)decoder.PixelHeight, (uint)Math.Ceiling(webView.Width), (uint)Math.Ceiling(webView.Height), 0, 0, bytes); await encoder.FlushAsync(); } webView.Width = (int)webView.GetValue(BeforeWidthProperty); webView.Height = (int)webView.GetValue(BeforeHeightProperty); webView.Refresh(); var toFileResult = new ToFileResult(false, file.Path); webView.SetValue(ToFileResultProperty, toFileResult); } catch (Exception e) { webView.Width = (int)webView.GetValue(BeforeWidthProperty); webView.Height = (int)webView.GetValue(BeforeHeightProperty); webView.Refresh(); var toFileResult = new ToFileResult(true, e.InnerException?.Message ?? e.Message); webView.SetValue(ToFileResultProperty, toFileResult); } } webView.Refresh(); }
public async void TakeScreenshotWithDelay() { // 3 second countdown for (int i = 3; i > 0; i--) { ScreenshotStatusTextBlock.Text = i.ToString(); await Task.Delay(1000); } ScreenshotStatusTextBlock.Text = "Image captured"; // AppRecordingManager is desktop-only, and its use here is quite hacky, // but it is able to capture popups (though not theme shadows). bool isAppRecordingPresent = ApiInformation.IsTypePresent("Windows.Media.AppRecording.AppRecordingManager"); if (!isAppRecordingPresent) { // Better than doing nothing TakeScreenshot(); } else { var manager = AppRecordingManager.GetDefault(); if (manager.GetStatus().CanRecord) { var result = await manager.SaveScreenshotToFilesAsync( ApplicationData.Current.LocalFolder, "appScreenshot", AppRecordingSaveScreenshotOption.HdrContentVisible, manager.SupportedScreenshotMediaEncodingSubtypes); if (result.Succeeded) { // Open the screenshot back up var screenshotFile = await ApplicationData.Current.LocalFolder.GetFileAsync("appScreenshot.png"); using (var stream = await screenshotFile.OpenAsync(FileAccessMode.Read)) { var decoder = await BitmapDecoder.CreateAsync(stream); // Find the control in the picture GeneralTransform t = ControlPresenter.TransformToVisual(Window.Current.Content); Point pos = t.TransformPoint(new Point(0, 0)); ; if (!CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar) { // Add the height of the title bar, which I really wish was programmatically available anywhere. pos.Y += 32.0; } // Crop the screenshot to the control area var transform = new BitmapTransform() { Bounds = new BitmapBounds() { X = (uint)(Math.Ceiling(pos.X)) + 1, // Avoid the 1px window border Y = (uint)(Math.Ceiling(pos.Y)) + 1, Width = (uint)ControlPresenter.ActualWidth - 1, // Rounding issues -- this avoids capturing the control border Height = (uint)ControlPresenter.ActualHeight - 1 } }; var softwareBitmap = await decoder.GetSoftwareBitmapAsync( decoder.BitmapPixelFormat, BitmapAlphaMode.Ignore, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage); // Save the cropped picture var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(GetBestScreenshotName(), CreationCollisionOption.ReplaceExisting); using (var outStream = await file.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, outStream); encoder.SetSoftwareBitmap(softwareBitmap); await encoder.FlushAsync(); } } // Delete intermediate file await screenshotFile.DeleteAsync(); } } } await Task.Delay(1000); ScreenshotStatusTextBlock.Text = ""; }
public static async Task <WriteableBitmap> ResizeByDecoderAsync(WriteableBitmap sourceImage, int newWidth, int newHeight, bool IsProportion) { int lW = sourceImage.PixelWidth; int lH = sourceImage.PixelHeight; if (newWidth != 0 && newHeight != 0) { double nWidthFactor = (double)lW / (double)newWidth; double nHeightFactor = (double)lH / (double)newHeight; if (nWidthFactor != nHeightFactor && !IsProportion) { if (Math.Abs(nWidthFactor - 1.0f) > Math.Abs(nHeightFactor - 1.0f)) { newWidth = (int)((double)lW / nHeightFactor); nWidthFactor = nHeightFactor; } else { newHeight = (int)((double)lH / nWidthFactor); nHeightFactor = nWidthFactor; } } } // Get the pixel buffer of the writable bitmap in bytes Stream stream = sourceImage.PixelBuffer.AsStream(); byte[] pixels = new byte[(uint)stream.Length]; await stream.ReadAsync(pixels, 0, pixels.Length); //Encoding the data of the PixelBuffer we have from the writable bitmap var inMemoryRandomStream = new InMemoryRandomAccessStream(); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, inMemoryRandomStream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)sourceImage.PixelWidth, (uint)sourceImage.PixelHeight, 96, 96, pixels); await encoder.FlushAsync(); // At this point we have an encoded image in inMemoryRandomStream // We apply the transform and decode var transform = new BitmapTransform { ScaledWidth = (uint)newWidth, ScaledHeight = (uint)newHeight, InterpolationMode = BitmapInterpolationMode.Fant }; inMemoryRandomStream.Seek(0); var decoder = await BitmapDecoder.CreateAsync(inMemoryRandomStream); var pixelData = await decoder.GetPixelDataAsync( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage); // An array containing the decoded image data var sourceDecodedPixels = pixelData.DetachPixelData(); // Approach 1 : Encoding the image buffer again: // Encoding data var inMemoryRandomStream2 = new InMemoryRandomAccessStream(); var encoder2 = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, inMemoryRandomStream2); encoder2.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)newWidth, (uint)newHeight, 96, 96, sourceDecodedPixels); await encoder2.FlushAsync(); inMemoryRandomStream2.Seek(0); // finally the resized writablebitmap var bitmap = new WriteableBitmap((int)newWidth, (int)newHeight); await bitmap.SetSourceAsync(inMemoryRandomStream2); return(bitmap); }
public static void writeImage(String outputPath, BitmapSource image, Dictionary <String, Object> options = null, ImageMetadata metaData = null, CancellableOperationProgressBase progress = null) { int width = image.PixelWidth; int height = image.PixelHeight; float scale = ImageUtils.resizeRectangle(width, height, Constants.MAX_THUMBNAIL_WIDTH, Constants.MAX_THUMBNAIL_HEIGHT); TransformedBitmap thumbnail = new TransformedBitmap(image, new System.Windows.Media.ScaleTransform(scale, scale)); if (options != null) { if (options.ContainsKey("Width")) { width = (int)options["Width"]; if (!options.ContainsKey("Height")) { height = (int)(((float)width / image.PixelWidth) * image.PixelHeight); } } if (options.ContainsKey("Height")) { height = (int)options["Height"]; if (!options.ContainsKey("Width")) { width = (int)(((float)height / image.PixelHeight) * image.PixelWidth); } } } BitmapSource outImage = image; if (width != image.PixelWidth || height != image.PixelHeight) { outImage = new TransformedBitmap(image, new System.Windows.Media.ScaleTransform((double)width / image.PixelWidth, (double)height / image.PixelHeight)); } ImageFormat format = MediaFormatConvert.fileNameToImageFormat(outputPath); BitmapEncoder encoder = null; if (format == ImageFormat.Jpeg) { encoder = configureJpeg(options, ref thumbnail); } else if (format == ImageFormat.Png) { encoder = configurePng(options); } else if (format == ImageFormat.Gif) { encoder = new GifBitmapEncoder(); } else if (format == ImageFormat.Bmp) { encoder = new BmpBitmapEncoder(); } else if (format == ImageFormat.Tiff) { encoder = configureTiff(options); } encoder.Frames.Add(BitmapFrame.Create(outImage, thumbnail, null, null)); FileStream outputFile = new FileStream(outputPath, FileMode.Create); encoder.Save(outputFile); outputFile.Close(); if (metaData != null) { metaData.Location = outputPath; ImageFileMetadataWriter metadataWriter = new ImageFileMetadataWriter(); metadataWriter.writeMetadata(metaData, progress); } }
/// <summary> /// Extracts a frame from the camera stream and detects if any faces are found. Used as a precursor to making an expensive API /// call to get proper face details. /// </summary> /// <remarks> /// Keep in mind this method is called from a Timer and not synchronized with the camera stream. Also, the processing time of FaceTracker /// will vary depending on the size of each frame and the number of faces being tracked. That is, a large image with several tracked faces may /// take longer to process. /// </remarks> private async Task <ApiRequestParameters> ProcessCurrentVideoFrameAsync() { // If a lock is being held it means we're still waiting for processing work on the previous frame to complete. // In this situation, don't wait on the semaphore but exit immediately. if (!frameProcessingSemaphore.Wait(0)) { return(null); } try { // Create a VideoFrame object specifying the pixel format we want our capture image to be (NV12 bitmap in this case). // GetPreviewFrame will convert the native webcam frame into this format. const BitmapPixelFormat InputPixelFormat = BitmapPixelFormat.Nv12; using (var previewFrame = new VideoFrame(InputPixelFormat, (int)videoProperties.Width, (int)videoProperties.Height)) { await mediaCapture.GetPreviewFrameAsync(previewFrame); // The returned VideoFrame should be in the supported NV12 format but we need to verify this. if (!FaceDetector.IsBitmapPixelFormatSupported(previewFrame.SoftwareBitmap.BitmapPixelFormat)) { throw new NotSupportedException("PixelFormat '" + InputPixelFormat.ToString() + "' is not supported by FaceDetector"); } var faces = await faceTracker.ProcessNextFrameAsync(previewFrame); if (faces.Any()) { // Found faces so create a bounding rectangle and store the parameters to make the API call and process the response. using (var ms = new MemoryStream()) { // It'll be faster to send a smaller rectangle of the faces found instead of the whole image. This is what we do here. var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ms.AsRandomAccessStream()); // To use the encoder to resize we need to change the bitmap format. Might be a better way to do this, I can't see it. var converted = SoftwareBitmap.Convert(previewFrame.SoftwareBitmap, BitmapPixelFormat.Rgba16); encoder.SetSoftwareBitmap(converted); //var bounds = boundingBoxCreator.BoundingBoxForFaces(faces, converted.PixelWidth, converted.PixelHeight); //encoder.BitmapTransform.Bounds = bounds; await encoder.FlushAsync(); LogStatusMessage($"Found face(s) on camera: {faces.Count}", StatusSeverity.Info, false); return(new ApiRequestParameters { Image = ms.ToArray(), Faces = faces }); } } return(null); } } catch (Exception ex) { LogStatusMessage("Unable to process current frame: " + ex.ToString(), StatusSeverity.Error, false); return(null); } finally { frameProcessingSemaphore.Release(); } }
public bool GetThumbnail(Stream stream, int width, int height, bool cachedOnly, out byte[] imageData, out ImageType imageType) { imageData = null; imageType = ImageType.Unknown; // No support for cache if (cachedOnly) { return(false); } Bitmap cachedBitmap = null; // used only for rotation try { if (stream.CanSeek) { stream.Seek(0, SeekOrigin.Begin); } // open the image file for reading using (var factory = new ImagingFactory2()) using (var inputStream = new WICStream(factory, stream)) using (var decoder = new BitmapDecoder(factory, inputStream, DecodeOptions.CacheOnLoad)) using (var rotator = new BitmapFlipRotator(factory)) using (var scaler = new BitmapScaler(factory)) using (var output = new MemoryStream()) { // decode the loaded image to a format that can be consumed by D2D BitmapSource source = decoder.GetFrame(0); // Prefer PNG output for source PNG and for source formats with Alpha channel var usePngOutput = decoder.DecoderInfo.FriendlyName.StartsWith("PNG") || PixelFormat.GetBitsPerPixel(source.PixelFormat) == 32; BitmapTransformOptions bitmapTransformationOptions = BitmapTransformOptions.Rotate0; BitmapFrameDecode frame = source as BitmapFrameDecode; if (frame != null) { const string EXIF_ORIENTATION_TAG = "/app1/{ushort=0}/{ushort=274}"; ushort? orientation = null; try { // Not supported on all input types, i.e. BMP will fail here orientation = (ushort?)frame.MetadataQueryReader.TryGetMetadataByName(EXIF_ORIENTATION_TAG); //0x0112 } catch { } // If the EXIF orientation specifies that the image needs to be flipped or rotated before display, set that up to happen if (orientation.HasValue) { switch (orientation.Value) { case 1: break; // No rotation required. case 2: bitmapTransformationOptions = BitmapTransformOptions.Rotate0 | BitmapTransformOptions.FlipHorizontal; break; case 3: bitmapTransformationOptions = BitmapTransformOptions.Rotate180; break; case 4: bitmapTransformationOptions = BitmapTransformOptions.Rotate180 | BitmapTransformOptions.FlipHorizontal; break; case 5: bitmapTransformationOptions = BitmapTransformOptions.Rotate270 | BitmapTransformOptions.FlipHorizontal; break; case 6: bitmapTransformationOptions = BitmapTransformOptions.Rotate90; break; case 7: bitmapTransformationOptions = BitmapTransformOptions.Rotate90 | BitmapTransformOptions.FlipHorizontal; break; case 8: bitmapTransformationOptions = BitmapTransformOptions.Rotate270; break; } } } // Scale down larger images int sourceWidth = source.Size.Width; int sourceHeight = source.Size.Height; if (width > 0 && height > 0 && (sourceWidth > width || sourceHeight > height)) { if (sourceWidth <= height) { width = sourceWidth; } int newHeight = sourceHeight * height / sourceWidth; if (newHeight > height) { // Resize with height instead width = sourceWidth * height / sourceHeight; newHeight = height; } scaler.Initialize(source, width, newHeight, BitmapInterpolationMode.Fant); source = scaler; } // Rotate if (bitmapTransformationOptions != BitmapTransformOptions.Rotate0) { // For fast rotation a cached bitmap is needed, otherwise only per-pixel-decoding happens which makes the process extremly slow. // See https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/5ff2b52b-602f-4b22-9fb2-371539ff5ebb/hang-in-createbitmapfromwicbitmap-when-using-iwicbitmapfliprotator?forum=windowswic cachedBitmap = new Bitmap(factory, source, BitmapCreateCacheOption.CacheOnLoad); rotator.Initialize(cachedBitmap, bitmapTransformationOptions); source = rotator; } Guid formatGuid = ContainerFormatGuids.Jpeg; imageType = ImageType.Jpeg; if (usePngOutput) { formatGuid = ContainerFormatGuids.Png; imageType = ImageType.Png; } using (var encoder = new BitmapEncoder(factory, formatGuid)) { encoder.Initialize(output); using (var bitmapFrameEncode = new BitmapFrameEncode(encoder)) { // Create image encoder var wicPixelFormat = PixelFormat.FormatDontCare; bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(source.Size.Width, source.Size.Height); bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat); bitmapFrameEncode.WriteSource(source); bitmapFrameEncode.Commit(); encoder.Commit(); } } imageData = output.ToArray(); return(true); } } catch (Exception) { //ServiceRegistration.Get<ILogger>().Warn("WICThumbnailProvider: Error loading bitmapSource from file data stream", ex); return(false); } finally { cachedBitmap?.Dispose(); } }
private async void clipHeadOKButton_Click(object sender, RoutedEventArgs e) { upClipHeadProgressBar.Visibility = Visibility.Visible; try { //HttpClient _httpClient = new HttpClient(); //CancellationTokenSource _cts = new CancellationTokenSource(); RenderTargetBitmap mapBitmap = new RenderTargetBitmap(); await mapBitmap.RenderAsync(headScrollViewer); var pixelBuffer = await mapBitmap.GetPixelsAsync(); IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder; IStorageFile saveFile = await applicationFolder.CreateFileAsync("temphead.png", CreationCollisionOption.OpenIfExists); using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)mapBitmap.PixelWidth, (uint)mapBitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); } var vault = new Windows.Security.Credentials.PasswordVault(); var credentialList = vault.FindAllByResource(resourceName); credentialList[0].RetrievePassword(); //string uphead = await NetWork.headUpload(appSetting.Values["stuNum"].ToString(), "ms-appdata:///local/temphead.png"); string uphead = await NetWork.headUpload(credentialList[0].UserName, "ms-appdata:///local/temphead.png"); Debug.WriteLine(uphead); if (uphead != "") { JObject obj = JObject.Parse(uphead); if (Int32.Parse(obj["state"].ToString()) == 200) { ClipHeadGrid.Visibility = Visibility.Collapsed; BackOpacityGrid.Visibility = Visibility.Collapsed; initHeadImage(); } else { Utils.Toast("头像上传错误"); } } else { Utils.Toast("头像上传错误"); } upClipHeadProgressBar.Visibility = Visibility.Collapsed; } catch (Exception) { Debug.WriteLine("设置头像,保存新头像异常"); } }
private async void PickWin32_Click(object sender, RoutedEventArgs e) { try { FileOpenPicker Picker = new FileOpenPicker { SuggestedStartLocation = PickerLocationId.ComputerFolder, ViewMode = PickerViewMode.List }; Picker.FileTypeFilter.Add(".exe"); Picker.FileTypeFilter.Add(".lnk"); Picker.FileTypeFilter.Add(".msc"); if (await Picker.PickSingleFileAsync() is StorageFile ExecuteFile) { IDictionary <string, object> PropertiesDictionary = await ExecuteFile.Properties.RetrievePropertiesAsync(new string[] { "System.FileDescription" }); string ExtraAppName = string.Empty; if (PropertiesDictionary.TryGetValue("System.FileDescription", out object DescriptionRaw)) { ExtraAppName = Convert.ToString(DescriptionRaw); } DisplayName.Text = string.IsNullOrEmpty(ExtraAppName) ? ExecuteFile.DisplayName : ExtraAppName; Protocol.Text = ExecuteFile.Path; StorageFile FileThumbnail = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("FileThumbnail.png", CreationCollisionOption.ReplaceExisting); if (await ExecuteFile.GetThumbnailRawStreamAsync() is IRandomAccessStream ThumbnailStream) { try { BitmapDecoder Decoder = await BitmapDecoder.CreateAsync(ThumbnailStream); using (SoftwareBitmap SBitmap = await Decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied)) using (SoftwareBitmap ResizeBitmap = ComputerVisionProvider.ResizeToActual(SBitmap)) using (InMemoryRandomAccessStream ResizeBitmapStream = new InMemoryRandomAccessStream()) { BitmapEncoder Encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ResizeBitmapStream); Encoder.SetSoftwareBitmap(ResizeBitmap); await Encoder.FlushAsync(); BitmapImage Image = new BitmapImage(); Icon.Source = Image; await Image.SetSourceAsync(ResizeBitmapStream); ResizeBitmapStream.Seek(0); using (Stream TransformStream = ResizeBitmapStream.AsStreamForRead()) using (Stream FileStream = await FileThumbnail.OpenStreamForWriteAsync()) { await TransformStream.CopyToAsync(FileStream); } } } finally { ThumbnailStream.Dispose(); } } else { Uri PageUri = AppThemeController.Current.Theme == ElementTheme.Dark ? new Uri("ms-appx:///Assets/Page_Solid_White.png") : new Uri("ms-appx:///Assets/Page_Solid_Black.png"); StorageFile PageFile = await StorageFile.GetFileFromApplicationUriAsync(PageUri); using (IRandomAccessStream PageStream = await PageFile.OpenAsync(FileAccessMode.Read)) { BitmapImage Image = new BitmapImage(); Icon.Source = Image; await Image.SetSourceAsync(PageStream); PageStream.Seek(0); using (Stream TransformStream = PageStream.AsStreamForRead()) using (Stream FileStream = await FileThumbnail.OpenStreamForWriteAsync()) { await TransformStream.CopyToAsync(FileStream); } } } ImageFile = FileThumbnail; } } catch (Exception ex) { LogTracer.Log(ex); FailureTips.IsOpen = true; } }
public static async Task CropImageAsync(string sourceImageFile, string destinationImageFile, double scaleFactor, Rect clipRect, CropType cropType = CropType.UseScaleFactor) { byte[] sourcePixels; BitmapTransform transform; BitmapDecoder bmpDecoder; using (var srcStream = await(await StorageFile.GetFileFromPathAsync(sourceImageFile)).OpenAsync(FileAccessMode.Read)) { bmpDecoder = await BitmapDecoder.CreateAsync(srcStream); if (cropType == CropType.GetLargestRect) { // calculate scale factor to be minimal while still fitting the rect double sx, sy; sx = clipRect.Width / bmpDecoder.PixelWidth; sy = clipRect.Height / bmpDecoder.PixelHeight; scaleFactor = Math.Max(sx, sy); } transform = new BitmapTransform() // scale source bitmap to size of drawn image { ScaledHeight = (uint)(bmpDecoder.PixelHeight * scaleFactor), ScaledWidth = (uint)(bmpDecoder.PixelWidth * scaleFactor), InterpolationMode = BitmapInterpolationMode.Fant }; // decode data and get binary data var pixelData = await bmpDecoder.GetPixelDataAsync(BitmapPixelFormat.Rgba16, BitmapAlphaMode.Straight, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage); sourcePixels = pixelData.DetachPixelData(); } using (var dstStream = await(await CreateOrOpenFileAsync(destinationImageFile)).OpenAsync(FileAccessMode.ReadWrite)) { // create encoder to save data dstStream.Size = 0; var ext = destinationImageFile.Substring(destinationImageFile.LastIndexOf('.') + 1); Guid encId; switch (ext.ToLowerInvariant()) { case "jpg": case "jpeg": encId = BitmapEncoder.JpegEncoderId; break; case "gif": encId = BitmapEncoder.GifEncoderId; break; case "png": encId = BitmapEncoder.PngEncoderId; break; case "bmp": encId = BitmapEncoder.BmpEncoderId; break; case "tif": case "tiff": encId = BitmapEncoder.TiffEncoderId; break; } var bmpEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, dstStream); // set data bmpEncoder.SetPixelData(BitmapPixelFormat.Rgba16, BitmapAlphaMode.Straight, transform.ScaledWidth, transform.ScaledHeight, bmpDecoder.DpiX, bmpDecoder.DpiY, sourcePixels); // apply crop bmpEncoder.BitmapTransform.Bounds = new BitmapBounds() { X = (uint)clipRect.X, Y = (uint)clipRect.Y, Width = (uint)clipRect.Width, Height = (uint)clipRect.Height }; bmpEncoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant; // save await bmpEncoder.FlushAsync(); } }
private async Task ThumbnailTranscodeAsync(UpdateFileGenerationStart update, string[] args) { try { var conversion = JsonConvert.DeserializeObject <VideoConversion>(args[2]); //if (conversion.Transcode) { var file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(args[0]); var temp = await _protoService.GetFileAsync(update.DestinationPath); var props = await file.Properties.GetVideoPropertiesAsync(); double originalWidth = props.GetWidth(); double originalHeight = props.GetHeight(); //if (!conversion.CropRectangle.IsEmpty()) //{ // file = await ImageHelper.CropAsync(file, temp, conversion.CropRectangle); // originalWidth = conversion.CropRectangle.Width; // originalHeight = conversion.CropRectangle.Height; //} using (var fileStream = await ImageHelper.OpenReadAsync(file)) using (var outputStream = await temp.OpenAsync(FileAccessMode.ReadWrite)) { var decoder = await BitmapDecoder.CreateAsync(fileStream); double ratioX = 90d / originalWidth; double ratioY = 90d / originalHeight; double ratio = Math.Min(ratioX, ratioY); uint width = (uint)(originalWidth * ratio); uint height = (uint)(originalHeight * ratio); var transform = new BitmapTransform(); transform.ScaledWidth = width; transform.ScaledHeight = height; transform.InterpolationMode = BitmapInterpolationMode.Linear; transform.Flip = conversion.Mirror == MediaMirroringOptions.Horizontal ? BitmapFlip.Horizontal : BitmapFlip.None; var pixelData = await decoder.GetSoftwareBitmapAsync(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage); var propertySet = new BitmapPropertySet(); var qualityValue = new BitmapTypedValue(0.77, PropertyType.Single); propertySet.Add("ImageQuality", qualityValue); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, outputStream); encoder.SetSoftwareBitmap(pixelData); await encoder.FlushAsync(); _protoService.Send(new FinishFileGeneration(update.GenerationId, null)); } } } catch (Exception ex) { _protoService.Send(new FinishFileGeneration(update.GenerationId, new Error(500, "FILE_GENERATE_LOCATION_INVALID " + ex.ToString()))); } }
/// <summary> /// Encode bitmap(s) to a file /// </summary> /// <param name="encoder">Bitmap encoder</param> /// <param name="filename">Target filename</param> public static void Save(this BitmapEncoder encoder, string filename) { using (Stream stream = File.Create(filename)) { encoder.Save(stream); } }