Il faut commencer par implémenter une énumération qui va nous indiquer quel type d'encodeur appliquer pour la sauvegarde du visual en mode image!
[csharp] public enum ImageFormat { Png, Gif, Bmp }Le code de la méthode de sauvegarde offrira une bonne souplesse ... Cependant, si vous voulez récuperer l'objet au lieu de le sauvegarder en fichier ... Il est tout à fait possible de le faire
[csharp] public class ExportVisual { public static void SaveToImageFile(string outputFilePath, Visual visual, int width, int height, ImageFormat imageFormat) { BitmapImage bitmap = new BitmapImage(); RenderTargetBitmap renderTarget = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32); renderTarget.Render(visual); BitmapEncoder encoder; switch (imageFormat) { case ImageFormat.Png: encoder = new PngBitmapEncoder(); break; case ImageFormat.Gif: encoder = new GifBitmapEncoder(); break; case ImageFormat.Bmp: default: encoder = new BmpBitmapEncoder(); break; } encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(renderTarget)); using (FileStream outputStream = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write)) { encoder.Save(outputStream); outputStream.Flush(); } } }Exemple d'utilisation
- XPS: sauvegarde de la page 0 dans un fichier gif
[csharp] System.Windows.Xps.Packaging.XpsDocument xpsDoc = new System.Windows.Xps.Packaging.XpsDocument(xpsFileName, System.IO.FileAccess.Read); System.Windows.Documents.FixedDocumentSequence docSeq = xpsDoc.GetFixedDocumentSequence(); System.Windows.Documents.DocumentPage docPage = docSeq.DocumentPaginator.GetPage(0); ExportVisual.SaveToImageFile(@"ImagePage0.gif", docPage.Visual, (int)docPage.Size.Width, (int)docPage.Size.Height, ImageFormat.Gif);
[csharp] ExportVisual.SaveToImageFile(@"ImageVisual0.gif", m_window, (int)m_window.RenderSize.Width, (int)m_window.RenderSize.Height, ImageFormat.Gif);