在运行时创建WPF的TIFF图像(Creating tiff image at runtime in

2019-10-16 16:11发布

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

可以采取什么问题吗? 我曾尝试以各种方式下面的代码,但每次没有运气。

Answer 1:

我发现这个念叨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();


文章来源: Creating tiff image at runtime in WPF
标签: wpf tiff