在WPF中在运行时创建tiff图像

时间:2012-05-03 21:32:50

标签: wpf tiff

我正在尝试在运行时生成一个简单的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”文件。但输出文件只有白色背景,没有从远程服务器接收到图像。

可能是什么问题?我以各种方式尝试了以下代码,但每次都没有运气。

1 个答案:

答案 0 :(得分: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();