Работа с qr-кодами

Создание QR-кода из текста

XAML

<Image x:Name="QrI" />
<TextBox x:Name="QrText" />
      

C#

var encoder = new QRCodeEncoder();
Bitmap bitmap = encoder.Encode(QrText.Text);

using (MemoryStream ms = new MemoryStream())
{
    bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
    ms.Position = 0;

    var bitmapImage = new BitmapImage();
    bitmapImage.BeginInit();
    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
    bitmapImage.StreamSource = ms;
    bitmapImage.EndInit();

    QrI.Source = bitmapImage;
}
      

Получение текста из QR-кода

C#

var dialog = new OpenFileDialog() { Filter = "*.png; | *.png;" };
if (dialog.ShowDialog().GetValueOrDefault())
{
    var imageBytes = File.ReadAllBytes(dialog.FileName);
    using (MemoryStream ms = new MemoryStream(imageBytes))
    {
        var bitmapImage = new BitmapImage();
        bitmapImage.BeginInit();
        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.StreamSource = ms;
        bitmapImage.EndInit();

        QrI.Source = bitmapImage;

        using (MemoryStream mss = new MemoryStream(imageBytes))
        {
            var decoder = new QRCodeDecoder();
            Bitmap bitmap = new Bitmap(mss);
            QrText.Text = decoder.Decode(new QRCodeBitmapImage(bitmap));
        }
    }
}
      

Скачивание QR-кода

C#

var dialog = new SaveFileDialog() { Filter = "*.png; | *.png;" };
if (dialog.ShowDialog().GetValueOrDefault())
{
    var file = File.Create(dialog.FileName);
    file.Close();

    var encoder = new JpegBitmapEncoder();
    var bitmapSource = (BitmapSource)QrI.Source;
    encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
    using (MemoryStream ms = new MemoryStream())
    {
        encoder.Save(ms);
        File.WriteAllBytes(dialog.FileName, ms.ToArray());
    }
}