简体   繁体   中英

Cannot save a Transparent PNG from my canvas in C#

I made a WPF canvas program which lets users add some PNG templates and make their own new design.

I could complete the working

However when I try to save , I get the white background Is there any way to get a transparent output ?

This is my code on saving image

public void SaveTo(string f)
    {
        Visual v = Dc;
        /// get bound of the visual
        Rect b = VisualTreeHelper.GetDescendantBounds(v);

        /// new a RenderTargetBitmap with actual size of c
        RenderTargetBitmap r = new RenderTargetBitmap(
            (int)b.Width, (int)b.Height,
            96, 96, PixelFormats.Pbgra32);

        /// render visual
        r.Render(v);

        /// new a JpegBitmapEncoder and add r into it 
        JpegBitmapEncoder e = new JpegBitmapEncoder();
        e.Frames.Add(BitmapFrame.Create(r));

        /// new a FileStream to write the image file
        FileStream s = new FileStream(f,
            FileMode.OpenOrCreate, FileAccess.Write);
        e.Save(s);
        s.Close();
    }

You are encoding to a Jpeg.

Jpegs have no transparency information (aka alpha channel).

You should use a PngBitmapEncoder .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM