Salvando Códigos QR como SVG no IronQR

This article was translated from English: Does it need improvement?
Translated
View the article in English

A IronQR não exporta códigos QR diretamente para SVG. Você ainda pode produzir um arquivo vetorial redesenhando o bitmap gerado como retângulos SVG com uma biblioteca de terceiros.

A razão é a pilha de imagens subjacente. A IronQR usa SixLabors.ImageSharp para processamento de imagens, que lida com formatos raster como PNG, JPEG e BMP, mas não oferece saída SVG. SVG simplesmente não é um formato alvo suportado pela dependência.

Solução

Gere o código QR com a IronQR como de costume, depois percorra seus pixels e reconstrua a matriz como formas vetoriais usando Svg.NET. Você mantém a geração de QR da IronQR e ganha controle total sobre o estilo e a estrutura do SVG.

1. Gera o Código QR e Converte para um Bitmap

Escreva o código QR, salve-o em um AnyBitmap, depois converta isso para um System.Drawing.Bitmap para que os pixels possam ser lidos individualmente.

var qr = QrWriter.Write("Hello SVG");
var anyBitmap = qr.Save();
// Convert AnyBitmap to System.Drawing.Bitmap
System.Drawing.Bitmap bit = anyBitmap;
var qr = QrWriter.Write("Hello SVG");
var anyBitmap = qr.Save();
// Convert AnyBitmap to System.Drawing.Bitmap
System.Drawing.Bitmap bit = anyBitmap;
Dim qr = QrWriter.Write("Hello SVG")
Dim anyBitmap = qr.Save()
' Convert AnyBitmap to System.Drawing.Bitmap
Dim bit As System.Drawing.Bitmap = anyBitmap
$vbLabelText   $csharpLabel

2. Redesenhe os pixels como retângulos SVG

Crie um SvgDocument dimensionado para o bitmap, depois percorra os pixels e adicione um SvgRectangle de 1x1 onde um pixel é lido como preto. A verificação de nível (R, G, e B todos abaixo de 128) trata pixels quase pretos como células preenchidas.

// Create new SVG document
var svgDoc = new SvgDocument
{
    Width = bit.Width,
    Height = bit.Height
};
// Loop through bitmap pixels and add black pixels as SVG rectangles
for (int y = 0; y < bit.Height; y++)
{
    for (int x = 0; x < bit.Width; x++)
    {
        System.Drawing.Color pixel = bit.GetPixel(x, y);
        // Check if pixel is black (or close enough)
        if (pixel.R < 128 && pixel.G < 128 && pixel.B < 128)
        {
            var rect = new SvgRectangle
            {
                X = x,
                Y = y,
                Width = 1,
                Height = 1,
                Fill = new SvgColourServer(System.Drawing.Color.Black)
            };
            svgDoc.Children.Add(rect);
        }
    }
}
// Create new SVG document
var svgDoc = new SvgDocument
{
    Width = bit.Width,
    Height = bit.Height
};
// Loop through bitmap pixels and add black pixels as SVG rectangles
for (int y = 0; y < bit.Height; y++)
{
    for (int x = 0; x < bit.Width; x++)
    {
        System.Drawing.Color pixel = bit.GetPixel(x, y);
        // Check if pixel is black (or close enough)
        if (pixel.R < 128 && pixel.G < 128 && pixel.B < 128)
        {
            var rect = new SvgRectangle
            {
                X = x,
                Y = y,
                Width = 1,
                Height = 1,
                Fill = new SvgColourServer(System.Drawing.Color.Black)
            };
            svgDoc.Children.Add(rect);
        }
    }
}
Imports System.Drawing

' Create new SVG document
Dim svgDoc As New SvgDocument With {
    .Width = bit.Width,
    .Height = bit.Height
}

' Loop through bitmap pixels and add black pixels as SVG rectangles
For y As Integer = 0 To bit.Height - 1
    For x As Integer = 0 To bit.Width - 1
        Dim pixel As Color = bit.GetPixel(x, y)
        ' Check if pixel is black (or close enough)
        If pixel.R < 128 AndAlso pixel.G < 128 AndAlso pixel.B < 128 Then
            Dim rect As New SvgRectangle With {
                .X = x,
                .Y = y,
                .Width = 1,
                .Height = 1,
                .Fill = New SvgColourServer(Color.Black)
            }
            svgDoc.Children.Add(rect)
        End If
    Next
Next
$vbLabelText   $csharpLabel

3. Escreva o arquivo SVG

Salve o documento no disco assim que cada célula preta tiver sido adicionada.

// Save the result as SVG
svgDoc.Write("qr-from-ironqr.svg");
// Save the result as SVG
svgDoc.Write("qr-from-ironqr.svg");
' Save the result as SVG
svgDoc.Write("qr-from-ironqr.svg")
$vbLabelText   $csharpLabel

Isso proporciona um código QR escalável, baseado em vetor, adequado para impressão ou uso de alta resolução.

Curtis Chau
Redator Técnico

Curtis Chau é bacharel em Ciência da Computação (Universidade Carleton) e se especializa em desenvolvimento front-end, com experiência em Node.js, TypeScript, JavaScript e React. Apaixonado por criar interfaces de usuário intuitivas e esteticamente agradáveis, Curtis gosta de trabalhar com frameworks modernos e criar manuais ...

Leia mais
Pronto para começar?
Nuget Baixar 70,398 | Versão: 2026.7 recém-lançado
Still Scrolling Icon

Ainda está rolando a tela?

Quer provas rápidas? PM > Install-Package IronQR
executar um exemplo Veja seu URL se transformar em um código QR.