Reputation: 1281
Hello I want to make a image of QR code using QRCodeWriter class . Yes I can create Bar code Image using BarcodeWriter But I need to create Using QR code Writter Class I found a solution but that is very old in stackoverflow in here QRCodeWritter Creating QR Code but here is a problem and the problem is
if (matrix.get_Renamed(x, y) == -1)
There is no method getrenamed I tried this but failed here is the method I got
Please Note that this matrix is BitMatrix matrix from ZXing.Common.BitMatrix . How to create and solve this thanks in advance .
Upvotes: 1
Views: 527
Reputation: 9438
With a [WPF] tag specifically, using ZXing.QrCode.QRCodeWriter()
, the question is how to create a QRCode image . I had the same question when I got here, and have been finding it surprisingly difficult to find a straightforward answer to this in the "latest" ZXing version: <PackageReference Include="ZXing.Net" Version="0.16.9" />
in 2025.
So I muddled through it on my own and here's what worked for me:
private static ImageSource GenerateQRCode(string qrText)
{
var bitMatrix =
new QRCodeWriter()
.encode(qrText, BarcodeFormat.QR_CODE, 150, 150);
int width = bitMatrix.Width;
int height = bitMatrix.Height;
int stride = (width + 7) / 8;
byte[] pixels = new byte[width * height];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
pixels[y * width + x] = bitMatrix[x, y] ? (byte)0 : (byte)255;
}
}
BitmapSource bitmapSource = BitmapSource.Create(
width,
height,
96,
96,
PixelFormats.Gray8,
null,
pixels,
width
);
return bitmapSource;
}
Usage
As a point of reference, my WPF view model has this singleton:
partial class UniqueNumberItem : ObservableObject
{
public ImageSource QRCode
{
get
{
if (qrCode is null)
{
qrCode = GenerateQRCode(UniqueNumber);
}
return qrCode;
}
}
ImageSource? qrCode = default;
.
.
.
}
Binding
It is bound in this manner:
<DataTemplate x:Key="PrintTemplate">
<Border
BorderThickness="2"
BorderBrush="Black"
CornerRadius="10"
Padding="10"
Margin="10">
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Image Source="{Binding QRCode}"
Width="150" Height="150"
HorizontalAlignment="Center"
Grid.Row="0" />
<TextBlock Text="{Binding WNR}"
FontSize="16"
HorizontalAlignment="Center"
Grid.Row="1"/>
<TextBlock Text="{Binding UniqueNumber}"
FontSize="16"
FontWeight="Bold"
HorizontalAlignment="Center"
Grid.Row="2"/>
<TextBlock Text="{Binding Matnr}"
FontSize="16"
FontStyle="Italic"
HorizontalAlignment="Center"
Grid.Row="3"/>
</Grid>
</Border>
</DataTemplate>
Upvotes: 0