简体   繁体   中英

save Image from Image-Control wpf c#

I made a QR-Code Encoder (WPF, c#) by using ZXing.net

I am displaying the QR-Code in an Image-Control

       var writer = new BarcodeWriter
        {
            Format = BarcodeFormat.QR_CODE,
            Options = new ZXing.Common.EncodingOptions
            {
                Height = 200,
                Width = 200,
                Margin = 0
            }
        };


        var image = writer.Write(qrtext.Text);
        qrImg.Source = image;

After that I want to save the image. I was using this example Save Image in a Folder .

  private void btnSaveImg_Click(object sender, RoutedEventArgs e)
    {

        string filePath = @"C:\Users\xxx\Desktop\image.png";

        SaveToPng(qrImg, filePath);
    }

    void SaveToBmp(FrameworkElement visual, string fileName)
    {
        var encoder = new BmpBitmapEncoder();
        SaveUsingEncoder(visual, fileName, encoder);
    }

    void SaveToPng(FrameworkElement visual, string fileName)
    {
        var encoder = new PngBitmapEncoder();
        SaveUsingEncoder(visual, fileName, encoder);
    }

    // and so on for other encoders (if you want)


    void SaveUsingEncoder(FrameworkElement visual, string fileName, BitmapEncoder encoder)
    {
        RenderTargetBitmap bitmap = new RenderTargetBitmap((int)visual.ActualWidth, (int)visual.ActualHeight, 96, 96, PixelFormats.Pbgra32);
        bitmap.Render(visual);
        BitmapFrame frame = BitmapFrame.Create(bitmap);
        encoder.Frames.Add(frame);

        using (var stream = File.Create(fileName))
        {
            encoder.Save(stream);
        }
    }

Unfortunately the image is not being saved. Furthermore, I get no exception. Hope you see my mistake.

Thx a lot

I found another solution, based on this post: How can I save the picture on image control in wpf?

So my solution, that works for me, is:

    String filePath = @"C:\Users\xxx\Desktop\test.jpg";

        var encoder = new PngBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create((BitmapSource)qrImg.Source));
        using (FileStream stream = new FileStream(filePath, FileMode.Create))
        encoder.Save(stream);

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