manuelbl / qrcodegenerator Goto Github PK
View Code? Open in Web Editor NEWQR Code Generator for .NET
License: MIT License
QR Code Generator for .NET
License: MIT License
There is now a .ToSvgString() method to return the SVG text string, but WPF needs the QR Code in a Geometry Path format to be consumed by an <Image>
or <Viewbox>
control. How can I get the text string of the QR Code as a Xaml Geometry Path with this library? If it cannot be extracted currently, could you add a .ToXamlString() method? Thank you, example and link to Geometry below.
Example:
string 2DBarcodePath = qrCode.ToXamlString(3);
<Viewbox
Width="100"
Height="100"
Stretch="Uniform">
<Path x:Name="2DBarcodePath" Fill="Black" />
</Viewbox>
Hi,
Thank you for publishing this library.
When I try to run it on a simple console app, I am getting an exception System.IO.FileLoadException: Could not load file or assembly 'QrCodeGenerator, Version=1.6.0.0, Culture=neutral, PublicKeyToken=6aa6bd7a159d47c2'. The located assembly's manifest definition does not match the assembly reference.
I am using .net 6.0.401 SDK on Windows 10
mkdir QrCodeGenerator && cd QrCodeGenerator
dotnet new console
Output:
The template "Console App" was created successfully.
Processing post-creation actions...
Running 'dotnet restore' on C:\_poc\QRCodes\New folder\QrCodeGenerator\QrCodeGenerator.csproj...
Determining projects to restore...
Restored C:\_poc\QRCodes\New folder\QrCodeGenerator\QrCodeGenerator.csproj (in 74 ms).
Restore succeeded.
dotnet add package Net.Codecrete.QrCodeGenerator
Output:
Determining projects to restore...
Writing C:\Users\yanal\AppData\Local\Temp\tmpBB98.tmp
info : X.509 certificate chain validation will use the default trust store selected by .NET.
info : Adding PackageReference for package 'Net.Codecrete.QrCodeGenerator' into project 'C:\_poc\QRCodes\New folder\QrCodeGenerator\QrCodeGenerator.csproj'.
info : CACHE https://api.nuget.org/v3/registration5-gz-semver2/net.codecrete.qrcodegenerator/index.json
info : Restoring packages for C:\_poc\QRCodes\New folder\QrCodeGenerator\QrCodeGenerator.csproj...
info : Package 'Net.Codecrete.QrCodeGenerator' is compatible with all the specified frameworks in project 'C:\_poc\QRCodes\New folder\QrCodeGenerator\QrCodeGenerator.csproj'.
info : PackageReference for package 'Net.Codecrete.QrCodeGenerator' version '2.0.3' added to file 'C:\_poc\QRCodes\New folder\QrCodeGenerator\QrCodeGenerator.csproj'.
info : Writing assets file to disk. Path: C:\_poc\QRCodes\New folder\QrCodeGenerator\obj\project.assets.json
log : Restored C:\_poc\QRCodes\New folder\QrCodeGenerator\QrCodeGenerator.csproj (in 75 ms).
Update Program.cs
using System.Text;
using Net.Codecrete.QrCodeGenerator;
var qr = QrCode.EncodeText("Hello, world!", QrCode.Ecc.Medium);
string svg = qr.ToSvgString(4);
File.WriteAllText("hello-world-qr.svg", svg, Encoding.UTF8);
dotnet restore
Output:
Determining projects to restore...
All projects are up-to-date for restore.
dotnet run
Output:
Unhandled exception. System.IO.FileLoadException: Could not load file or assembly 'QrCodeGenerator, Version=1.6.0.0, Culture=neutral, PublicKeyToken=6aa6bd7a159d47c2'. The located assembly's manifest definition does not match the assembly reference. (0x80131040)
File name: 'QrCodeGenerator, Version=1.6.0.0, Culture=neutral, PublicKeyToken=6aa6bd7a159d47c2'
at Program.<Main>$(String[] args)
What am I missing ?
Wouldn't it make sense to create 3 sub packages, something like
Net.Codecrete.QrCodeGenerator.WindowsDrawing
Net.Codecrete.QrCodeGenerator.SkiaSharp
Net.Codecrete.QrCodeGenerator.ImageSharp
they could already have references to the relevant nuget packages they require.
Or is this more of a temporary solution until ImageSharp is out of beta
In the main readme.md of this repo, in section Manual operation there is Line 91:
"var segments = QrCode.MakeSegments("3141592653589793238462643383");"
I tried the example but QrCode for me has no member "MakeSegments". However if i change QrCode to QrSegment it works like a charm. Maybe a typo?
Regards Tobi
QR code that is generated as an SVG path (through invocation to QrCode.ToGraphicsPath()) is not getting rendered on the screen for some mobile phone models. Particularly when testing on my OnePlus Nord 2 this was indeed the case. It runs latest version of OxyOS (android 13). The QR code is however rendered successfully in the emulator (Pixel 5, Android 11). After debugging the code and fetching the path string that is generated when running on the phone and comparing it to the one taken from the emulator, it turned out that the issue is caused by a rather subtle circumstance. The path contains instructions in the form of Mx,yhAvBh-Az, where x, y are coordinates of the starting point of a rectangle, while A and B are respectively horizontal and vertical line lengths. The "-" sign before the last horizontal length says that the line will be drawn in the opposite direction. This character was generated on my phone as "−". I literally felt like my eyeballs would pop out of orbit when i was examining what the heck is the difference between the 2 path strings. I guess anybody would feel the same way, as there was literally no visible difference. Until VS Code compare come to rescue! Now when putting the 2 chars one next to each other it is much more obvious - "−" vs "-"! I guess this is due to locale settings. My phone is in Norwegian local, so this might be an issue with many other locales as well.
In order to fix this issue in needs to be assured that the "-" sign is char 0x2d, and not 0xe2 0x88 0x92 ("−").
Hi!
I need to show result qr-code in img html tag using base64 encoding.
e.g.
When I use options Ecc.High and Ecc.Quartile all is ok.
But when I use options Ecc.Low and Ecc.Medium image is not shown.
I explored the result base64 string and saw that it had incorrect format. At the end of the string there is only one symbol "=" (but must be "=="). And If I take away several last symbols (about 600) of the string and add "=" symbol, everything is getting ok.
Also when I save bitmap to file (.png), everything is good. Problem is only with base64 string.
May be some unnesassary bytes get to bitmap when using options Low and Medium ?
My code:
public string ToBase64(string data)
{
var qrCode = QrCode.EncodeText(data, QrCode.Ecc.Low);
using (var ms = new MemoryStream())
using (var bitmap = qrCode.ToBitmap(6, 10);)
{
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return Convert.ToBase64String(ms.GetBuffer());
}
}
Hey, not a problem or anything, but just wanted to mention that I released a small blazor component recently, which uses this library. Its for a QR code component (obviously). Plenty already exist, but all (at least all that I found) render the QR code using js, which is fine with Blazor, but not if rendering non-interactively (static SSR for example) - which was my exact scenario. I wanted to render a QR code in static SSR.
I've given options for most things I could see a benefit in, including adding a logo in the centre of the QR code (non destructively to the actual QR code itself). Repo is here if interested.
Feel free to close, just wanted to leave a note about usage, and thank you. :)
'QrCodeGenerator, Version=1.6.0.0, Culture=neutral, PublicKeyToken=6aa6bd7a159d47c2, processorArchitecture=MSIL'
at System.Reflection.RuntimeAssembly.InternalLoad(ObjectHandleOnStack assemblyName, ObjectHandleOnStack requestingAssembly, StackCrawlMarkHandle stackMark, Boolean throwOnFileNotFound, ObjectHandleOnStack assemblyLoadContext, ObjectHandleOnStack retAssembly)
at System.Reflection.RuntimeAssembly.InternalLoad(AssemblyName assemblyName, RuntimeAssembly requestingAssembly, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, AssemblyLoadContext assemblyLoadContext)
at System.Reflection.Assembly.Load(AssemblyName assemblyRef)
at System.AppDomain.Load(AssemblyName assemblyRef)
at Nop.Core.Infrastructure.AppDomainTypeFinder.LoadMatchingAssemblies(String directoryPath)
at Nop.Core.Infrastructure.WebAppTypeFinder.GetAssemblies()
at Nop.Web.Framework.Infrastructure.Extensions.ServiceCollectionExtensions.ConfigureApplicationServices(IServiceCollection services, WebApplicationBuilder builder)
at Program.
Hi, first of all thanks for this great project! 💪🏻
Is it possible to embed an image (probably a logo) in the center of the QR code image? Like QRCode Monkey's ADD LOGO IMAGE
feature. Or as discussed in this other project: codebude/QRCoder#232
I'm using the Demo-ImageSharp
sample.
Thanks!
I see some points to improve performance, for example replacing NumericRegex.IsMatch(text)
to text.All(char.IsDigit)
and similar cases. Do you plan to implement that or this just a strict port from Java version?
Not an issue per se, but trying to create a Maui Blazor Desktop app. Looking to have an SVG export option. Is this something that can be done?
Hi, How can we update the information we added to the qr code without changing the qr code. The program will generate a qr code. The content will be changed without changing the qr code. How can i do ?
Hi.
Is it possible to generate encoding in Byte format and specify the version?
The Byte generator only allows to specify the message in Byte array and the ecc correction level but not the version.
In the
Extensions file for Skia
The creation of the Bitmap doesn't allow for a transparent colour to be used for the background.
If it is replaced with the following you can use a colour that includes transparency for the background.
SKBitmap bitmap = new SKBitmap(dim, dim, SKColorType.Rgba8888, SKAlphaType.Premul);
I haven't tested for all cases, but seems to be the minimum required to get transparency.
I did also test using canvas.Clear(background)
instead of canvas.DrawRect(0, 0, dim, dim, paint);
which also seemed to work
When I add the extension functions for SixLabors.Imagesharp, I get the error on fill:
IImageProcessingContext does not contain a definition for fill.
The extension method code is below. I can't use System.Drawing() because my target is iOS and Skia had signing issues so I wanted to test SixLabors.
//
// QR code generator library (.NET)
// https://github.com/manuelbl/QrCodeGenerator
//
// Copyright (c) 2021 Manuel Bleichenbacher
// Licensed under MIT License
// https://opensource.org/licenses/MIT
//
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Extensions;
using System;
using System.IO;
using Image = SixLabors.ImageSharp.Image;
namespace Net.Codecrete.QrCodeGenerator
{
public static class QrCodeBitmapExtensions
{
/// <inheritdoc cref="ToBitmap(QrCode, int, int)"/>
/// <param name="background">The background color.</param>
/// <param name="foreground">The foreground color.</param>
public static Image ToBitmap(this QrCode qrCode, int scale, int border, SixLabors.ImageSharp.Color foreground, SixLabors.ImageSharp.Color background)
{
// check arguments
if (scale <= 0)
{
throw new ArgumentOutOfRangeException(nameof(scale), "Value out of range");
}
if (border < 0)
{
throw new ArgumentOutOfRangeException(nameof(border), "Value out of range");
}
int size = qrCode.Size;
int dim = (size + border * 2) * scale;
if (dim > short.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(scale), "Scale or border too large");
}
// create bitmap
Image<Rgb24> image = new Image<Rgb24>(dim, dim);
image.Mutate(img =>
{
// draw background
img.Fill(background);
// draw modules
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
if (qrCode.GetModule(x, y))
{
img.Fill(foreground, new Rectangle((x + border) * scale, (y + border) * scale, scale, scale));
}
}
}
});
return image;
}
/// <summary>
/// Creates a bitmap (raster image) of this QR code.
/// <para>
/// The <paramref name="scale"/> parameter specifies the scale of the image, which is
/// equivalent to the width and height of each QR code module. Additionally, the number
/// of modules to add as a border to all four sides can be specified.
/// </para>
/// <para>
/// For example, <c>ToBitmap(scale: 10, border: 4)</c> means to pad the QR code with 4 white
/// border modules on all four sides, and use 10×10 pixels to represent each module.
/// </para>
/// <para>
/// The resulting bitmap uses the pixel format <see cref="PixelFormat.Format24bppRgb"/>.
/// If not specified, the foreground color is black (0x000000) und the background color always white (0xFFFFFF).
/// </para>
/// </summary>
/// <param name="scale">The width and height, in pixels, of each module.</param>
/// <param name="border">The number of border modules to add to each of the four sides.</param>
/// <returns>The created bitmap representing this QR code.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="scale"/> is 0 or negative, <paramref name="border"/> is negative
/// or the resulting image is wider than 32,768 pixels.</exception>
public static Image ToBitmap(this QrCode qrCode, int scale, int border)
{
return qrCode.ToBitmap(scale, border, SixLabors.ImageSharp.Color.Black, SixLabors.ImageSharp.Color.White);
}
/// <inheritdoc cref="ToPng(QrCode, int, int)"/>
/// <param name="background">The background color.</param>
/// <param name="foreground">The foreground color.</param>
public static byte[] ToPng(this QrCode qrCode, int scale, int border, SixLabors.ImageSharp.Color foreground, SixLabors.ImageSharp.Color background)
{
using Image image = qrCode.ToBitmap(scale, border, foreground, background);
using MemoryStream ms = new MemoryStream();
image.SaveAsPng(ms);
return ms.ToArray();
}
/// <summary>
/// Creates a PNG image of this QR code and returns it as a byte array.
/// <para>
/// The <paramref name="scale"/> parameter specifies the scale of the image, which is
/// equivalent to the width and height of each QR code module. Additionally, the number
/// of modules to add as a border to all four sides can be specified.
/// </para>
/// <para>
/// For example, <c>ToPng(scale: 10, border: 4)</c> means to pad the QR code with 4 white
/// border modules on all four sides, and use 10×10 pixels to represent each module.
/// </para>
/// <para>
/// If not specified, the foreground color is black (0x000000) und the background color always white (0xFFFFFF).
/// </para>
/// </summary>
/// <param name="scale">The width and height, in pixels, of each module.</param>
/// <param name="border">The number of border modules to add to each of the four sides.</param>
/// <returns>The created bitmap representing this QR code.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="scale"/> is 0 or negative, <paramref name="border"/> is negative
/// or the resulting image is wider than 32,768 pixels.</exception>
public static byte[] ToPng(this QrCode qrCode, int scale, int border)
{
return qrCode.ToPng(scale, border, SixLabors.ImageSharp.Color.Black, SixLabors.ImageSharp.Color.White);
}
/// <inheritdoc cref="SaveAsPng(QrCode, string, int, int)"/>
/// <param name="background">The background color.</param>
/// <param name="foreground">The foreground color.</param>
public static void SaveAsPng(this QrCode qrCode, string filename, int scale, int border, SixLabors.ImageSharp.Color foreground, SixLabors.ImageSharp.Color background)
{
using Image image = qrCode.ToBitmap(scale, border, foreground, background);
image.SaveAsPng(filename);
}
/// <summary>
/// Saves this QR code as a PNG file.
/// <para>
/// The <paramref name="scale"/> parameter specifies the scale of the image, which is
/// equivalent to the width and height of each QR code module. Additionally, the number
/// of modules to add as a border to all four sides can be specified.
/// </para>
/// <para>
/// For example, <c>SaveAsPng("qrcode.png", scale: 10, border: 4)</c> means to pad the QR code with 4 white
/// border modules on all four sides, and use 10×10 pixels to represent each module.
/// </para>
/// <para>
/// If not specified, the foreground color is black (0x000000) und the background color always white (0xFFFFFF).
/// </para>
/// </summary>
/// <param name="scale">The width and height, in pixels, of each module.</param>
/// <param name="border">The number of border modules to add to each of the four sides.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="scale"/> is 0 or negative, <paramref name="border"/> is negative
/// or the resulting image is wider than 32,768 pixels.</exception>
public static void SaveAsPng(this QrCode qrCode, string filename, int scale, int border)
{
qrCode.SaveAsPng(filename, scale, border, SixLabors.ImageSharp.Color.Black, SixLabors.ImageSharp.Color.White);
}
}
}```
https://github.com/manuelbl/QrCodeGenerator/blob/master/Demo-ImageSharp/Program.cs
internal static void HelloWorld()
{
var text = "Hello, world!";
var filename = "hello-world-QR.png";
var qr = QrCode.EncodeText(text, QrCode.Ecc.High); // Create the QR code symbol
int border = 4;
int scale = (int)(128 * 1.0 / (qr.Size + border * 2));
qr.SaveAsPng(filename, scale, border);
Console.WriteLine($"The QR code has been saved as {Path.GetFullPath(filename)}");
}
I expect output size of the QR Code image is 128px.
But the generated size of QR Code image is 99px.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.