2012-05-03 127 views
1

我試圖在運行時生成一個簡單的tiff圖像。該圖像由從遠程服務器下載的白色背景和圖像組成。在WPF運行時創建tiff圖像

下面是我爲實現這一目標編寫的代碼:

 const string url = "http://localhost/barcode.gif"; 

     var size = new Size(794, 1123); 
     var drawingVisual = new DrawingVisual(); 

     using (var drawingContext = drawingVisual.RenderOpen()) 
     { 
      drawingContext.DrawRectangle(new SolidColorBrush(Colors.White), null, new Rect(size)); 

      var image = new BitmapImage(new Uri(url)); 
      drawingContext.DrawImage(image, new Rect(0, 0, 180, 120)); 
     } 

     var targetBitmap = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Default); 
     targetBitmap.Render(drawingVisual); 

     var convertedBitmap = new FormatConvertedBitmap(targetBitmap, PixelFormats.BlackWhite, null, 0); 

     var encoder = new TiffBitmapEncoder(); 
     encoder.Frames.Add(BitmapFrame.Create(convertedBitmap)); 

     using (var fs = new FileStream("out.tif", FileMode.Create)) 
     { 
      encoder.Save(fs); 
     } 

代碼工作,併產生「out.tif」文件。但輸出文件只有白色背景,沒有從遠程服務器接收到圖像。

可能是什麼問題?我以各種方式嘗試了以下代碼,但每次都沒有運氣。

回答

0

我發現這個關於FormatConvertedBitmap類的閱讀。也許可以試試

 FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap(); 

     // BitmapSource objects like FormatConvertedBitmap can only have their properties 
     // changed within a BeginInit/EndInit block. 
     newFormatedBitmapSource.BeginInit(); 

     // Use the BitmapSource object defined above as the source for this new 
     // BitmapSource (chain the BitmapSource objects together). 
     newFormatedBitmapSource.Source = targetBitmap; 

     // Set the new format to BlackWhite. 
     newFormatedBitmapSource.DestinationFormat = PixelFormats.BlackWhite; 
     newFormatedBitmapSource.EndInit();