private static D2DBitmap CreateBitmapFromDecoder(RenderTarget renderTarget, ImagingFactory wicFactory, BitmapDecoder decoder) { BitmapFrameDecode source; FormatConverter converter; // Create the initial frame. source = decoder.GetFrame(0); // Convert the image format to 32bppPBGRA -- which Direct2D expects. converter = wicFactory.CreateFormatConverter(); converter.Initialize( source.ToBitmapSource(), PixelFormats.Pbgra32Bpp, BitmapDitherType.None, BitmapPaletteType.MedianCut ); // Create a Direct2D bitmap from the WIC bitmap. return renderTarget.CreateBitmapFromWicBitmap( converter.ToBitmapSource()); }
/// <summary> /// Encodes the specified bitmap data and outputs it to the specified /// <c>BinaryWriter</c>. Bitmap data should be in BGRA format. /// For public use only. /// </summary> public async Task EncodeAsync(byte[] bytes, BinaryWriter writer) { if (this.Width == this.OutputWidth && this.Height == this.OutputHeight) { // Header writer.Write(this.Width); writer.Write(this.Height); writer.Write(bytes.Length); // Data writer.Write(bytes); } else { #if NETFX_CORE using (var bmpStream = new InMemoryRandomAccessStream()) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, bmpStream); encoder.BitmapTransform.ScaledWidth = (uint)this.OutputWidth; encoder.BitmapTransform.ScaledHeight = (uint)this.OutputHeight; encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)this.Width, (uint)this.Height, 96, 96, bytes); await encoder.FlushAsync(); bmpStream.Seek(0); var dec = await BitmapDecoder.CreateAsync(BitmapDecoder.BmpDecoderId, bmpStream); var pixelDataProvider = await dec.GetPixelDataAsync(); var pixelData = pixelDataProvider.DetachPixelData(); if (writer.BaseStream == null || writer.BaseStream.CanWrite == false) { return; } // Header writer.Write(this.OutputWidth); writer.Write(this.OutputHeight); writer.Write((int)pixelData.Length); // Data writer.Write(pixelData); } #else WriteableBitmap bmp = BitmapFactory.New(this.Width, this.Height); int stride = this.Width * 4; // 4 bytes per pixel in BGRA var dirtyRect = new Int32Rect(0, 0, this.Width, this.Height); bmp.WritePixels(dirtyRect, bytes, stride, 0); var newBytes = await Task.FromResult(bmp.Resize(this.OutputWidth, this.OutputHeight, WriteableBitmapExtensions.Interpolation.NearestNeighbor).ToByteArray()); // Header writer.Write(this.OutputWidth); writer.Write(this.OutputHeight); writer.Write(newBytes.Length); // Data writer.Write(newBytes); #endif } }
private async Task <byte[]> GetImageAsByteAsync(Guid format, int quality, int desiredWidth, int desiredHeight) { if (Control == null || Control.Source == null) { return(null); } var bitmap = Control.Source as WriteableBitmap; if (bitmap == null) { return(null); } byte[] pixels = null; uint pixelsWidth = (uint)bitmap.PixelWidth; uint pixelsHeight = (uint)bitmap.PixelHeight; if (desiredWidth != 0 || desiredHeight != 0) { double widthRatio = (double)desiredWidth / (double)bitmap.PixelWidth; double heightRatio = (double)desiredHeight / (double)bitmap.PixelHeight; double scaleRatio = Math.Min(widthRatio, heightRatio); if (desiredWidth == 0) { scaleRatio = heightRatio; } if (desiredHeight == 0) { scaleRatio = widthRatio; } uint aspectWidth = (uint)((double)bitmap.PixelWidth * scaleRatio); uint aspectHeight = (uint)((double)bitmap.PixelHeight * scaleRatio); using (var tempStream = new InMemoryRandomAccessStream()) { byte[] tempPixels = await GetBytesFromBitmapAsync(bitmap); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, tempStream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, pixelsWidth, pixelsHeight, 96, 96, tempPixels); await encoder.FlushAsync(); tempStream.Seek(0); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(tempStream); BitmapTransform transform = new BitmapTransform() { ScaledWidth = aspectWidth, ScaledHeight = aspectHeight, InterpolationMode = BitmapInterpolationMode.Linear }; PixelDataProvider pixelData = await decoder.GetPixelDataAsync( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage); pixels = pixelData.DetachPixelData(); pixelsWidth = aspectWidth; pixelsHeight = aspectHeight; } } else { pixels = await GetBytesFromBitmapAsync(bitmap); } using (var stream = new InMemoryRandomAccessStream()) { var encoder = await BitmapEncoder.CreateAsync(format, stream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, pixelsWidth, pixelsHeight, 96, 96, pixels); await encoder.FlushAsync(); stream.Seek(0); var bytes = new byte[stream.Size]; await stream.ReadAsync(bytes.AsBuffer(), (uint)stream.Size, InputStreamOptions.None); return(bytes); } }
private static BitmapFrame ReadBitmapFrame(Stream streamPhoto) { BitmapDecoder bdDecoder = BitmapDecoder.Create(streamPhoto, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); return(bdDecoder.Frames[0]); }
/// <summary> /// Método del boton subir imagen para el perfil de usuario que abre el explorador de archivos para obtener una imagen jpg o png. /// Si la imagen ocupa menos de 1 MB transforma la imagen del tipo System.Drawing a byte[] (soportado en WPF) y asigna la imagen /// al usuario mostrandola en la interfaz; si la imagen es mayor de 1MB muestra un mensaje indicandolo. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SubirImagen(object sender, RoutedEventArgs e) { System.Drawing.Image image = null; // Abrir explorador de archivos System.Windows.Forms.OpenFileDialog dialogoBuscarArchivo = new System.Windows.Forms.OpenFileDialog(); BitmapDecoder bitdecoder; // Filtar imagen por jpg o png dialogoBuscarArchivo.Filter = "Image files (*.jpg, *.png) | *.jpg; *.png"; dialogoBuscarArchivo.FilterIndex = 1; dialogoBuscarArchivo.Title = (string)Application.Current.FindResource("SubirImagen"); dialogoBuscarArchivo.Multiselect = false; if (dialogoBuscarArchivo.ShowDialog() == System.Windows.Forms.DialogResult.OK) { //Tamaño de la imagen no puede ser mayor de 1MB var size = new FileInfo(dialogoBuscarArchivo.FileName).Length; if (size < 1023000) { // Transformar la imagen a System.Drawing using (Stream stream = dialogoBuscarArchivo.OpenFile()) { string ruta = dialogoBuscarArchivo.FileName; image = System.Drawing.Image.FromFile(ruta); bitdecoder = BitmapDecoder.Create(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad); } } else // imagen mayor a 1MB { string mensaje = (string)Application.Current.FindResource("imagenMax"); string cabecera = (string)Application.Current.FindResource("informacion"); MessageBox.Show(mensaje, cabecera, MessageBoxButton.OK, MessageBoxImage.Information); } } // Si se elige imagen if (image != null) { // Transformar la imagen a byte[] y asignarla al usuario using (var ms = new MemoryStream()) { image.Save(ms, image.RawFormat); usuario.Imagen = ms.ToArray(); } // Trnasformar la imagen para mostrarla en la interfaz byte[] img = usuario.Imagen; var imagen = new BitmapImage(); using (var mem = new MemoryStream(img)) { mem.Position = 0; imagen.BeginInit(); imagen.CreateOptions = BitmapCreateOptions.PreservePixelFormat; imagen.CacheOption = BitmapCacheOption.OnLoad; imagen.UriSource = null; imagen.StreamSource = mem; imagen.EndInit(); } usuarioImagen.Source = imagen; } }
private async Task <AppData> LoadModernAndLegacyAppData(Windows.ApplicationModel.Package item, StorageFolder saveLogoLocation) { AppData data = new AppData(); try { data.FamilyName = item.Id.FamilyName; if (familyNameAppData.ContainsKey(data.FamilyName)) { familyNameAppData[data.FamilyName].PackageId = item.Id.FullName; //Refresh package id. data.PackageId = ""; return(data); } // // Сводка: // Перечисляет упакованные приложения на устройстве. Возвращаются только упакованные // приложения, зарегистрированные для текущего пользователя. // // Возврат: // Список упакованных приложений вместе с их отображаемым именем, описанием и логотипом. IReadOnlyList <Windows.ApplicationModel.Core.AppListEntry> x = await item.GetAppListEntriesAsync(); if ((x == null) || (x.Count == 0)) { return(null); } data.DisplayName = (x.First().DisplayInfo.DisplayName); data.PackageId = item.Id.FullName; data.PackageRootFolder = item.InstalledLocation.Path; data.IsLegacyApp = data.PackageRootFolder[data.PackageRootFolder.Length - 1] == '}'; data.PackageDataFolder = await GetDataFolder(data); if ((await saveLogoLocation.TryGetItemAsync(data.FamilyName + ".png")) == null) { WriteableBitmap bmp = null; try { var stream = await x.First().DisplayInfo.GetLogo(new Size(50, 50)).OpenReadAsync(); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); bmp = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight); bmp.SetSource(stream); //await bmp.SaveAsync(saveLogoLocation, data.FamilyName + ".png"); } catch { } } data.LogoPath = System.IO.Path.Combine(saveLogoLocation.Path, data.FamilyName + ".png"); try { if (data.IsLegacyApp) { data.Publisher = await TryGetPublisherName_Legacy(item); } else { data.Publisher = await TryGetPublisherName_Modern(item); } } catch { } return(data); } catch { } return(null); }
//------------------------------------------------------------------------------------- // Load a WIC-supported file in memory //------------------------------------------------------------------------------------- internal static Image LoadFromWICMemory(IntPtr pSource, int size, bool makeACopy, GCHandle?handle) { var flags = WICFlags.AllFrames; Image image = null; // Create input stream for memory using (var stream = new WICStream(Factory, new DataPointer(pSource, size))) { // If the decoder is unable to decode the image, than return null BitmapDecoder decoder = null; try { decoder = new BitmapDecoder(Factory, stream, DecodeOptions.CacheOnDemand); using (var frame = decoder.GetFrame(0)) { // Get metadata Guid convertGuid; var tempDesc = DecodeMetadata(flags, decoder, frame, out convertGuid); // If not supported. if (!tempDesc.HasValue) { return(null); } var mdata = tempDesc.Value; if ((mdata.ArraySize > 1) && (flags & WICFlags.AllFrames) != 0) { return(DecodeMultiframe(flags, mdata, decoder)); } image = DecodeSingleFrame(flags, mdata, convertGuid, frame); } } catch { image = null; } finally { if (decoder != null) { decoder.Dispose(); } } } // For WIC, we are not keeping the original buffer. if (image != null && !makeACopy) { if (handle.HasValue) { handle.Value.Free(); } else { SharpDX.Utilities.FreeMemory(pSource); } } return(image); }
private async void ProgramPickerDialog_Loading(FrameworkElement sender, object args) { LoadingText.Visibility = Visibility.Visible; WholeArea.Visibility = Visibility.Collapsed; List <ProgramPickerItem> RecommandList = new List <ProgramPickerItem>(); try { using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController()) { List <AssociationPackage> AssocList = await Exclusive.Controller.GetAssociateFromPathAsync(OpenFile.Path).ConfigureAwait(true); List <AppInfo> AppInfoList = (await Launcher.FindFileHandlersAsync(OpenFile.Type)).ToList(); await SQLite.Current.UpdateProgramPickerRecordAsync(OpenFile.Type, AssocList.Concat(AppInfoList.Select((Info) => new AssociationPackage(OpenFile.Type, Info.PackageFamilyName, true)))).ConfigureAwait(true); foreach (AppInfo Info in AppInfoList) { try { using (IRandomAccessStreamWithContentType LogoStream = await Info.DisplayInfo.GetLogo(new Windows.Foundation.Size(128, 128)).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 Stream = new InMemoryRandomAccessStream()) { BitmapEncoder Encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, Stream); Encoder.SetSoftwareBitmap(ResizeBitmap); await Encoder.FlushAsync(); BitmapImage Image = new BitmapImage(); await Image.SetSourceAsync(Stream); RecommandList.Add(new ProgramPickerItem(Image, Info.DisplayInfo.DisplayName, Info.DisplayInfo.Description, Info.PackageFamilyName)); } } } catch (Exception ex) { LogTracer.Log(ex, "An exception was threw when getting or processing App Logo"); } } } } catch (Exception ex) { LogTracer.Log(ex, "An exception was threw when fetching association data"); } foreach (AssociationPackage Package in await SQLite.Current.GetProgramPickerRecordAsync(OpenFile.Type, false).ConfigureAwait(true)) { try { if (await FileSystemStorageItemBase.CheckExistAsync(Package.ExecutablePath).ConfigureAwait(true)) { StorageFile ExecuteFile = await StorageFile.GetFileFromPathAsync(Package.ExecutablePath); 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); } if (await ExecuteFile.GetThumbnailRawStreamAsync().ConfigureAwait(true) is IRandomAccessStream ThumbnailStream) { using (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 ThumbnailBitmap = new BitmapImage(); await ThumbnailBitmap.SetSourceAsync(ResizeBitmapStream); if (Package.IsRecommanded) { RecommandList.Add(new ProgramPickerItem(ThumbnailBitmap, string.IsNullOrEmpty(ExtraAppName) ? ExecuteFile.DisplayName : ExtraAppName, Globalization.GetString("Application_Admin_Name"), ExecuteFile.Path)); } else { NotRecommandList.Add(new ProgramPickerItem(ThumbnailBitmap, string.IsNullOrEmpty(ExtraAppName) ? ExecuteFile.DisplayName : ExtraAppName, Globalization.GetString("Application_Admin_Name"), ExecuteFile.Path)); } } } } else { if (Package.IsRecommanded) { RecommandList.Add(new ProgramPickerItem(new BitmapImage(AppThemeController.Current.Theme == ElementTheme.Dark ? new Uri("ms-appx:///Assets/Page_Solid_White.png") : new Uri("ms-appx:///Assets/Page_Solid_Black.png")), string.IsNullOrEmpty(ExtraAppName) ? ExecuteFile.DisplayName : ExtraAppName, Globalization.GetString("Application_Admin_Name"), ExecuteFile.Path)); } else { NotRecommandList.Add(new ProgramPickerItem(new BitmapImage(AppThemeController.Current.Theme == ElementTheme.Dark ? new Uri("ms-appx:///Assets/Page_Solid_White.png") : new Uri("ms-appx:///Assets/Page_Solid_Black.png")), string.IsNullOrEmpty(ExtraAppName) ? ExecuteFile.DisplayName : ExtraAppName, Globalization.GetString("Application_Admin_Name"), ExecuteFile.Path)); } } } else { await SQLite.Current.DeleteProgramPickerRecordAsync(Package).ConfigureAwait(true); } } catch (Exception ex) { LogTracer.Log(ex, "An exception was threw trying add to ApplicationList"); } } string AdminExecutablePath = await SQLite.Current.GetDefaultProgramPickerRecordAsync(OpenFile.Type).ConfigureAwait(true); if (!string.IsNullOrEmpty(AdminExecutablePath)) { if (RecommandList.FirstOrDefault((Item) => Item.Path.Equals(AdminExecutablePath, StringComparison.OrdinalIgnoreCase)) is ProgramPickerItem RecommandItem) { CurrentUseProgramList.Items.Add(RecommandItem); CurrentUseProgramList.SelectedIndex = 0; RecommandList.Remove(RecommandItem); } else if (NotRecommandList.FirstOrDefault((Item) => Item.Path.Equals(AdminExecutablePath, StringComparison.OrdinalIgnoreCase)) is ProgramPickerItem NotRecommandItem) { CurrentUseProgramList.Items.Add(NotRecommandItem); CurrentUseProgramList.SelectedIndex = 0; NotRecommandList.Remove(NotRecommandItem); } } if (CurrentUseProgramList.Items.Count == 0) { switch (OpenFile.Type.ToLower()) { case ".jpg": case ".png": case ".bmp": case ".heic": case ".gif": case ".tiff": case ".mkv": case ".mp4": case ".mp3": case ".flac": case ".wma": case ".wmv": case ".m4a": case ".mov": case ".alac": case ".txt": case ".pdf": case ".exe": { Area1.Visibility = Visibility.Visible; CurrentUseProgramList.Visibility = Visibility.Visible; Title1.Text = Globalization.GetString("ProgramPicker_Dialog_Title_1"); Title2.Text = Globalization.GetString("ProgramPicker_Dialog_Title_2"); CurrentUseProgramList.Items.Add(new ProgramPickerItem(new BitmapImage(new Uri("ms-appx:///Assets/RX-icon.png")), Globalization.GetString("ProgramPicker_Dialog_BuiltInViewer"), Globalization.GetString("ProgramPicker_Dialog_BuiltInViewer_Description"), Package.Current.Id.FamilyName)); CurrentUseProgramList.SelectedIndex = 0; break; } default: { Area1.Visibility = Visibility.Collapsed; CurrentUseProgramList.Visibility = Visibility.Collapsed; Title2.Text = Globalization.GetString("ProgramPicker_Dialog_Title_2"); break; } } } else { Area1.Visibility = Visibility.Visible; CurrentUseProgramList.Visibility = Visibility.Visible; Title1.Text = Globalization.GetString("ProgramPicker_Dialog_Title_1"); Title2.Text = Globalization.GetString("ProgramPicker_Dialog_Title_2"); switch (OpenFile.Type.ToLower()) { case ".jpg": case ".png": case ".bmp": case ".heic": case ".gif": case ".tiff": case ".mkv": case ".mp4": case ".mp3": case ".flac": case ".wma": case ".wmv": case ".m4a": case ".mov": case ".alac": case ".txt": case ".pdf": case ".exe": { ProgramCollection.Add(new ProgramPickerItem(new BitmapImage(new Uri("ms-appx:///Assets/RX-icon.png")), Globalization.GetString("ProgramPicker_Dialog_BuiltInViewer"), Globalization.GetString("ProgramPicker_Dialog_BuiltInViewer_Description"), Package.Current.Id.FamilyName)); break; } } } if (RecommandList.Count == 0) { ShowMore.Visibility = Visibility.Collapsed; foreach (ProgramPickerItem Item in NotRecommandList) { ProgramCollection.Add(Item); } OtherProgramList.MaxHeight = 300; } else { foreach (ProgramPickerItem Item in RecommandList) { ProgramCollection.Add(Item); } } if (CurrentUseProgramList.SelectedIndex == -1) { OtherProgramList.SelectedIndex = 0; } LoadingText.Visibility = Visibility.Collapsed; WholeArea.Visibility = Visibility.Visible; }
private BitmapDecoder GetDecoder(IRandomAccessStream ras) { return(Task.Run(async() => { return await BitmapDecoder.CreateAsync(ras); }).Result); }
private async void Options_changed(object sender, SelectionChangedEventArgs e) { if (Cut.IsSelected) { string desiredName = DateTime.Now.Ticks + ".jpg"; StorageFolder applicationFolder = ApplicationData.Current.LocalFolder; StorageFolder folder = await applicationFolder.CreateFolderAsync("Pic", CreationCollisionOption.OpenIfExists); StorageFile saveFile = await folder.CreateFileAsync(desiredName, CreationCollisionOption.OpenIfExists); RenderTargetBitmap bitmap = new RenderTargetBitmap(); await bitmap.RenderAsync(Img); var pixelBuffer = await bitmap.GetPixelsAsync(); using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); } if (saveFile != null) { CutPicture(saveFile); } } else { if (addfilter.IsSelected) { string desiredName = DateTime.Now.Ticks + ".jpg"; StorageFolder applicationFolder = ApplicationData.Current.LocalFolder; StorageFolder folder = await applicationFolder.CreateFolderAsync("Pic", CreationCollisionOption.OpenIfExists); StorageFile saveFile = await folder.CreateFileAsync(desiredName, CreationCollisionOption.OpenIfExists); RenderTargetBitmap bitmap = new RenderTargetBitmap(); await bitmap.RenderAsync(Img); var pixelBuffer = await bitmap.GetPixelsAsync(); using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); } if (saveFile != null) { BlankPage2 editor = new BlankPage2(); editor.Show(saveFile); editor.ImageEditedCompleted += (image_edited) => { Img.Source = image_edited; }; } } else { if (blur.IsSelected) { string desiredName = DateTime.Now.Ticks + ".jpg"; StorageFolder applicationFolder = ApplicationData.Current.LocalFolder; StorageFolder folder = await applicationFolder.CreateFolderAsync("Pic", CreationCollisionOption.OpenIfExists); StorageFile saveFile = await folder.CreateFileAsync(desiredName, CreationCollisionOption.OpenIfExists); RenderTargetBitmap bitmap = new RenderTargetBitmap(); await bitmap.RenderAsync(Img); var pixelBuffer = await bitmap.GetPixelsAsync(); using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); } if (saveFile == null) { // The user cancelled the picking operation return; } SoftwareBitmap inputBitmap; using (IRandomAccessStream stream = await saveFile.OpenAsync(FileAccessMode.Read)) { // Create the decoder from the stream BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); // Get the SoftwareBitmap representation of the file inputBitmap = await decoder.GetSoftwareBitmapAsync(); } if (inputBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 || inputBitmap.BitmapAlphaMode != BitmapAlphaMode.Premultiplied) { inputBitmap = SoftwareBitmap.Convert(inputBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); } SoftwareBitmap outputBitmap = new SoftwareBitmap(inputBitmap.BitmapPixelFormat, inputBitmap.PixelWidth, inputBitmap.PixelHeight, BitmapAlphaMode.Premultiplied); var helper = new OpenCVBridge.OpenCVHelper(); helper.Blur(inputBitmap, outputBitmap); var bitmapSource = new SoftwareBitmapSource(); await bitmapSource.SetBitmapAsync(outputBitmap); Img.Source = bitmapSource; } else { if (scrawl.IsSelected) { string desiredName = DateTime.Now.Ticks + ".jpg"; StorageFolder applicationFolder = ApplicationData.Current.LocalFolder; StorageFolder folder = await applicationFolder.CreateFolderAsync("Pic", CreationCollisionOption.OpenIfExists); StorageFile saveFile = await folder.CreateFileAsync(desiredName, CreationCollisionOption.OpenIfExists); RenderTargetBitmap bitmap = new RenderTargetBitmap(); await bitmap.RenderAsync(Img); var pixelBuffer = await bitmap.GetPixelsAsync(); using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); } if (saveFile != null) { scrawl editor = new scrawl(); editor.Show(saveFile); editor.ImageEditedCompleted += (image_edited) => { Img.Source = image_edited; }; } } else { if (open.IsSelected) { //文件选择器 FileOpenPicker openPicker = new FileOpenPicker(); //初始位置 openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; //添加文件类型 openPicker.FileTypeFilter.Add(".jpg"); openPicker.FileTypeFilter.Add(".jpeg"); openPicker.FileTypeFilter.Add(".png"); openPicker.FileTypeFilter.Add(".gif"); //选取单个文件 Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync(); if (file != null) { using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read)) { var srcImage = new BitmapImage(); await srcImage.SetSourceAsync(stream); Img.Source = srcImage; } } } else { if (regenerate.IsSelected) { MyFrame.Navigate(typeof(Page1)); } else { if (Camera.IsSelected) { CameraCaptureUI captureUI = new CameraCaptureUI(); captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg; captureUI.PhotoSettings.CroppedSizeInPixels = new Size(200, 200); StorageFile photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo); if (photo == null) { // User cancelled photo capture return; } IRandomAccessStream stream = await photo.OpenAsync(FileAccessMode.Read); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync(); SoftwareBitmap softwareBitmapBGR8 = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); SoftwareBitmapSource bitmapSource = new SoftwareBitmapSource(); await bitmapSource.SetBitmapAsync(softwareBitmapBGR8); Img.Source = bitmapSource; } else { if (save.IsSelected) { FileSavePicker savefile = new FileSavePicker(); //初始位置 savefile.SuggestedStartLocation = PickerLocationId.PicturesLibrary; // 显示在下拉列表的文件类型 savefile.FileTypeChoices.Add("图片", new List <string>() { ".png", ".jpg", ".jpeg", ".bmp" }); // 默认的文件名 savefile.SuggestedFileName = "SaveFile"; StorageFile sFile = await savefile.PickSaveFileAsync(); if (sFile != null) { // 在用户完成更改并调用CompleteUpdatesAsync之前,阻止对文件的更新 CachedFileManager.DeferUpdates(sFile); //把控件变成图像 RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(); //传入参数Image控件 await renderTargetBitmap.RenderAsync(Img); IBuffer pixelbuffer = await renderTargetBitmap.GetPixelsAsync(); using (var fileStream = await sFile.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(); } } } else { if (Sharpen.IsSelected) { string desiredName = DateTime.Now.Ticks + ".jpg"; StorageFolder applicationFolder = ApplicationData.Current.LocalFolder; StorageFolder folder = await applicationFolder.CreateFolderAsync("Pic", CreationCollisionOption.OpenIfExists); StorageFile saveFile = await folder.CreateFileAsync(desiredName, CreationCollisionOption.OpenIfExists); RenderTargetBitmap bitmap = new RenderTargetBitmap(); await bitmap.RenderAsync(Img); var pixelBuffer = await bitmap.GetPixelsAsync(); using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); } if (saveFile != null) { BlankPage1 editor = new BlankPage1(); editor.Show(saveFile); editor.ImageEditedCompleted += (image_edited) => { Img.Source = image_edited; }; } } else { string desiredName = DateTime.Now.Ticks + ".jpg"; StorageFolder applicationFolder = ApplicationData.Current.LocalFolder; StorageFolder folder = await applicationFolder.CreateFolderAsync("Pic", CreationCollisionOption.OpenIfExists); StorageFile saveFile = await folder.CreateFileAsync(desiredName, CreationCollisionOption.OpenIfExists); RenderTargetBitmap bitmap = new RenderTargetBitmap(); await bitmap.RenderAsync(Img); var pixelBuffer = await bitmap.GetPixelsAsync(); using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); } if (saveFile != null) { paster editor = new paster(); editor.Show(saveFile); editor.ImageEditedCompleted += (image_edited) => { Img.Source = image_edited; }; } } } } } } } } } } }
private async void OpenExecute() { var picker = new FileOpenPicker(); picker.ViewMode = PickerViewMode.Thumbnail; picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; picker.FileTypeFilter.AddRange(Constants.PhotoTypes); var file = await picker.PickSingleFileAsync(); if (file == null) { return; } var stream = await file.OpenReadAsync(); { var points = Native.MrzRecognizer.FindCornerPoints(stream); if (points != null) { var pointsScale = 1.0f; Vector2 topLeft = new Vector2(points[0], points[1]), topRight = new Vector2(points[2], points[3]), bottomLeft = new Vector2(points[4], points[5]), bottomRight = new Vector2(points[6], points[7]); if (topRight.X < topLeft.X) { Vector2 tmp = topRight; topRight = topLeft; topLeft = tmp; tmp = bottomRight; bottomRight = bottomLeft; bottomLeft = tmp; } double topLength = Hypotenuse(topRight.X - topLeft.X, topRight.Y - topLeft.Y); double bottomLength = Hypotenuse(bottomRight.X - bottomLeft.X, bottomRight.Y - bottomLeft.Y); double leftLength = Hypotenuse(bottomLeft.X - topLeft.X, bottomLeft.Y - topLeft.Y); double rightLength = Hypotenuse(bottomRight.X - topRight.X, bottomRight.Y - topRight.Y); double tlRatio = topLength / leftLength; double trRatio = topLength / rightLength; double blRatio = bottomLength / leftLength; double brRatio = bottomLength / rightLength; if ((tlRatio >= 1.35 && tlRatio <= 1.75) && (blRatio >= 1.35 && blRatio <= 1.75) && (trRatio >= 1.35 && trRatio <= 1.75) && (brRatio >= 1.35 && brRatio <= 1.75)) { double avgRatio = (tlRatio + trRatio + blRatio + brRatio) / 4.0; float newWidth = 1024; float newHeight = (int)Math.Round(1024 / avgRatio); stream.Seek(0); var props = await file.Properties.GetImagePropertiesAsync(); var decoder = await BitmapDecoder.CreateAsync(stream); var pixelData2 = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, new BitmapTransform(), ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage); var pixelData = pixelData2.DetachPixelData(); Source.Width = newWidth; Source.Height = newHeight; CanvasDevice device = CanvasDevice.GetSharedDevice(); CanvasRenderTarget offscreen = new CanvasRenderTarget(device, newWidth, newHeight, 96); using (CanvasDrawingSession ds = offscreen.CreateDrawingSession()) { ds.Clear(Colors.Red); var bitmap = CanvasBitmap.CreateFromBytes(device, pixelData, (int)decoder.PixelWidth, (int)decoder.PixelHeight, Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized); var t = general2DProjection( topLeft.X, topLeft.Y, 0, 0, topRight.X, topRight.Y, newWidth, 0, bottomRight.X, bottomRight.Y, newWidth, newHeight, bottomLeft.X, bottomLeft.Y, 0, newHeight); for (int i = 0; i != 9; ++i) t[i] = t[i] / t[8]; var matrix = new Matrix4x4(t[0], t[3], 0, t[6], t[1], t[4], 0, t[7], 0, 0, 1, 0, t[2], t[5], 0, t[8]); ds.DrawImage(bitmap, 0, 0, new Rect(0, 0, props.Width, props.Height), 1, CanvasImageInterpolation.Linear, matrix); } using (var memory = new InMemoryRandomAccessStream()) { await offscreen.SaveAsync(memory, CanvasBitmapFileFormat.Png, 1); memory.Seek(0); var charRects = Native.MrzRecognizer.BinarizeAndFindCharacters(memory, out string mrz); offscreen = new CanvasRenderTarget(device, newWidth, newHeight, 96); using (CanvasDrawingSession ds = offscreen.CreateDrawingSession()) { ds.Clear(Colors.Red); var bitmap = CanvasBitmap.CreateFromBytes(device, pixelData, (int)decoder.PixelWidth, (int)decoder.PixelHeight, Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized); var t = general2DProjection( topLeft.X, topLeft.Y, 0, 0, topRight.X, topRight.Y, newWidth, 0, bottomRight.X, bottomRight.Y, newWidth, newHeight, bottomLeft.X, bottomLeft.Y, 0, newHeight); for (int i = 0; i != 9; ++i) t[i] = t[i] / t[8]; var matrix = new Matrix4x4(t[0], t[3], 0, t[6], t[1], t[4], 0, t[7], 0, 0, 1, 0, t[2], t[5], 0, t[8]); ds.DrawImage(bitmap, 0, 0, new Rect(0, 0, props.Width, props.Height), 1, CanvasImageInterpolation.Linear, matrix); foreach (var line in charRects) { foreach (var box in line) { ds.DrawRectangle(box, Colors.Red, 2); } } } await offscreen.SaveAsync(memory, CanvasBitmapFileFormat.Png, 1); var bitmapImage = new BitmapImage(); await bitmapImage.SetSourceAsync(memory); Source.Source = bitmapImage; var result = ParseMrz(mrz); String type = "unknown"; if (result.Type == RecognitionResult.TYPE_PASSPORT) type = "Passport"; else if (result.Type == RecognitionResult.TYPE_ID) type = "ID"; String info = "Type: " + type + "\n" + "Number: " + result.Number + "\n" + "First name: " + result.FirstName + "\nLast name: " + result.LastName + "\n" + "Gender: " + (result.Gender == RecognitionResult.GENDER_MALE ? "male" : (result.Gender == RecognitionResult.GENDER_FEMALE ? "female" : "unknown")) + "\n" + "Birth date: " + result.birthDay + "." + result.birthMonth + "." + result.birthYear + "\n" + "Expiry date: " + (result.DoesNotExpire ? "does not expire" : (result.expiryDay + "." + result.expiryMonth + "." + result.expiryYear)) + "\n" + "Issuing country: " + (result.IssuingCountry) + "\n" + "Nationality: " + (result.Nationality) + "\n"; Mrz.Text = result.Raw; Info.Text = info; } } stream.Dispose(); //Lines.Children.Clear(); //Lines.Children.Add(new Line { X1 = topLeft.X, Y1 = topLeft.Y, X2 = topRight.X, Y2 = topRight.Y, Stroke = new SolidColorBrush(Colors.Red), StrokeThickness = 2 }); //Lines.Children.Add(new Line { X1 = topRight.X, Y1 = topRight.Y, X2 = bottomRight.X, Y2 = bottomRight.Y, Stroke = new SolidColorBrush(Colors.Red), StrokeThickness = 2 }); //Lines.Children.Add(new Line { X1 = bottomRight.X, Y1 = bottomRight.Y, X2 = bottomLeft.X, Y2 = bottomLeft.Y, Stroke = new SolidColorBrush(Colors.Red), StrokeThickness = 2 }); //Lines.Children.Add(new Line { X1 = bottomLeft.X, Y1 = bottomLeft.Y, X2 = topLeft.X, Y2 = topLeft.Y, Stroke = new SolidColorBrush(Colors.Red), StrokeThickness = 2 }); } } }
public static async Task <StorageFile> CompressAndSaveFileAsync(String _pathIn, String _pathOut, String _nameOut, uint _sizePic, Boolean _square) { try { bool _inverted = false; StorageFolder folder_out = await StorageFolder.GetFolderFromPathAsync(_pathOut); StorageFile file_in = await StorageFile.GetFileFromPathAsync(_pathIn); StorageFile file_out = await folder_out.CreateFileAsync(_nameOut, CreationCollisionOption.ReplaceExisting); IRandomAccessStream sourceStream = await file_in.OpenAsync(FileAccessMode.Read); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream); Double _ratio = (Double)decoder.OrientedPixelWidth / (Double)decoder.OrientedPixelHeight; BitmapTransform transform = new BitmapTransform(); if (decoder.OrientedPixelWidth != decoder.PixelWidth) { _inverted = true; } uint HeightOut, WidthOut; if (_ratio > 1) { transform.ScaledHeight = _sizePic; transform.ScaledWidth = (uint)(_sizePic * _ratio); HeightOut = _sizePic; WidthOut = _square ? _sizePic : (uint)(_sizePic * _ratio); if (_square && (_ratio < 2)) { transform.Bounds = new BitmapBounds() { Height = HeightOut, Width = WidthOut, X = (uint)(_sizePic * (_ratio - 1)) } } ; else { transform.Bounds = new BitmapBounds() { Height = HeightOut, Width = WidthOut } }; } else { if (_inverted) { transform.ScaledHeight = _sizePic; transform.ScaledWidth = (uint)(_sizePic / _ratio);; HeightOut = _square ? _sizePic : (uint)(_sizePic / _ratio); WidthOut = _sizePic; transform.Bounds = new BitmapBounds() { Height = HeightOut, Width = WidthOut }; } else { transform.ScaledHeight = (uint)(_sizePic / _ratio); transform.ScaledWidth = _sizePic; HeightOut = _square ? _sizePic : (uint)(_sizePic / _ratio); WidthOut = _sizePic; transform.Bounds = new BitmapBounds() { Height = HeightOut, Width = WidthOut }; } } PixelDataProvider pixelData = await decoder.GetPixelDataAsync( BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage); IRandomAccessStream destinationStream = await file_out.OpenAsync(FileAccessMode.ReadWrite); BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destinationStream); encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, WidthOut, HeightOut, 96, 96, pixelData.DetachPixelData()); await encoder.FlushAsync(); destinationStream.Dispose(); return(file_out); } catch (Exception e) { Debug.WriteLine(e.Message); return(null); } }
private async void mohu_Click(object sender, RoutedEventArgs e) { string desiredName = DateTime.Now.Ticks + ".jpg"; StorageFolder applicationFolder = ApplicationData.Current.LocalFolder; StorageFolder folder = await applicationFolder.CreateFolderAsync("Pic", CreationCollisionOption.OpenIfExists); StorageFile saveFile = await folder.CreateFileAsync(desiredName, CreationCollisionOption.OpenIfExists); RenderTargetBitmap bitmap = new RenderTargetBitmap(); await bitmap.RenderAsync(Img); var pixelBuffer = await bitmap.GetPixelsAsync(); using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); } if (saveFile == null) { // The user cancelled the picking operation return; } SoftwareBitmap inputBitmap; using (IRandomAccessStream stream = await saveFile.OpenAsync(FileAccessMode.Read)) { // Create the decoder from the stream BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); // Get the SoftwareBitmap representation of the file inputBitmap = await decoder.GetSoftwareBitmapAsync(); } if (inputBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 || inputBitmap.BitmapAlphaMode != BitmapAlphaMode.Premultiplied) { inputBitmap = SoftwareBitmap.Convert(inputBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); } SoftwareBitmap outputBitmap = new SoftwareBitmap(inputBitmap.BitmapPixelFormat, inputBitmap.PixelWidth, inputBitmap.PixelHeight, BitmapAlphaMode.Premultiplied); var helper = new OpenCVBridge.OpenCVHelper(); helper.Blur(inputBitmap, outputBitmap); var bitmapSource = new SoftwareBitmapSource(); await bitmapSource.SetBitmapAsync(outputBitmap); Img.Source = bitmapSource; }
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(); } }
/// <summary> /// Gets bitmap. /// </summary> /// <param name="image">The image.</param> /// <returns>Returns bitmap.</returns> private Bitmap GetBitmap(OxyImage image) { if (image == null) { return null; } if (!this.imagesInUse.Contains(image)) { this.imagesInUse.Add(image); } Bitmap res; using (var stream = new MemoryStream(image.GetData())) { var decoder = new BitmapDecoder(this.wicFactory, stream, DecodeOptions.CacheOnDemand); var frame = decoder.GetFrame(0); var converter = new FormatConverter(this.wicFactory); converter.Initialize(frame, dx.WIC.PixelFormat.Format32bppPRGBA); res = Bitmap.FromWicBitmap(this.renderTarget, converter); } this.imageCache.Add(image, res); return res; }
public static void ClampScaleImage( string srcImagePath, string dstImagePath, int clampMin, int clampMax, byte scaleMin = 0, byte scaleMax = 255) { // Learned how to go from managed memory to pointers for image manipulation from this: // https://docs.microsoft.com/en-us/dotnet/api/system.drawing.imaging.bitmapdata?view=netframework-4.7.2 // src BitmapDecoder decoder = null; Stream imageStreamSource = new FileStream(srcImagePath, FileMode.Open, FileAccess.Read, FileShare.Read); { string ext = Path.GetExtension(srcImagePath); switch (ext.ToLower()) { case ".png": decoder = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); break; case ".tif": case ".tiff": decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); break; case ".jpg": case ".jpeg": decoder = new JpegBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); break; case ".bmp": decoder = new BmpBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); break; default: Trace.Assert(false); break; // unsupported extention } } BitmapSource bitmapSource = decoder.Frames[0]; int srcBytesPerPixel = bitmapSource.Format.BitsPerPixel / 8; int stride = (int)bitmapSource.PixelWidth * srcBytesPerPixel; byte[] pixels = new byte[(int)bitmapSource.PixelHeight * stride]; bitmapSource.CopyPixels(pixels, stride, 0); int srcWidth = bitmapSource.PixelWidth; int srcHeight = bitmapSource.PixelHeight; int srcTotalPixels = srcWidth * srcHeight; // dst var dst = new Bitmap(srcWidth, srcHeight, format: System.Drawing.Imaging.PixelFormat.Format24bppRgb); var rect = new Rectangle(0, 0, srcWidth, srcHeight); System.Drawing.Imaging.BitmapData dstData = dst.LockBits(rect, System.Drawing.Imaging.ImageLockMode.WriteOnly, dst.PixelFormat); IntPtr dstPtr = dstData.Scan0; int dstBytes = Math.Abs(dstData.Stride) * dst.Height; byte[] dstRgbValues = new byte[dstBytes]; System.Runtime.InteropServices.Marshal.Copy(dstPtr, dstRgbValues, 0, dstBytes); int dstBytesPerPixel = Image.GetPixelFormatSize(dst.PixelFormat) / 8; Debug.Assert(dstBytesPerPixel == 3); for (int i = 0; i < srcTotalPixels; i++) { int s = i * srcBytesPerPixel; int d = i * dstBytesPerPixel; byte vLo = pixels[s + 0]; byte vHi = pixels[s + 1]; int v = (vHi << 8) | vLo; v = Math.Min(v, clampMax); v = Math.Max(v, clampMin); float ans = (v - clampMin) * (scaleMax - scaleMin) / (clampMax - clampMin); dstRgbValues[d + 0] = (byte)ans; dstRgbValues[d + 1] = (byte)ans; dstRgbValues[d + 2] = (byte)ans; } System.Runtime.InteropServices.Marshal.Copy(dstRgbValues, 0, dstPtr, dstBytes); dst.UnlockBits(dstData); System.Drawing.Imaging.ImageFormat format = null; { string ext = Path.GetExtension(dstImagePath); format = System.Drawing.Imaging.ImageFormat.Bmp; switch (ext.ToLower()) { case ".png": format = System.Drawing.Imaging.ImageFormat.Png; break; case ".tif": case ".tiff": format = System.Drawing.Imaging.ImageFormat.Tiff; break; case ".jpg": case ".jpeg": format = System.Drawing.Imaging.ImageFormat.Jpeg; break; case ".bmp": format = System.Drawing.Imaging.ImageFormat.Bmp; break; default: Trace.Assert(false); break; // unsupported extention } } dst.Save(dstImagePath, format); }
public static async Task <IRandomAccessStream> ResizeImage(this IRandomAccessStream imageStream, uint width, uint height, InterpolationMode interpolationMode) { IRandomAccessStream resizedStream = imageStream; var decoder = await BitmapDecoder.CreateAsync(imageStream); if (decoder.OrientedPixelHeight > height || decoder.OrientedPixelWidth > width) { using (imageStream) { resizedStream = new InMemoryRandomAccessStream(); BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder); double widthRatio = (double)width / decoder.OrientedPixelWidth; double heightRatio = (double)height / decoder.OrientedPixelHeight; double scaleRatio = Math.Min(widthRatio, heightRatio); if (width == 0) { scaleRatio = heightRatio; } if (height == 0) { scaleRatio = widthRatio; } uint aspectHeight = (uint)Math.Floor(decoder.OrientedPixelHeight * scaleRatio); uint aspectWidth = (uint)Math.Floor(decoder.OrientedPixelWidth * scaleRatio); if (interpolationMode == InterpolationMode.None) { encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.NearestNeighbor; } 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.Linear; } encoder.BitmapTransform.ScaledHeight = aspectHeight; encoder.BitmapTransform.ScaledWidth = aspectWidth; await encoder.FlushAsync(); resizedStream.Seek(0); } } return(resizedStream); }
//------------------------------------------------------------------------------------- // Decodes an image array, resizing/format converting as needed //------------------------------------------------------------------------------------- private static Image DecodeMultiframe(WICFlags flags, ImageDescription metadata, BitmapDecoder decoder) { var image = Image.New(metadata); Guid sourceGuid; if (!ToWIC(metadata.Format, out sourceGuid)) { return(null); } for (int index = 0; index < metadata.ArraySize; ++index) { var pixelBuffer = image.PixelBuffer[index, 0]; using (var frame = decoder.GetFrame(index)) { var pfGuid = frame.PixelFormat; var size = frame.Size; if (pfGuid == sourceGuid) { if (size.Width == metadata.Width && size.Height == metadata.Height) { // This frame does not need resized or format converted, just copy... frame.CopyPixels(pixelBuffer.RowStride, pixelBuffer.DataPointer, pixelBuffer.BufferStride); } else { // This frame needs resizing, but not format converted using (var scaler = new BitmapScaler(Factory)) { scaler.Initialize(frame, metadata.Width, metadata.Height, GetWICInterp(flags)); scaler.CopyPixels(pixelBuffer.RowStride, pixelBuffer.DataPointer, pixelBuffer.BufferStride); } } } else { // This frame required format conversion using (var converter = new FormatConverter(Factory)) { converter.Initialize(frame, pfGuid, GetWICDither(flags), null, 0, BitmapPaletteType.Custom); if (size.Width == metadata.Width && size.Height == metadata.Height) { converter.CopyPixels(pixelBuffer.RowStride, pixelBuffer.DataPointer, pixelBuffer.BufferStride); } else { // This frame needs resizing, but not format converted using (var scaler = new BitmapScaler(Factory)) { scaler.Initialize(frame, metadata.Width, metadata.Height, GetWICInterp(flags)); scaler.CopyPixels(pixelBuffer.RowStride, pixelBuffer.DataPointer, pixelBuffer.BufferStride); } } } } } } return(image); }
async void RunCustomVision() { try { _misty.SkillLogger.Log("Taking picture to analyze"); _misty.SendDebugMessage("Taking picture to analyze", null); ITakePictureResponse takePictureResponse = await _misty.TakePictureAsync("oretest.jpg", false, true, true, 640, 480); _misty.SendDebugMessage("Picture taken", null); SoftwareBitmap softwareBitmap; using (IRandomAccessStream stream = new MemoryStream((byte[])takePictureResponse.Data.Image).AsRandomAccessStream()) { stream.Seek(0); // Create the decoder from the stream BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); // Get the SoftwareBitmap representation of the file in BGRA8 format softwareBitmap = await decoder.GetSoftwareBitmapAsync(); softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); } // Encapsulate the image in the WinML image type (VideoFrame) to be bound and evaluated VideoFrame inputImage = VideoFrame.CreateWithSoftwareBitmap(softwareBitmap); _misty.SendDebugMessage("Picture processed, sending to model", null); // Evaluate the image OnnxModelOutput output = await EvaluateVideoFrameAsync(inputImage); _misty.SendDebugMessage("Model finished eval", null); await _misty.DisplayImageAsync("e_DefaultContent.jpg", 100); if (output == null) { _misty.SendDebugMessage("Model output empty", null); _misty.ChangeLED(0, 0, 0, OnResponse); alreadyRunning = false; } else { int vectorCount = output.detected_classes.GetAsVectorView().Count; double initialScore = output.detected_scores.GetAsVectorView()[0]; long initialClass = output.detected_classes.GetAsVectorView()[0]; if (vectorCount == 0 || initialScore < 0.25) { _misty.ChangeLED(0, 0, 0, OnResponse); alreadyRunning = false; } else if (initialClass == 1 && initialScore >= 0.25) { _misty.ChangeLED(255, 0, 0, OnResponse); _misty.RunSkill("e1fcbf5b-9163-4d09-8707-bffd00ddcd5d", null, null); alreadyRunning = false; } else if (initialClass == 0 && initialScore >= 0.25) { _misty.ChangeLED(0, 0, 255, OnResponse); //Say found Ore //_misty.RunSkill("a61832ab-6bc1-4f1a-9de1-0d1dc8bf3ff0", null, null); var data = new StringContent("{ \"text\":\"Ore Found!\",\"pitch\":0,\"speechRate\":0,\"voice\":null,\"flush\":false,\"utteranceId\":null }", Encoding.UTF8, "application/json"); HttpResponseMessage result = await client.PostAsync("http://127.0.0.1/api/tts/speak?text=Ore Found!&pitch=0&speechRate=0&flush=false", data); double calcTrajectory = yaw.getYaw() + (25 * (((output.detected_boxes.GetAsVectorView()[0] + output.detected_boxes.GetAsVectorView()[2]) / 2) - 0.5) * -1); await _misty.SendDebugMessageAsync("Trajectory: " + calcTrajectory); //Take the current yaw of the robot and then add the box X axis percentage //The 20 number is approximately how many degrees you have to rotate to go from edge to center of the camera if (calcTrajectory > yaw.getYaw()) { await _misty.DriveAsync(0, 5); } else { await _misty.DriveAsync(0, -5); } //data = new StringContent("{ \"heading\":" + calcTrajectory.ToString() + ",\"radius\":0,\"timeMs\":3000,\"reverse\":false }", Encoding.UTF8, "application/json"); //result = await client.PostAsync("http://127.0.0.1/api/drive/arc", data); yaw.setTargetYaw(calcTrajectory); yaw.YawReached += HandleYawReached; calcTrajectory = _currentHeadPitch + (80 * (((output.detected_boxes.GetAsVectorView()[1] + output.detected_boxes.GetAsVectorView()[3]) / 2) - 0.5)); await _misty.MoveHeadAsync(calcTrajectory, 0, 0, 100, AngularUnit.Degrees); //_misty.DriveArc(calcTrajectory, 0.2, 2000, false, null); //357.47 deg 50% at 2sec = 341.88 16 degree 342.46 } } } catch (Exception ex) { alreadyRunning = false; _misty.SendDebugMessage($"error: {ex.Message}", null); _misty.SendDebugMessage("Picture processing failed", null); } }
public BitmapBrush makeBitmapBrush(string imgName, RenderTarget renderTarget, bool blankImage = false) { //TODO : 여기 바꿔라! string imageSrc = ""; if (blankImage) { SharpDX.Direct2D1.PixelFormat pf = new SharpDX.Direct2D1.PixelFormat() { AlphaMode = D3DHandler.ALPHA_MODE, Format = D3DHandler.RENDER_FORMAT }; BitmapRenderTarget pallete = new BitmapRenderTarget(renderTarget, CompatibleRenderTargetOptions.GdiCompatible, pf); return(new BitmapBrush(renderTarget, pallete.Bitmap, new BitmapBrushProperties() { ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap })); } if (resourceCore.getFile(imgName, out ResFile resFile)) { ImagingFactory imagingFactory = new ImagingFactory(); /*NativeFileStream fileStream = new NativeFileStream(imageSrc, * NativeFileMode.Open, NativeFileAccess.Read);*/ MemoryStream ms = new MemoryStream(resFile.rawData); BitmapDecoder bitmapDecoder = new BitmapDecoder(imagingFactory, ms, DecodeOptions.CacheOnDemand); BitmapFrameDecode frame = bitmapDecoder.GetFrame(0); FormatConverter converter = new FormatConverter(imagingFactory); converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA); Bitmap bitmap = Bitmap.FromWicBitmap(renderTarget, converter); Utilities.Dispose(ref bitmapDecoder); Utilities.Dispose(ref imagingFactory); Utilities.Dispose(ref converter); return(new BitmapBrush(renderTarget, bitmap, new BitmapBrushProperties() { ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap })); } else { Console.WriteLine("{0} missing", imageSrc); SharpDX.Direct2D1.PixelFormat pf = new SharpDX.Direct2D1.PixelFormat() { AlphaMode = D3DHandler.ALPHA_MODE, Format = D3DHandler.RENDER_FORMAT }; BitmapRenderTarget pallete = new BitmapRenderTarget(renderTarget, CompatibleRenderTargetOptions.GdiCompatible, new Size2F(30f, 30f), new Size2(1, 1), pf); pallete.BeginDraw(); pallete.Clear(Color.Purple); pallete.EndDraw(); return(new BitmapBrush(renderTarget, pallete.Bitmap, new BitmapBrushProperties() { ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap })); } }
static public ICaptureProcessor createCaptureProcessor(string a_FilePath) { if (MainWindow.mCaptureManager == null) { return(null); } string lPresentationDescriptor = "<?xml version='1.0' encoding='UTF-8'?>" + "<PresentationDescriptor StreamCount='1'>" + "<PresentationDescriptor.Attributes Title='Attributes of Presentation'>" + "<Attribute Name='MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK' GUID='{58F0AAD8-22BF-4F8A-BB3D-D2C4978C6E2F}' Title='The symbolic link for a video capture driver.' Description='Contains the unique symbolic link for a video capture driver.'>" + "<SingleValue Value='ImageCaptureProcessor' />" + "</Attribute>" + "<Attribute Name='MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME' GUID='{60D0E559-52F8-4FA2-BBCE-ACDB34A8EC01}' Title='The display name for a device.' Description='The display name is a human-readable string, suitable for display in a user interface.'>" + "<SingleValue Value='Image Capture Processor' />" + "</Attribute>" + "</PresentationDescriptor.Attributes>" + "<StreamDescriptor Index='0' MajorType='MFMediaType_Video' MajorTypeGUID='{73646976-0000-0010-8000-00AA00389B71}'>" + "<MediaTypes TypeCount='1'>" + "<MediaType Index='0'>" + "<MediaTypeItem Name='MF_MT_FRAME_SIZE' GUID='{1652C33D-D6B2-4012-B834-72030849A37D}' Title='Width and height of the video frame.' Description='Width and height of a video frame, in pixels.'>" + "<Value.ValueParts>" + "<ValuePart Title='Width' Value='Temp_Width' />" + "<ValuePart Title='Height' Value='Temp_Height' />" + "</Value.ValueParts>" + "</MediaTypeItem>" + "<MediaTypeItem Name='MF_MT_AVG_BITRATE' GUID='{20332624-FB0D-4D9E-BD0D-CBF6786C102E}' Title='Approximate data rate of the video stream.' Description='Approximate data rate of the video stream, in bits per second, for a video media type.'>" + "<SingleValue Value='33570816' />" + "</MediaTypeItem>" + "<MediaTypeItem Name='MF_MT_MAJOR_TYPE' GUID='{48EBA18E-F8C9-4687-BF11-0A74C9F96A8F}' Title='Major type GUID for a media type.' Description='The major type defines the overall category of the media data.'>" + "<SingleValue Value='MFMediaType_Video' GUID='{73646976-0000-0010-8000-00AA00389B71}' />" + "</MediaTypeItem>" + "<MediaTypeItem Name='MF_MT_DEFAULT_STRIDE' GUID='{644B4E48-1E02-4516-B0EB-C01CA9D49AC6}' Title='Default surface stride.' Description='Default surface stride, for an uncompressed video media type. Stride is the number of bytes needed to go from one row of pixels to the next.'>" + "<SingleValue Value='Temp_Stride' />" + "</MediaTypeItem>" + "<MediaTypeItem Name='MF_MT_FIXED_SIZE_SAMPLES' GUID='{B8EBEFAF-B718-4E04-B0A9-116775E3321B}' Title='The fixed size of samples in stream.' Description='Specifies for a media type whether the samples have a fixed size.'>" + "<SingleValue Value='True' />" + "</MediaTypeItem>" + "<MediaTypeItem Name='MF_MT_FRAME_RATE' GUID='{C459A2E8-3D2C-4E44-B132-FEE5156C7BB0}' Title='Frame rate.' Description='Frame rate of a video media type, in frames per second.'>" + "<RatioValue Value='10.0'>" + "<Value.ValueParts>" + "<ValuePart Title='Numerator' Value='20' />" + "<ValuePart Title='Denominator' Value='1' />" + "</Value.ValueParts>" + "</RatioValue>" + "</MediaTypeItem>" + "<MediaTypeItem Name='MF_MT_PIXEL_ASPECT_RATIO' GUID='{C6376A1E-8D0A-4027-BE45-6D9A0AD39BB6}' Title='Pixel aspect ratio.' Description='Pixel aspect ratio for a video media type.'>" + "<RatioValue Value='1'>" + "<Value.ValueParts>" + "<ValuePart Title='Numerator' Value='1' />" + "<ValuePart Title='Denominator' Value='1' />" + "</Value.ValueParts>" + "</RatioValue>" + "</MediaTypeItem>" + "<MediaTypeItem Name='MF_MT_ALL_SAMPLES_INDEPENDENT' GUID='{C9173739-5E56-461C-B713-46FB995CB95F}' Title='Independent of samples.' Description='Specifies for a media type whether each sample is independent of the other samples in the stream.'>" + "<SingleValue Value='True' />" + "</MediaTypeItem>" + "<MediaTypeItem Name='MF_MT_SAMPLE_SIZE' GUID='{DAD3AB78-1990-408B-BCE2-EBA673DACC10}' Title='The fixed size of each sample in stream.' Description='Specifies the size of each sample, in bytes, in a media type.'>" + "<SingleValue Value='Temp_SampleSize' />" + "</MediaTypeItem>" + "<MediaTypeItem Name='MF_MT_INTERLACE_MODE' GUID='{E2724BB8-E676-4806-B4B2-A8D6EFB44CCD}' Title='Describes how the frames are interlaced.' Description='Describes how the frames in a video media type are interlaced.'>" + "<SingleValue Value='MFVideoInterlace_Progressive' />" + "</MediaTypeItem>" + "<MediaTypeItem Name='MF_MT_SUBTYPE' GUID='{F7E34C9A-42E8-4714-B74B-CB29D72C35E5}' Title='Subtype GUID for a media type.' Description='The subtype GUID defines a specific media format type within a major type.'>" + "<SingleValue GUID='{Temp_SubTypeGUID}' />" + "</MediaTypeItem>" + "</MediaType>" + "</MediaTypes>" + "</StreamDescriptor>" + "</PresentationDescriptor>"; ImageCaptureProcessor lICaptureProcessor = new ImageCaptureProcessor(); using (var lImageStream = File.Open(a_FilePath, FileMode.Open)) { if (lImageStream == null) { return(null); } var lBitmap = BitmapDecoder.Create(lImageStream, BitmapCreateOptions.None, BitmapCacheOption.None); if (lBitmap == null) { return(null); } if (lBitmap.Frames == null || lBitmap.Frames.Count == 0) { return(null); } BitmapSource bitmapSource = lBitmap.Frames[0]; int lStride = 0; Guid lMFVideoFormat_RGBFormat = MFVideoFormat_ARGB32; MainWindow.mCaptureManager.getStrideForBitmapInfoHeader(lMFVideoFormat_RGBFormat, (uint)bitmapSource.PixelWidth, out lStride); int width = bitmapSource.PixelWidth; int height = bitmapSource.PixelHeight; int stride = (int)Math.Abs(lStride); lPresentationDescriptor = lPresentationDescriptor.Replace("Temp_Width", ((uint)bitmapSource.PixelWidth).ToString()); lPresentationDescriptor = lPresentationDescriptor.Replace("Temp_Height", ((uint)bitmapSource.PixelHeight).ToString()); lPresentationDescriptor = lPresentationDescriptor.Replace("Temp_Stride", lStride.ToString()); lPresentationDescriptor = lPresentationDescriptor.Replace("Temp_SampleSize", ((uint)(Math.Abs(lStride) * bitmapSource.PixelHeight * 3)).ToString()); lPresentationDescriptor = lPresentationDescriptor.Replace("Temp_SubTypeGUID", lMFVideoFormat_RGBFormat.ToString()); lICaptureProcessor.mPresentationDescriptor = lPresentationDescriptor; foreach (var litem in lBitmap.Frames) { bitmapSource = litem; if (bitmapSource.Format != System.Windows.Media.PixelFormats.Bgra32) { FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap(); newFormatedBitmapSource.BeginInit(); newFormatedBitmapSource.Source = litem; newFormatedBitmapSource.DestinationFormat = System.Windows.Media.PixelFormats.Bgra32; newFormatedBitmapSource.EndInit(); bitmapSource = newFormatedBitmapSource; } byte[] lPixels = new byte[height * stride]; bitmapSource.CopyPixels(lPixels, stride, 0); lICaptureProcessor.mRawDataFrames.Add(new RawDataFrame(lPixels)); } } return(lICaptureProcessor); }
private void Paste() { var data = Clipboard.GetContent(); if (data.Contains(StandardDataFormats.Bitmap)) { var bitmap = Task.Run(async() => { try { var t = await data.GetBitmapAsync(); var t2 = await t.OpenReadAsync(); var dec = await BitmapDecoder.CreateAsync(t2.AsStream().AsRandomAccessStream()); if (dec.PixelWidth != 20 && dec.PixelHeight != 24) { return(null); } var pd = await dec.GetPixelDataAsync(); var bytes = pd.DetachPixelData(); return(bytes); } catch { return(null); } }).Result; if (bitmap == null) { return; } PasteGlyphValue(bitmap); return; } if (!data.Contains(StandardDataFormats.Text)) { return; } var stringData = Task.Run(async() => { try { var clipboardAsync = data.GetTextAsync(); return(await clipboardAsync); } catch { return(null); } }).Result; if (stringData.StartsWith("@")) { PasteGlyphValue(stringData); } else { try { stringData = stringData.Substring(stringData.IndexOf('{'), stringData.IndexOf('}') - stringData.IndexOf('{')); var cd = new List <bool>(); stringData = stringData.Replace('{', ' '); stringData = stringData.Replace('}', ' '); stringData = stringData.Trim(); foreach (var d in stringData.Split(',')) { if (int.TryParse(d, out var b)) { cd.Add(b > 0); } else { return; } } if (cd.Count == GlyphArray.Length) { GlyphArray = cd.ToArray(); } } catch { } } }
private async Task <byte[]> ResizeImage(byte[] imageData, float size) { var bitmap = new BitmapImage(); using (var stream = new InMemoryRandomAccessStream()) { await stream.WriteAsync(imageData.AsBuffer()); stream.Seek(0); await bitmap.SetSourceAsync(stream); } var originHeight = bitmap.PixelHeight; var originWidth = bitmap.PixelWidth; float newHeight = 0; float newWidth = 0; float value = 0; if (originHeight > originWidth) { value = 1 / (originWidth / size); newWidth = size; newHeight = originHeight * value; } else if (originHeight < originWidth) { value = 1 / (originHeight / size); newHeight = size; newWidth = originWidth * value; } else { newHeight = size; newWidth = size; } byte[] resizedData; using (var streamIn = new MemoryStream(imageData)) { using (var imageStream = streamIn.AsRandomAccessStream()) { var decoder = await BitmapDecoder.CreateAsync(imageStream); var resizedStream = new InMemoryRandomAccessStream(); var encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder); encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Linear; encoder.BitmapTransform.ScaledHeight = (uint)newHeight; encoder.BitmapTransform.ScaledWidth = (uint)newWidth; await encoder.FlushAsync(); resizedStream.Seek(0); resizedData = new byte[resizedStream.Size]; await resizedStream.ReadAsync(resizedData.AsBuffer(), (uint)resizedStream.Size, InputStreamOptions.None); } } return(resizedData); }
private static BitmapDecoder GetDecoder(BitmapSource image, Image imageControl, out GifFile gifFile) { gifFile = null; BitmapDecoder decoder = null; Stream stream = null; Uri uri = null; BitmapCreateOptions createOptions = BitmapCreateOptions.None; var bmp = image as BitmapImage; if (bmp != null) { createOptions = bmp.CreateOptions; if (bmp.StreamSource != null) { stream = bmp.StreamSource; } else if (bmp.UriSource != null) { uri = bmp.UriSource; if (!uri.IsAbsoluteUri) { var baseUri = bmp.BaseUri ?? (imageControl as IUriContext)?.BaseUri; if (baseUri != null) { uri = new Uri(baseUri, uri); } } } } else { BitmapFrame frame = image as BitmapFrame; if (frame != null) { decoder = frame.Decoder; Uri.TryCreate(frame.BaseUri, frame.ToString(), out uri); } } if (decoder == null) { if (stream != null) { stream.Position = 0; decoder = BitmapDecoder.Create(stream, createOptions, BitmapCacheOption.OnLoad); } else if (uri != null && uri.IsAbsoluteUri) { decoder = BitmapDecoder.Create(uri, createOptions, BitmapCacheOption.OnLoad); } } if (decoder is GifBitmapDecoder && !CanReadNativeMetadata(decoder)) { if (stream != null) { stream.Position = 0; gifFile = GifFile.ReadGifFile(stream, true); } else if (uri != null) { gifFile = DecodeGifFile(uri); } else { throw new InvalidOperationException("Can't get URI or Stream from the source. AnimatedSource should be either a BitmapImage, or a BitmapFrame constructed from a URI."); } } if (decoder == null) { throw new InvalidOperationException("Can't get a decoder from the source. AnimatedSource should be either a BitmapImage or a BitmapFrame."); } return(decoder); }
public async Task TestExtractVideoFrameAsync() { Uri uri = new Uri(Constants.DownloadUriSource); Assert.IsNotNull(uri); StorageFile file = await StorageFile.CreateStreamedFileFromUriAsync(Constants.DownloadStreamedFileName, uri, null); Assert.IsNotNull(file); IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read); Assert.IsNotNull(readStream); // CreateFromStreamAsync should return valid FFmpegInteropMSS object which generates valid MediaStreamSource object var frameGrabber = await FrameGrabber.CreateFromStreamAsync(readStream); var frame = await frameGrabber.ExtractVideoFrameAsync(TimeSpan.Zero); Assert.IsNotNull(frame); using (var stream = new InMemoryRandomAccessStream()) { // encode as jpeg await frame.EncodeAsJpegAsync(stream); stream.Seek(0); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); var bitmap = await decoder.GetFrameAsync(0); Assert.IsNotNull(bitmap); // encode as png stream.Seek(0); stream.Size = 0; await frame.EncodeAsPngAsync(stream); stream.Seek(0); decoder = await BitmapDecoder.CreateAsync(stream); bitmap = await decoder.GetFrameAsync(0); Assert.IsNotNull(bitmap); // encode as bmp stream.Seek(0); stream.Size = 0; await frame.EncodeAsBmpAsync(stream); stream.Seek(0); decoder = await BitmapDecoder.CreateAsync(stream); bitmap = await decoder.GetFrameAsync(0); Assert.IsNotNull(bitmap); } }
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: case QuickStartType.UpdateApp: { if (Uri.TryCreate(Protocol.Text, UriKind.Absolute, out Uri Result)) { if (Result.IsFile) { if (WIN_Native_API.CheckExist(Protocol.Text)) { try { StorageFile ExcuteFile = await StorageFile.GetFileFromPathAsync(Protocol.Text); DisplayName.Text = Convert.ToString((await ExcuteFile.Properties.RetrievePropertiesAsync(new string[] { "System.FileDescription" }))["System.FileDescription"]); if (await ExcuteFile.GetThumbnailBitmapAsync().ConfigureAwait(true) is BitmapImage Image) { Icon.Source = Image; } else { Icon.Source = new BitmapImage(new Uri("ms-appx:///Assets/Page_Solid_White.png")); } RenderTargetBitmap RTB = new RenderTargetBitmap(); await RTB.RenderAsync(Icon); StorageFile FileThumbnail = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("FileThumbnail.png", CreationCollisionOption.ReplaceExisting); using (IRandomAccessStream Stream = await FileThumbnail.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder Encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, Stream); byte[] PixelData = (await RTB.GetPixelsAsync()).ToArray(); Encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)RTB.PixelWidth, (uint)RTB.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, PixelData); await Encoder.FlushAsync(); } 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; 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)) { StorageFile FileThumbnail = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("FileThumbnail.png", CreationCollisionOption.ReplaceExisting); using (IRandomAccessStream Stream = await FileThumbnail.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder Encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, Stream); Encoder.SetSoftwareBitmap(ResizeBitmap); await Encoder.FlushAsync(); } ImageFile = FileThumbnail; using (IRandomAccessStream Stream = await FileThumbnail.OpenAsync(FileAccessMode.Read)) { BitmapImage Source = new BitmapImage(); await Source.SetSourceAsync(Stream); Icon.Source = Source; } } } } else { FormatErrorTip.IsOpen = true; } } } else { FormatErrorTip.IsOpen = true; } break; } case QuickStartType.WebSite: case QuickStartType.UpdateWeb: { try { if (Uri.TryCreate(Protocol.Text, UriKind.Absolute, out Uri Result)) { Uri ImageUri = new Uri(Result, "favicon.ico"); HttpWebRequest Request = WebRequest.CreateHttp(ImageUri); using (WebResponse Response = await Request.GetResponseAsync().ConfigureAwait(true)) using (Stream ImageStream = Response.GetResponseStream()) { StorageFile DownloadImage = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("DownloadFile.ico", CreationCollisionOption.ReplaceExisting); using (Stream FileStream = await DownloadImage.OpenStreamForWriteAsync().ConfigureAwait(true)) { await ImageStream.CopyToAsync(FileStream).ConfigureAwait(true); } ImageFile = DownloadImage; } Icon.Source = new BitmapImage(ImageUri); } 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().ConfigureAwait(true)) using (Stream ImageStream = Response.GetResponseStream()) { StorageFile DownloadImage = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("DownloadFile.ico", CreationCollisionOption.ReplaceExisting); using (Stream FileStream = await DownloadImage.OpenStreamForWriteAsync().ConfigureAwait(true)) { await ImageStream.CopyToAsync(FileStream).ConfigureAwait(true); } ImageFile = DownloadImage; } Icon.Source = new BitmapImage(QueryUrl); } catch { FailureTips.IsOpen = true; } } break; } } }
private void WriteCopyOfPictureUsingWic(string originalFileName, string outputFileName) { bool tryOneLastMethod = false; using (Stream originalFile = new FileStream(originalFileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { BitmapCreateOptions createOptions = BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreColorProfile; BitmapDecoder original = BitmapDecoder.Create(originalFile, createOptions, BitmapCacheOption.None); JpegBitmapEncoder output = new JpegBitmapEncoder(); if (original.Frames[0] != null && original.Frames[0].Metadata != null) { BitmapMetadata bitmapMetadata = original.Frames[0].Metadata.Clone() as BitmapMetadata; bitmapMetadata.SetQuery("/app1/ifd/PaddingSchema:Padding", METADATA_PADDING_IN_BYTES); bitmapMetadata.SetQuery("/app1/ifd/exif/PaddingSchema:Padding", METADATA_PADDING_IN_BYTES); bitmapMetadata.SetQuery("/xmp/PaddingSchema:Padding", METADATA_PADDING_IN_BYTES); SetMetadata(bitmapMetadata); output.Frames.Add(BitmapFrame.Create(original.Frames[0], original.Frames[0].Thumbnail, bitmapMetadata, original.Frames[0].ColorContexts)); } try { using (Stream outputFile = File.Open(outputFileName, FileMode.Create, FileAccess.ReadWrite)) { output.Save(outputFile); } } catch (NotSupportedException e) { System.Diagnostics.Debug.Print(e.Message); output = new JpegBitmapEncoder(); output.Frames.Add(BitmapFrame.Create(original.Frames[0], original.Frames[0].Thumbnail, original.Metadata, original.Frames[0].ColorContexts)); using (Stream outputFile = File.Open(outputFileName, FileMode.Create, FileAccess.ReadWrite)) { output.Save(outputFile); } tryOneLastMethod = true; } } if (tryOneLastMethod) { File.Move(outputFileName, outputFileName + "tmp"); using (Stream recentlyOutputFile = new FileStream(outputFileName + "tmp", FileMode.Open, FileAccess.Read, FileShare.Read)) { BitmapCreateOptions createOptions = BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreColorProfile; BitmapDecoder original = BitmapDecoder.Create(recentlyOutputFile, createOptions, BitmapCacheOption.None); JpegBitmapEncoder output = new JpegBitmapEncoder(); if (original.Frames[0] != null && original.Frames[0].Metadata != null) { BitmapMetadata bitmapMetadata = original.Frames[0].Metadata.Clone() as BitmapMetadata; bitmapMetadata.SetQuery("/app1/ifd/PaddingSchema:Padding", METADATA_PADDING_IN_BYTES); bitmapMetadata.SetQuery("/app1/ifd/exif/PaddingSchema:Padding", METADATA_PADDING_IN_BYTES); bitmapMetadata.SetQuery("/xmp/PaddingSchema:Padding", METADATA_PADDING_IN_BYTES); SetMetadata(bitmapMetadata); output.Frames.Add(BitmapFrame.Create(original.Frames[0], original.Frames[0].Thumbnail, bitmapMetadata, original.Frames[0].ColorContexts)); } using (Stream outputFile = File.Open(outputFileName, FileMode.Create, FileAccess.ReadWrite)) { output.Save(outputFile); } } File.Delete(outputFileName + "tmp"); } }
private static D2DBitmap CreateBitmapFromDecoder(RenderTarget renderTarget, ImagingFactory wicFactory, BitmapDecoder decoder) { BitmapFrameDecode source; FormatConverter converter; // Create the initial frame. source = decoder.GetFrame(0); // Convert the image format to 32bppPBGRA -- which Direct2D expects. converter = wicFactory.CreateFormatConverter(); converter.Initialize( source.ToBitmapSource(), PixelFormats.Pbgra32Bpp, BitmapDitherType.None, BitmapPaletteType.MedianCut ); // Create a Direct2D bitmap from the WIC bitmap. return(renderTarget.CreateBitmapFromWicBitmap( converter.ToBitmapSource())); }
// Return a vector of software bitmaps of maximum count of maxFrames selected by a user and loaded from a stream public async Task <List <SoftwareBitmap> > GetSelectedSoftwareBitmaps() { // <SnippetGetMaxLLFFrames> // Query the supported max number of input bitmap frames for Low Light Fusion int maxFrames = LowLightFusion.MaxSupportedFrameCount; // The bitmap frames to perform Low Light Fusion on. var framelist = new List <SoftwareBitmap>(maxFrames); // </SnippetGetMaxLLFFrames> // <SnippetGetFrames> var fileOpenPicker = new FileOpenPicker(); fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; fileOpenPicker.FileTypeFilter.Add(".png"); fileOpenPicker.ViewMode = PickerViewMode.Thumbnail; var inputFiles = await fileOpenPicker.PickMultipleFilesAsync(); if (inputFiles == null) { // The user cancelled the picking operation return(null); } if (inputFiles.Count >= maxFrames) { Debug.WriteLine("You can only choose up to {0} image(s) to input.", maxFrames); } // </SnippetGetFrames> // <SnippetDecodeFrames> SoftwareBitmap softwareBitmap; // Decode the images into bitmaps for (int i = 0; i < inputFiles.Count; i++) { using (IRandomAccessStream stream = await inputFiles[0].OpenAsync(FileAccessMode.Read)) { // Create the decoder from the stream BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); // Get the SoftwareBitmap representation of the file softwareBitmap = await decoder.GetSoftwareBitmapAsync(); framelist.Add(softwareBitmap); } } // Ensure that the selected bitmap frames have an acceptable pixel format for Low Light Fusion. // For this sample, we'll use the pixel format at index 0. IReadOnlyList <BitmapPixelFormat> formats = LowLightFusion.SupportedBitmapPixelFormats; BitmapPixelFormat llfFormat = formats[0]; for (int i = 0; i < framelist.Count; i++) { if (framelist[i].BitmapPixelFormat == llfFormat) { // The pixel format is acceptable } else { // Convert the pixel format framelist[i] = SoftwareBitmap.Convert(framelist[i], llfFormat); } } return(framelist); // </SnippetDecodeFrames> }
public void Execute() { string path; using (var inputStream = File.OpenRead(_file)) { var decoder = BitmapDecoder.Create( inputStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); var encoder = BitmapEncoder.Create(decoder.CodecInfo.ContainerFormat); if (!encoder.CanEncode()) { encoder = BitmapEncoder.Create(_settings.FallbackEncoder); } ConfigureEncoder(encoder); if (decoder.Metadata != null) { try { encoder.Metadata = decoder.Metadata; } catch (InvalidOperationException) { } } if (decoder.Palette != null) { encoder.Palette = decoder.Palette; } foreach (var originalFrame in decoder.Frames) { BitmapMetadata metadata = (BitmapMetadata)originalFrame.Metadata; if (metadata != null) { try { // Detect whether metadata can copied successfully _ = metadata.Clone(); } catch (ArgumentException) { metadata = null; } } encoder.Frames.Add( BitmapFrame.Create( Transform(originalFrame), thumbnail: null, metadata, // TODO: Add an option to strip any metadata that doesn't affect rendering (issue #3) colorContexts: null)); } path = GetDestinationPath(encoder); Directory.CreateDirectory(Path.GetDirectoryName(path)); using (var outputStream = File.Open(path, FileMode.CreateNew, FileAccess.Write)) { encoder.Save(outputStream); } } if (_settings.KeepDateModified) { File.SetLastWriteTimeUtc(path, File.GetLastWriteTimeUtc(_file)); } if (_settings.Replace) { var backup = GetBackupPath(); File.Replace(path, _file, backup, ignoreMetadataErrors: true); FileSystem.DeleteFile(backup, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin); } }
private async Task loadMeta(Photo photo, ObservableCollection <Photo> list) { try { if (photo.Disposed) { return; } var mmap = MemoryMappedFile.CreateFromFile( File.Open(photo.FileName, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.Read), mmapName(photo.FileName), 0, MemoryMappedFileAccess.Read, HandleInheritability.None, false); var img = new BitmapImage(); Photo.Metadata metadata; DispatcherOperation metaSet; try { using (var stream = new UnsafeMemoryMapStream( mmap.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read), FileAccess.Read)) { var data = stream.Stream; { var decoder = BitmapDecoder.Create(data, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); var frames = decoder.Frames; if (frames.Count < 1) { throw new ArgumentException("Image contained no frame data.", nameof(photo)); } if (!(frames[0].Metadata is BitmapMetadata imgMeta)) { throw new NullReferenceException("Image contained no metadata"); } metadata = Exif.GetMetadata(imgMeta); metadata.Width = frames[0].PixelWidth; metadata.Height = frames[0].PixelHeight; } data.Seek(0, SeekOrigin.Begin); metaSet = photo.Dispatcher.InvokeAsync(() => photo.Set(metadata)); img.BeginInit(); img.StreamSource = data; if (3 * metadata.Width > 2 * metadata.Height) { img.DecodePixelWidth = 3 * ThumbnailHeight / 2; } else { img.DecodePixelHeight = ThumbnailHeight; } img.CacheOption = BitmapCacheOption.OnLoad; img.Rotation = Exif.OrienationToRotation(metadata.Orientation); img.EndInit(); img.Freeze(); } await metaSet; } catch { mmap.Dispose(); throw; } if (!await photo.Dispatcher.InvokeAsync(() => { if (photo.Disposed) { return(false); } photo.mmap = mmap; photo.loader = this; photo.ThumbImage = img; return(true); })) { mmap.Dispose(); } } catch (Exception ex) { await photo.Dispatcher.InvokeAsync(() => { MessageBox.Show(ex.ToString(), string.Format("Error loading {0}\n\n{1}", photo.FileName, ex), MessageBoxButton.OK, MessageBoxImage.Error); photo.Dispose(); list.Remove(photo); }); } }
private async void CreateAndSaveVideo() { if (m_files != null && m_files.Count > 0) { if (_isDateNeeded) { SortPhoto(); } StorageFolder myVideoLibrary; //если папка существует открываем ,если нет создаем try { myVideoLibrary = await KnownFolders.PicturesLibrary.GetFolderAsync("ImageConvertor"); } catch { myVideoLibrary = await KnownFolders.PicturesLibrary.CreateFolderAsync("ImageConvertor"); } StorageFile videoFile = await myVideoLibrary.CreateFileAsync(_videoName + ".mp4", CreationCollisionOption.GenerateUniqueName); if (videoFile != null) { PickPhotoBtn.IsEnabled = false; Encode.IsEnabled = false; dateCheckBox.IsChecked = false; durationList.IsEnabled = false; nameBox.IsEnabled = false; BackBar.IsEnabled = false; progressRing.IsActive = true; titleBlock.Text = "Конвертирование . . ."; try { using (IRandomAccessStream videoStream = await videoFile.OpenAsync(FileAccessMode.ReadWrite)) { m_picture = new PictureWriter(videoStream, m_videoWidth, m_videoHeight); foreach (StorageFile file in m_files) { Windows.Storage.FileProperties.ImageProperties properties = await file.Properties.GetImagePropertiesAsync(); var longitude = properties.Longitude; float scaleOfWidth = (float)m_videoWidth / properties.Width; float scaleOfHeight = (float)m_videoHeight / properties.Height; float scale = scaleOfHeight > scaleOfWidth ? scaleOfWidth : scaleOfHeight; uint width = (uint)(properties.Width * scale); uint height = (uint)(properties.Height * scale); using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read)) { for (int i = 0; i < 10 * _durationSec; ++i) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); PixelDataProvider dataProvider = await decoder.GetPixelDataAsync( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, new BitmapTransform { ScaledWidth = width, ScaledHeight = height }, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.ColorManageToSRgb); m_picture.AddFrame(dataProvider.DetachPixelData(), (int)width, (int)height); } } } m_picture.Finalize(); m_picture = null; } } catch (Exception ex) { CreateAndSaveVideo(); } progressRing.IsActive = false; await CreateVideoModelAndWrite(videoFile); //сохраняем данные о файле в локальную папку Frame.Navigate(typeof(MainPage)); } } }
private static ShaderResourceView LoadFromDecoder(D3DDevice device, ImagingFactory factory, BitmapDecoder bitmapDecoder) { if (bitmapDecoder.FrameCount == 0) throw new ArgumentException("Image file successfully loaded, but it has no image frames."); BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0); BitmapSource bitmapSource = bitmapFrameDecode.ToBitmapSource(); // create texture description Texture2DDescription textureDescription = new Texture2DDescription() { Width = bitmapSource.Size.Width, Height = bitmapSource.Size.Height, MipLevels = 1, ArraySize = 1, Format = Format.R8G8B8A8_UNORM, SampleDescription = new SampleDescription() { Count = 1, Quality = 0, }, Usage = Usage.Dynamic, BindFlags = BindFlag.ShaderResource, CpuAccessFlags = CpuAccessFlag.Write, MiscFlags = 0 }; // create texture Texture2D texture = device.CreateTexture2D(textureDescription); // Create a format converter WICFormatConverter converter = factory.CreateFormatConverter(); converter.Initialize( bitmapSource, PixelFormats.Pf32bppRGBA, BitmapDitherType.None, BitmapPaletteType.Custom); // get bitmap data byte[] buffer = converter.CopyPixels(); // Copy bitmap data to texture MappedTexture2D texmap = texture.Map(0, Map.WriteDiscard, MapFlag.Unspecified); Marshal.Copy(buffer, 0, texmap.Data, buffer.Length); texture.Unmap(0); // create shader resource view description ShaderResourceViewDescription srvDescription = new ShaderResourceViewDescription() { Format = textureDescription.Format, ViewDimension = ShaderResourceViewDimension.Texture2D, Texture2D = new Texture2DShaderResourceView() { MipLevels = textureDescription.MipLevels, MostDetailedMip = 0 } }; // create shader resource view from texture return device.CreateShaderResourceView(texture, srvDescription); }