Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a WPF visual element as JPEG

This thing has been driving me crazy.

I have a Visiblox chart. which I'm currently exporting as a PNG using the following code:

    var chart = this.CalibrationChartVisibility == Visibility.Visible ? this.calibrationChart : this.residualChart;


    var transform = chart.LayoutTransform;
    chart.LayoutTransform = null;

    var width = (int)chart.ActualWidth;
    var height = (int)chart.ActualHeight;

    var rtb = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
    rtb.Render(chart);

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

    var stream = new MemoryStream();

    encoder.Save(stream);
    stream.Position = 0;

    chart.LayoutTransform = transform;
    return stream.ToArray();

and I get something like this: png chart

But now I need to also need to export it as a JPEG. I thought it would be simple, just change the encoder but this is what I get: jpg chart

I've tried this: http://social.msdn.microsoft.com/Forums/vstudio/en-US/31ac62d4-399b-4f2e-a9b9-749efe7528b6/rendertargetbitmap-to-file-problem?forum=wpf

and this: http://www.grumpydev.com/2009/01/03/taking-wpf-screenshots/

and this: Get a bitmap image from a Control view

and ervey sugestion on this post: How to save image using JpegBitmapEncoder

or this one: saving WPF InkCanvas to a JPG - image is getting cropped

and everything else which crossed my mind, but the outcome is still the same.

There must be something I'm overlooking but I have no idea what it is.

like image 329
memory of a dream Avatar asked Feb 12 '26 15:02

memory of a dream


1 Answers

To sum up comments this seems to be a background issue as PNG, attached to this question, has everything transparent apart from chart lines and since JPEG does not support transparency all that is transparent will be black.

Simpliest solution would be to set background of chart to some color

like image 114
dkozl Avatar answered Feb 15 '26 18:02

dkozl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!