使用RenderTargetBitmap在内存中创建位图在生产WCF服务中失败

时间:2017-10-17 00:23:06

标签: wpf wcf iis-7 rendertargetbitmap

我正在使用WPF对象在内存中生成位图图像。执行此操作的程序驻留在WCF Web服务中。当我在IISExpress上本地运行时,以及在测试IIS 7服务器上运行时,图像呈现正确。但是,在QA使用的服务器上运行时,图像无法正确呈现。更具体地,仅渲染250px高度图像的顶部22px行。测试服务器和QA服务器上的设置应该是相同的(在这里插入持怀疑态度的脸)。

问题:IIS中的哪些可能的设置可能会影响此图像渲染?此外,我认为可能存在线程问题,因为RenderTargetBitmap异步渲染,我确实得到了部分图像。

以下是我使用的代码:

private byte[] RenderGauge(ViewData viewData)
{
    double resolution = 4 * ReSize;
    double dpi = 96 * resolution;
    var view = new Gauge();
    var vm = new GuageViewModel(viewData);

    view.Measure(new Size(350, 70));
    view.Arrange(new Rect(new Size(350, 70)));

    var bounds = VisualTreeHelper.GetDescendantBounds(view);
    if (bounds != Rect.Empty)
    {
        height = (int)(Math.Floor(bounds.Height) + 1);
        width = (int)(Math.Floor(bounds.Width) + 1);
        size = new Size(width, height);
    }

    var bitmap = new RenderTargetBitmap((int)(width * resolution), (int)(height * resolution), dpi, dpi, PixelFormats.Pbgra32);
    var visual = new DrawingVisual();
    using (var context = visual.RenderOpen())
    {
        var brush = new VisualBrush(view);
        context.DrawRectangle(brush, null, new Rect(new Point(), bounds.Size));
    }

    bitmap.Render(visual);

    var encoder = new PngBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(bitmap));

    byte[] img;
    using (var MS = new MemoryStream())
    {
        encoder.Save(MS);
        img = MS.ToArray();
    }

    img = img == null ? new byte[0] : img;
    return img;
}

2 个答案:

答案 0 :(得分:0)

所以,我做了完全相同的事情,我有很多问题渲染文件。我发现在XAML中使用绑定到位图有帮助。我的视图模型中返回图像源的代码是:

    public Uri ImageUri
    {
        get { return new Uri(ImagePath, UriKind.Absolute); }
    }

    public BitmapImage ImageSource
    {
        get
        {
            try
            {
                if (string.IsNullOrEmpty(ImagePath) || !File.Exists(ImagePath))
                    return null;

                var image = new BitmapImage();
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.UriSource = ImageUri;
                image.EndInit();

                return image;
            }
            catch (Exception e)
            {
                var logger = LogManager.GetLogger(typeof(ImageDetails));
                ExceptionHelper.LogExceptionMessage(logger, e);
            }

            return null;
        }
    }

然后在XAML中我绑定到ImageSource属性。

我认为RenderTargetBitmap的大多数问题都与XAML中的异步绑定有关,因为render方法是同步的。

答案 1 :(得分:-1)

我刚开始遇到类似的问题。它已经工作了几年,现在我只是得到一个黑色的图像。你解决了吗?也许Windows更新打破了它。它在调试中工作正常。