在IronQR中將QR碼保存為SVG
IronQR不會將QR碼直接匯出到SVG。 您仍然可以通過使用第三方庫將生成的位圖重新繪製為SVG矩形來生成矢量文件。
原因是底層影像堆疊。 IronQR 使用 SixLabors.ImageSharp 進行影像處理,可以處理像 PNG、JPEG 和 BMP 等光柵格式,但不提供 SVG 輸出。 SVG簡單來說不是依賴項支持的目標格式。
解決方案
像往常一樣用IronQR生成QR碼,然後遍歷其像素並使用Svg.NET將矩陣重新構建為矢量形狀。 您保留了IronQR的QR碼生成功能,並且可以完全控制SVG的樣式和結構。
1. 生成QR碼並轉換為位圖
寫入 QR 碼,將其儲存到 AnyBitmap,然後將其轉換為 System.Drawing.Bitmap,以便可以逐像素讀取。
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
2. 將像素重繪為SVG矩形
建立一個大小與位圖相同的 SvgDocument,然後迴圈遍歷像素,在像素讀取為黑色的地方新增 1x1 的 SvgRectangle。 臨界值檢查(R, G 和 B 都低於 128)將接近黑色的像素視為填充的單元格。
// 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
3. 編寫SVG文件
一旦所有黑色單元格都被新增,請將文件保存到磁碟上。
// 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")
這為您提供了可縮放的基於矢量的QR碼,適合列印或高解析度使用。

