4

In a C#/WPF application, I have a DataChart object that I need to save to an image. Currently, the object is added to a Fixed Document and correctly displays on that Fixed Document by using the following code:

VisualBrush chartBrush = new VisualBrush(chart);
Rectangle chartRect = new Rectangle();
chartRect.Height = chartClone.Height;
chartRect.Width = chartClone.Width;
chartRect.Fill = chartBrush;
AddBlockUIElement(chartRect, textAlignment);

However, rather than add it as a block to a Fixed Document, I now need to simply save the image to disk. I've tried doing the following:

RenderTargetBitmap bmp = new RenderTargetBitmap((int)chart.Width, (int)chart.Height, 96, 96, PixelFormats.Default);
bmp.Render(chart);
PngBitmapEncoder image = new PngBitmapEncoder();
image.Frames.Add(BitmapFrame.Create(bmp));
using (Stream fs = File.Create("TestImage.png"))
{
  image.Save(fs);
  fs.Close();
}

However, this simply gives me a solid black image in the size of my chart and I cannot figure out why.

So my question is, does anyone know of a better way to turn the DataChart object into a PNG or BMP image I can save? I've tried searching on getting from a VisualBrush or a Rectangle to an image, but haven't found anything, other than the above, that seems to do what I need.

Thanks so much!

JToland
  • 3,630
  • 12
  • 49
  • 70
  • 1
    The bad news is I'm pretty sure this is a driver/graphics card issue, as it should work. Try updating your driver or try your code on a different computer (or a different OS). Still working on some good news :) – Blindy Jun 01 '11 at 17:43

2 Answers2

-1

See if you can work with the code below:

VisualBrush target = new VisualBrush(element);
DrawingVisual visual = new DrawingVisual();
DrawingContext dc = visual.RenderOpen();
dc.DrawRectangle(target, null, new Rect(0, 0, 
    width, 
    height));
dc.Close();

RenderTargetBitmap bmp = new RenderTargetBitmap(
    (int)width,
    (int)height, 96, 96, PixelFormats.Pbgra32);
bmp.Render(visual); 
tofutim
  • 22,664
  • 20
  • 87
  • 148
-1

replace this line

image.Frames.Add(BitmapFrame.Create(BitmapRender));

with such

image.Frames.Add(BitmapFrame.Create(bmp));
Eugen
  • 2,934
  • 2
  • 26
  • 47
  • I'm sorry, that was a typo actually -- I already had it that way it just got changed when I was asking the question. Thanks for the catch though! – JToland Jun 01 '11 at 17:13
  • I'm using such a code http://pastebin.com/up3JGuFw in my project and it works just perfect. – Eugen Jun 01 '11 at 18:43