diff --git a/QRCoder.Core/Abstractions/AbstractQRCode.cs b/QRCoder.Core/Abstractions/AbstractQRCode.cs index 93c2185..1ab1a95 100644 --- a/QRCoder.Core/Abstractions/AbstractQRCode.cs +++ b/QRCoder.Core/Abstractions/AbstractQRCode.cs @@ -5,17 +5,18 @@ namespace QRCoder.Core.Abstractions using QRCoder.Core.Models; /// - /// AbstractQRCode + /// Abstract base class for all QR code renderers. Provides shared lifecycle management + /// and access to the underlying used for rendering. /// public abstract class AbstractQRCode : IDisposable { /// - /// QRCodeData + /// The QR code data used for rendering. Contains the module matrix that defines the QR code pattern. /// protected QRCodeData QrCodeData { get; set; } /// - /// AbstractQRCode + /// Initializes a new instance of the renderer and sets a process-wide regex timeout of 500ms. /// protected AbstractQRCode() { @@ -27,9 +28,9 @@ protected AbstractQRCode() } /// - /// AbstractQRCode + /// Initializes a new instance of the renderer with the specified QR code data. /// - /// + /// The generated by . protected AbstractQRCode(QRCodeData data) : this() { this.QrCodeData = data; diff --git a/QRCoder.Core/Assets/nuget-readme.md b/QRCoder.Core/Assets/nuget-readme.md index f5cce94..9c617f0 100644 --- a/QRCoder.Core/Assets/nuget-readme.md +++ b/QRCoder.Core/Assets/nuget-readme.md @@ -1,42 +1,113 @@ -## About +# QRCoder.Core -QRCoder.Core is a simple library, written in C#.NET, based on [QrCode](https://github.com/codebude/QRCoder) which enables you to create QR codes. It is available as a .NET Core version on NuGet. It uses SkiaSharp for cross-platform compatibility. +A cross-platform .NET library for QR Code generation using **SkiaSharp**. Compatible with **Windows**, **Linux**, **macOS**, and **mobile** (Xamarin / MAUI). +Based on [QRCoder](https://github.com/codebude/QRCoder). Supports **.NET Standard 2.1**, **.NET 8.0**, **.NET 10.0**, and **.NET Framework 4.8**. -*** +--- -## Documentation +## Quick Start -👉 *Your first place to go should be our wiki. Here you can find a detailed documentation of the QRCoder and its functions.* -* [**QRCode Wiki**](https://github.com/codebude/QRCoder/wiki) or [**QRCode.Core Wiki**](https://github.com/afonsoft/QRCoder.Core/wiki) +```csharp +using QRCoder.Core; + +// Generate QR code data +using var generator = new QRCodeGenerator(); +using var data = generator.CreateQrCode("https://github.com/afonsoft/QRCoder.Core", + QRCodeGenerator.ECCLevel.M); + +// Render as PNG bytes (cross-platform, no System.Drawing needed) +using var png = new PngByteQRCode(data); +byte[] pngBytes = png.GetGraphic(10); +File.WriteAllBytes("qrcode.png", pngBytes); +``` + +## Output Formats -## Usage / Quick start +| Format | Class | Example | +|--------|-------|---------| +| **PNG** | `PngByteQRCode` | `new PngByteQRCode(data).GetGraphic(10)` → `byte[]` | +| **SVG** | `SvgQRCode` | `new SvgQRCode(data).GetGraphic(10)` → `string` | +| **PDF** | `PdfByteQRCode` | `new PdfByteQRCode(data).GetGraphic(5)` → `byte[]` | +| **ASCII** | `ASCIIQRCode` | `new ASCIIQRCode(data).GetGraphic(1)` → `string` | +| **Base64** | `Base64QRCode` | `new Base64QRCode(data).GetGraphic(10)` → `string` | +| **SKBitmap** | `QRCode` | `new QRCode(data).GetGraphic(10)` → `SKBitmap` | +| **Postscript** | `PostscriptQRCode` | `new PostscriptQRCode(data).GetGraphic(5)` → `string` | +| **Artistic** | `ArtQRCode` | `new ArtQRCode(data).GetGraphic(10)` → `SKBitmap` | +| **BMP** | `BitmapByteQRCode` | `new BitmapByteQRCode(data).GetGraphic(10)` → `byte[]` | -You only need four lines of code, to generate and view your first QR code. +## Multiple Formats Example ```csharp -using (QRCodeGenerator qrGenerator = new QRCodeGenerator()) -using (QRCodeData qrCodeData = qrGenerator.CreateQrCode("The text which should be encoded.", QRCodeGenerator.ECCLevel.Q)) -using (QRCode qrCode = new QRCode(qrCodeData)) -{ - Bitmap qrCodeImage = qrCode.GetGraphic(20); -} +using QRCoder.Core; + +using var gen = new QRCodeGenerator(); +using var data = gen.CreateQrCode("Hello World", QRCodeGenerator.ECCLevel.M); + +// SVG +using var svg = new SvgQRCode(data); +string svgString = svg.GetGraphic(10); + +// ASCII (terminal) +using var ascii = new ASCIIQRCode(data); +Console.WriteLine(ascii.GetGraphic(1)); + +// PDF +using var pdf = new PdfByteQRCode(data); +byte[] pdfBytes = pdf.GetGraphic(5); + +// With custom colors +using var qr = new QRCode(data); +using var bitmap = qr.GetGraphic(10, "#1a1a2e", "#e0e0e0"); ``` -### Optional parameters and overloads +## Payload Types -The GetGraphics-method has some more overloads. The first two enable you to set the color of the QR code graphic. One uses Color-class-types, the other HTML hex color notation. +Generate formatted QR code content for common use cases: ```csharp -//Set color by using Color-class types -Bitmap qrCodeImage = qrCode.GetGraphic(20, Color.DarkRed, Color.PaleGreen, true); +using QRCoder.Core; -//Set color by using HTML hex color notation -Bitmap qrCodeImage = qrCode.GetGraphic(20, "#000ff0", "#0ff000"); +using var gen = new QRCodeGenerator(); + +// Wi-Fi +var wifi = new PayloadGenerator.WiFi("MyNetwork", "MyPassword", + PayloadGenerator.WiFi.Authentication.WPA); +using var wifiData = gen.CreateQrCode(wifi.ToString(), QRCodeGenerator.ECCLevel.M); + +// URL +var url = new PayloadGenerator.Url("https://github.com/afonsoft/QRCoder.Core"); +using var urlData = gen.CreateQrCode(url.ToString(), QRCodeGenerator.ECCLevel.M); + +// Email +var mail = new PayloadGenerator.Mail("test@example.com", "Subject", "Body"); +using var mailData = gen.CreateQrCode(mail.ToString(), QRCodeGenerator.ECCLevel.M); + +// Phone Number +var phone = new PayloadGenerator.PhoneNumber("+1234567890"); +using var phoneData = gen.CreateQrCode(phone.ToString(), QRCodeGenerator.ECCLevel.M); + +// Contact Card (vCard) +var contact = new PayloadGenerator.ContactData( + PayloadGenerator.ContactData.ContactOutputType.VCard3, + "Doe", "John", phone: "+1234567890", email: "john@example.com"); +using var contactData = gen.CreateQrCode(contact.ToString(), QRCodeGenerator.ECCLevel.M); ``` -The other overload enables you to render a logo/image in the center of the QR code. +Supported payloads: URL, WiFi, Mail, SMS, PhoneNumber, MMS, Geolocation, CalendarEvent, ContactData, Bitcoin, Girocode, BezahlCode, SwissQrCode, OneTimePassword, ShadowSocksConfig, Bookmark, SkypeCall, WhatsAppMessage, and more. -```csharp -Bitmap qrCodeImage = qrCode.GetGraphic(20, Color.Black, Color.White, (Bitmap)Bitmap.FromFile("C:\\myimage.png")); -``` \ No newline at end of file +## Error Correction Levels + +| Level | Recovery | Use Case | +|-------|----------|----------| +| `ECCLevel.L` | ~7% | Maximum data capacity | +| `ECCLevel.M` | ~15% | General purpose (recommended) | +| `ECCLevel.Q` | ~25% | Higher reliability | +| `ECCLevel.H` | ~30% | Maximum recovery (logos, artistic QR) | + +## Documentation & Source + +- **Repository**: [https://github.com/afonsoft/QRCoder.Core](https://github.com/afonsoft/QRCoder.Core) +- **Usage Guide**: [https://github.com/afonsoft/QRCoder.Core/blob/main/docs/en-US/usage-guide.md](https://github.com/afonsoft/QRCoder.Core/blob/main/docs/en-US/usage-guide.md) +- **Issues**: [https://github.com/afonsoft/QRCoder.Core/issues](https://github.com/afonsoft/QRCoder.Core/issues) +- **License**: MIT diff --git a/QRCoder.Core/Exceptions/DataTooLongException.cs b/QRCoder.Core/Exceptions/DataTooLongException.cs index f786f1d..5147ecc 100644 --- a/QRCoder.Core/Exceptions/DataTooLongException.cs +++ b/QRCoder.Core/Exceptions/DataTooLongException.cs @@ -3,7 +3,8 @@ namespace QRCoder.Core.Exceptions { /// - /// DataTooLongException + /// Thrown when the input data exceeds the maximum capacity allowed by the QR code standard + /// for the specified error correction level, encoding mode, and optional fixed version. /// public class DataTooLongException : Exception { diff --git a/QRCoder.Core/Extensions/SKColorExtensions.cs b/QRCoder.Core/Extensions/SKColorExtensions.cs index b907aad..67462f4 100644 --- a/QRCoder.Core/Extensions/SKColorExtensions.cs +++ b/QRCoder.Core/Extensions/SKColorExtensions.cs @@ -3,13 +3,23 @@ namespace QRCoder.Core.Extensions { + /// + /// Extension methods for converting values to and from hexadecimal string notation. + /// public static class SKColorExtensions { + /// + /// Converts this color to an ARGB hexadecimal string (e.g., "#FF000000" for opaque black). + /// public static string ToHex(this SKColor color) { return string.Format(CultureInfo.InvariantCulture, "#{0:X2}{1:X2}{2:X2}{3:X2}", color.Alpha, color.Red, color.Green, color.Blue); } + /// + /// Parses a hexadecimal color string (#RRGGBB or #AARRGGBB) into an . + /// Returns for null, empty, or invalid input. + /// public static SKColor FromHex(string hex) { if (string.IsNullOrEmpty(hex)) diff --git a/QRCoder.Core/Extensions/StringValueAttribute.cs b/QRCoder.Core/Extensions/StringValueAttribute.cs index 4dbaf6e..8e294e8 100644 --- a/QRCoder.Core/Extensions/StringValueAttribute.cs +++ b/QRCoder.Core/Extensions/StringValueAttribute.cs @@ -10,7 +10,7 @@ public class StringValueAttribute : Attribute #region Properties /// - /// Holds the alue in an enum + /// Holds the string value associated with the enum member. /// public string StringValue { get; protected set; } @@ -27,7 +27,7 @@ public StringValueAttribute(string value) } /// - /// CustomExtensions + /// Extension methods for retrieving values from enum members. /// public static class CustomExtensions { diff --git a/QRCoder.Core/Models/QRCodeData.cs b/QRCoder.Core/Models/QRCodeData.cs index 840f238..0e05ae2 100644 --- a/QRCoder.Core/Models/QRCodeData.cs +++ b/QRCoder.Core/Models/QRCodeData.cs @@ -6,12 +6,15 @@ namespace QRCoder.Core.Models { /// - /// QRCodeData + /// Stores the encoded QR code data as a module matrix. Each element in the matrix represents + /// a row of modules (black/white squares). Generated by + /// and consumed by renderer classes to produce visual output. /// public class QRCodeData : IDisposable { /// - /// Module Matrix + /// The module matrix representing the QR code. Each is a row, + /// where true = dark module and false = light module. /// public List ModuleMatrix { get; set; } @@ -25,20 +28,20 @@ public QRCodeData(int version) } /// - /// QRCodeData + /// Loads QR code data from a file in the proprietary QRR format. /// - /// pathToRawData - /// compressMode + /// Path to the QRR file containing saved QR code data. + /// Compression mode used when the file was saved. public QRCodeData(string pathToRawData, Compression compressMode) : this(File.ReadAllBytes(pathToRawData), compressMode) { } /// - /// QRCodeData + /// Loads QR code data from a byte array in the proprietary QRR format. /// - /// rawData - /// compressMode - /// Exception + /// Byte array containing saved QR code data in QRR format. + /// Compression mode used when the data was saved. + /// Thrown when the raw data does not match the QRR file format. public QRCodeData(byte[] rawData, Compression compressMode) { var bytes = new List(rawData); @@ -105,10 +108,11 @@ public QRCodeData(byte[] rawData, Compression compressMode) } /// - /// GetRawData + /// Serializes the QR code data into a byte array in the proprietary QRR format, + /// with optional Deflate or GZip compression. /// - /// compressMode - /// + /// The compression algorithm to apply to the output. + /// A byte array containing the QR code data in QRR format. public byte[] GetRawData(Compression compressMode) { var bytes = new List(); @@ -172,10 +176,10 @@ public byte[] GetRawData(Compression compressMode) } /// - /// SaveRawData + /// Saves the QR code data to a file in the proprietary QRR format. /// - /// filePath - /// compressMode + /// The path where the QRR file will be written. + /// The compression algorithm to apply. public void SaveRawData(string filePath, Compression compressMode) { File.WriteAllBytes(filePath, GetRawData(compressMode)); @@ -216,7 +220,7 @@ protected virtual void Dispose(bool disposing) } /// - /// Compression + /// Specifies the compression algorithm used when saving or loading QR code data. /// public enum Compression { diff --git a/QRCoder.Core/Models/Size.cs b/QRCoder.Core/Models/Size.cs index 28819a6..0aff709 100644 --- a/QRCoder.Core/Models/Size.cs +++ b/QRCoder.Core/Models/Size.cs @@ -1,8 +1,18 @@ namespace QRCoder.Core.Models { + /// + /// Represents the dimensions (width and height) of a QR code rendering area. + /// public struct Size { + /// + /// The width of the rendering area in the target unit (pixels, points, etc.). + /// public double Width { get; set; } + + /// + /// The height of the rendering area in the target unit (pixels, points, etc.). + /// public double Height { get; set; } public Size(double width, double height) diff --git a/QRCoder.Core/Renderers/ArtQRCode.cs b/QRCoder.Core/Renderers/ArtQRCode.cs index 7387ef9..357e7c7 100644 --- a/QRCoder.Core/Renderers/ArtQRCode.cs +++ b/QRCoder.Core/Renderers/ArtQRCode.cs @@ -10,7 +10,8 @@ namespace QRCoder.Core.Renderers { /// - /// ArtQRCode + /// Renders a QR code with artistic styling using rounded dots instead of square modules. + /// Supports custom dot colors, background images, and quiet zone control. /// public class ArtQRCode : AbstractQRCode { diff --git a/QRCoder.Core/Renderers/AsciiQRCode.cs b/QRCoder.Core/Renderers/AsciiQRCode.cs index e8a4885..f012277 100644 --- a/QRCoder.Core/Renderers/AsciiQRCode.cs +++ b/QRCoder.Core/Renderers/AsciiQRCode.cs @@ -9,7 +9,8 @@ namespace QRCoder.Core.Renderers { /// - /// AsciiQRCode + /// Renders a QR code as ASCII art text, suitable for terminal/console output. + /// Each module is represented by configurable dark and light character strings. /// public class AsciiQRCode : AbstractQRCode { diff --git a/QRCoder.Core/Renderers/Base64QRCode.cs b/QRCoder.Core/Renderers/Base64QRCode.cs index 2c774f0..5ed80b8 100644 --- a/QRCoder.Core/Renderers/Base64QRCode.cs +++ b/QRCoder.Core/Renderers/Base64QRCode.cs @@ -12,7 +12,8 @@ namespace QRCoder.Core.Renderers { /// - /// Base64QRCode + /// Renders a QR code as a Base64-encoded image string. Useful for embedding QR codes + /// directly in HTML img tags or CSS without requiring a separate file. /// public class Base64QRCode : AbstractQRCode { diff --git a/QRCoder.Core/Renderers/BitmapByteQRCode.cs b/QRCoder.Core/Renderers/BitmapByteQRCode.cs index 88117d8..7ce705b 100644 --- a/QRCoder.Core/Renderers/BitmapByteQRCode.cs +++ b/QRCoder.Core/Renderers/BitmapByteQRCode.cs @@ -9,7 +9,8 @@ namespace QRCoder.Core.Renderers { /// - /// SKBitmapByteQRCode + /// Renders a QR code as a raw BMP (bitmap) byte array. Produces an uncompressed + /// 24-bit color bitmap image suitable for further processing or display. /// // ReSharper disable once InconsistentNaming public class SKBitmapByteQRCode : AbstractQRCode diff --git a/QRCoder.Core/Renderers/PdfByteQRCode.cs b/QRCoder.Core/Renderers/PdfByteQRCode.cs index b4744bb..66ed926 100644 --- a/QRCoder.Core/Renderers/PdfByteQRCode.cs +++ b/QRCoder.Core/Renderers/PdfByteQRCode.cs @@ -15,7 +15,8 @@ namespace QRCoder.Core.Renderers { /// - /// PdfByteQRCode + /// Renders a QR code as a PDF document byte array. Generates a minimal valid PDF + /// containing the QR code image with configurable colors and quiet zone. /// // ReSharper disable once InconsistentNaming public class PdfByteQRCode : AbstractQRCode diff --git a/QRCoder.Core/Renderers/PngByteQRCode.cs b/QRCoder.Core/Renderers/PngByteQRCode.cs index 59eaedb..c8e9552 100644 --- a/QRCoder.Core/Renderers/PngByteQRCode.cs +++ b/QRCoder.Core/Renderers/PngByteQRCode.cs @@ -9,7 +9,8 @@ namespace QRCoder.Core.Renderers { /// - /// PngByteQRCode + /// Renders a QR code as a PNG image byte array. This renderer does not require System.Drawing + /// and works cross-platform on Windows, Linux, macOS, and mobile. /// public sealed class PngByteQRCode : AbstractQRCode { diff --git a/QRCoder.Core/Renderers/PostscriptQRCode.cs b/QRCoder.Core/Renderers/PostscriptQRCode.cs index 1a5d2ab..0067af9 100644 --- a/QRCoder.Core/Renderers/PostscriptQRCode.cs +++ b/QRCoder.Core/Renderers/PostscriptQRCode.cs @@ -9,7 +9,8 @@ namespace QRCoder.Core.Renderers { /// - /// PostscriptQRCode + /// Renders a QR code as a Postscript or EPS (Encapsulated PostScript) string. + /// Suitable for high-quality print output and vector graphics workflows. /// public class PostscriptQRCode : AbstractQRCode { diff --git a/QRCoder.Core/Renderers/SvgQRCode.cs b/QRCoder.Core/Renderers/SvgQRCode.cs index 0899df4..1308b9e 100644 --- a/QRCoder.Core/Renderers/SvgQRCode.cs +++ b/QRCoder.Core/Renderers/SvgQRCode.cs @@ -12,7 +12,8 @@ namespace QRCoder.Core.Renderers { /// - /// SvgQRCode + /// Renders a QR code as an SVG (Scalable Vector Graphics) string. Supports custom colors, + /// sizing modes, quiet zones, and optional embedded logos (bitmap or SVG). /// public class SvgQRCode : AbstractQRCode { diff --git a/README.md b/README.md index 946d9e6..c12c1d4 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,3 @@ - # QRCoder.Core - QR Code Generator Library [![Build status](https://github.com/afonsoft/QRCoder.Core/actions/workflows/build-and-pack.yml/badge.svg?branch=main)](https://github.com/afonsoft/QRCoder.Core/actions/workflows/build-and-pack.yml) @@ -7,10 +6,59 @@ [![Code Quality](https://sonarcloud.io/api/project_badges/measure?project=QrCode.Core&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=QrCode.Core) [![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=QrCode.Core&metric=security_rating)](https://sonarcloud.io/summary/new_code?id=QrCode.Core) -## Documentation / Documentação +> **[Leia em Portugues (pt-BR)](README.pt-br.md)** + +## Documentation -- **[Usage Guide (English)](docs/en-US/usage-guide.md)** -- **[Guia de Uso (Português)](docs/pt-BR/guia-de-uso.md)** +- **[Usage Guide (English)](docs/en-US/usage-guide.md)** — PNG, SVG, PDF, ASCII, Base64, Postscript, Artistic QR Codes +- **[Guia de Uso (Portugues)](docs/pt-BR/guia-de-uso.md)** — PNG, SVG, PDF, ASCII, Base64, Postscript, QR Codes Artisticos + +## Project Description + +QRCoder.Core is a cross-platform .NET library for QR Code generation using **SkiaSharp** for image rendering. Compatible with **Windows**, **Linux**, **macOS**, and **mobile** (Xamarin / MAUI). + +Based on [QRCoder](https://github.com/codebude/QRCoder). Developed and maintained by [AFONSOFT](https://github.com/afonsoft). + +### Supported Output Formats + +| Format | Class | Description | +|--------|-------|-------------| +| **SKBitmap** | `QRCode` | SkiaSharp bitmap image (cross-platform) | +| **PNG** | `PngByteQRCode` | PNG byte array (no System.Drawing needed) | +| **SVG** | `SvgQRCode` | Scalable vector graphics string | +| **PDF** | `PdfByteQRCode` | PDF document as byte array | +| **ASCII** | `ASCIIQRCode` | ASCII art for terminal output | +| **Base64** | `Base64QRCode` | Base64-encoded image string | +| **Postscript** | `PostscriptQRCode` | Postscript/EPS format | +| **Artistic** | `ArtQRCode` | Custom QR with rounded dots and backgrounds | +| **BMP Bytes** | `BitmapByteQRCode` | Bitmap byte array | + +### Supported Payload Types + +The `PayloadGenerator` class provides formatted strings for common QR code use cases: + +| Payload | Description | +|---------|-------------| +| `Url` | Website URL | +| `WiFi` | Wi-Fi network credentials | +| `Mail` | Email with subject and body | +| `SMS` | SMS message | +| `PhoneNumber` | Phone number | +| `MMS` | Multimedia message | +| `Geolocation` | GPS coordinates | +| `CalendarEvent` | Calendar event (iCal/vEvent) | +| `ContactData` | vCard / MeCard contact | +| `BitcoinLikeCryptoCurrencyAddress` | Bitcoin/crypto payment | +| `Girocode` | European SEPA payment | +| `BezahlCode` | German payment standard | +| `SwissQrCode` | Swiss QR-bill payment | +| `OneTimePassword` | TOTP/HOTP for 2FA | +| `ShadowSocksConfig` | ShadowSocks proxy config | +| `Bookmark` | Browser bookmark | +| `SkypeCall` | Skype call link | +| `WhatsAppMessage` | WhatsApp message | +| `RussiaPaymentOrder` | Russian payment order | +| `SlovenianUpnQr` | Slovenian UPN QR payment | ## Test Coverage @@ -21,97 +69,48 @@ | **Method Coverage** | 78%+ | Good | | **Total Tests** | 300+ | All Passed | -## Descrição do Projeto / Project Description - -QRCoder.Core is a cross-platform .NET library for QR Code generation using **SkiaSharp** for image rendering. Compatible with **Windows**, **Linux**, **macOS**, and **mobile** (Xamarin / MAUI). +## Project Status -QRCoder.Core é uma biblioteca .NET multiplataforma para geração de QR Codes usando **SkiaSharp** para renderização de imagens. Compatível com **Windows**, **Linux**, **macOS** e **mobile** (Xamarin / MAUI). +**Complete** - Actively maintained with modern CI/CD pipelines. -Based on [QRCoder](https://github.com/codebude/QRCoder). Developed and maintained by AFONSOFT. +## Prerequisites -## Status do Projeto -Concluída +This library is compatible with multiple .NET versions: -## Estrutura do Repositório -``` -. -├── [Docs/](Docs/) # Documentação gerada automaticamente para a biblioteca. -│ └── media/ # Imagens e mídias utilizadas na documentação. -├── [LICENSE.txt](LICENSE.txt) # Arquivo de licença do projeto. -├── [QRCoder.Core/](QRCoder.Core/) # Código-fonte principal da biblioteca QRCoder.Core. -│ ├── [ASCIIQRCode.cs](QRCoder.Core/ASCIIQRCode.cs) # Implementação para gerar códigos QR em formato ASCII. -│ ├── [AbstractQRCode.cs](QRCoder.Core/AbstractQRCode.cs) # Classe base abstrata para todos os tipos de códigos QR. -│ ├── [ArtQRCode.cs](QRCoder.Core/ArtQRCode.cs) # Implementação para gerar códigos QR artísticos. -│ ├── [Assets/](QRCoder.Core/Assets/) # Ativos do projeto, incluindo ícones e arquivos README para NuGet. -│ │ ├── nuget-icon.png # Ícone do pacote NuGet. -│ │ └── nuget-readme.md # Conteúdo do README para o pacote NuGet. -│ ├── [Base64QRCode.cs](QRCoder.Core/Base64QRCode.cs) # Implementação para gerar códigos QR em formato Base64. -│ ├── [BitmapByteQRCode.cs](QRCoder.Core/BitmapByteQRCode.cs) # Implementação para gerar códigos QR como bitmaps de bytes. -│ ├── [Exceptions/](QRCoder.Core/Exceptions/) # Classes de exceção personalizadas para a biblioteca. -│ │ └── [DataTooLongException.cs](QRCoder.Core/Exceptions/DataTooLongException.cs) # Exceção lançada quando os dados excedem o limite do código QR. -│ ├── [Extensions/](QRCoder.Core/Extensions/) # Métodos de extensão para funcionalidades adicionais. -│ │ └── [StringValueAttribute.cs](QRCoder.Core/Extensions/StringValueAttribute.cs) # Atributo para valores de string personalizados. -│ ├── [PayloadGenerator.cs](QRCoder.Core/PayloadGenerator.cs) # Gerador de payload para diferentes tipos de códigos QR (ex: URL, SMS, Wi-Fi). -│ ├── [PdfByteQRCode.cs](QRCoder.Core/PdfByteQRCode.cs) # Implementação para gerar códigos QR em formato PDF. -│ ├── [PngByteQRCode.cs](QRCoder.Core/PngByteQRCode.cs) # Implementação para gerar códigos QR em formato PNG. -│ ├── [PostscriptQRCode.cs](QRCoder.Core/PostscriptQRCode.cs) # Implementação para gerar códigos QR em formato Postscript. -│ ├── [QRCode.cs](QRCoder.Core/QRCode.cs) # Classe principal para manipulação e renderização de códigos QR. -│ ├── [QRCodeData.cs](QRCoder.Core/QRCodeData.cs) # Estrutura de dados para armazenar dados do código QR. -│ ├── [QRCodeGenerator.cs](QRCoder.Core/QRCodeGenerator.cs) # Gerador de dados do código QR. -│ ├── [QRCoder.Core.csproj](QRCoder.Core/QRCoder.Core.csproj) # Arquivo de projeto C# para a biblioteca QRCoder.Core. -│ └── [SvgQRCode.cs](QRCoder.Core/SvgQRCode.cs) # Implementação para gerar códigos QR em formato SVG. -├── [QRCoder.Core.Docs.shfbproj](QRCoder.Core.Docs.shfbproj) # Projeto de documentação do Sandcastle Help File Builder. -├── [QRCoder.Core.Docs.sln](QRCoder.Core.Docs.sln) # Solução para o projeto de documentação. -├── [QRCoder.Core.Tests/](QRCoder.Core.Tests/) # Projeto de testes unitários para a biblioteca. -│ ├── [ArtQRCodeRendererTests.cs](QRCoder.Core.Tests/ArtQRCodeRendererTests.cs) # Testes para o renderizador de códigos QR artísticos. -│ ├── [AsciiQRCodeRendererTests.cs](QRCoder.Core.Tests/AsciiQRCodeRendererTests.cs) # Testes para o renderizador de códigos QR ASCII. -│ ├── [Helpers/](QRCoder.Core.Tests/Helpers/) # Classes auxiliares para testes. -│ │ ├── [CategoryDiscoverer.cs](QRCoder.Core.Tests/Helpers/CategoryDiscoverer.cs) # Auxiliar para descoberta de categorias de teste. -│ │ └── [HelperFunctions.cs](QRCoder.Core.Tests/Helpers/HelperFunctions.cs) # Funções auxiliares gerais para testes. -│ ├── [PayloadGeneratorTests.cs](QRCoder.Core.Tests/PayloadGeneratorTests.cs) # Testes para o gerador de payload. -│ ├── [PngByteQRCodeRendererTests.cs](QRCoder.Core.Tests/PngByteQRCodeRendererTests.cs) # Testes para o renderizador de códigos QR PNG. -│ ├── [QRCodeRendererTests.cs](QRCoder.Core.Tests/QRCodeRendererTests.cs) # Testes para o renderizador geral de códigos QR. -│ ├── [QRCoder.Core.Tests.csproj](QRCoder.Core.Tests/QRCoder.Core.Tests.csproj) # Arquivo de projeto C# para os testes. -│ ├── [QRGeneratorTests.cs](QRCoder.Core.Tests/QRGeneratorTests.cs) # Testes para o gerador de códigos QR. -│ ├── [SvgQRCodeRendererTests.cs](QRCoder.Core.Tests/SvgQRCodeRendererTests.cs) # Testes para o renderizador de códigos QR SVG. -│ └── [assets/](QRCoder.Core.Tests/assets/) # Ativos utilizados em testes (imagens, etc.). -├── [QRCoder.Core.sln](QRCoder.Core.sln) # Solução principal para o projeto QRCoder.Core. -└── [readme.md](readme.md) # README original do repositório. -``` +- **.NET Standard 2.1** — Maximum compatibility +- **.NET 8.0** — LTS recommended +- **.NET 10.0** — Latest version +- **.NET Framework 4.8** — Legacy support -## Tecnologias Utilizadas -* **C#**: Linguagem de programação principal. -* **.NET Standard 2.1, .NET 8.0, .NET 10.0, .NET Framework 4.8**: Frameworks alvo para a biblioteca. -* **SkiaSharp**: Biblioteca gráfica para renderização de códigos QR em diferentes formatos. -* **SkiaSharp.Views**: Componentes de UI para SkiaSharp. -* **System.Text.Encoding**: Para manipulação de codificação de texto. -* **System.Text.Encoding.Extensions**: Extensões para codificação de texto. -* **System.Text.Encoding.CodePages**: Suporte para páginas de código adicionais. -* **SourceLink.Create.CommandLine**: Para depuração de código-fonte. -* **Microsoft.SourceLink.GitHub**: Para integração com SourceLink do GitHub. +**Technologies Used:** +- **C#** — Primary programming language +- **SkiaSharp** — Cross-platform graphics library for rendering +- **SkiaSharp.Views** — SkiaSharp UI components +- **System.Text.Encoding.CodePages** — Additional code page support -## Pré-requisitos -Para usar ou contribuir com este projeto, você precisará ter o SDK do .NET instalado em sua máquina, compatível com as versões .NET Standard 2.1, .NET 8.0, .NET 10.0 ou .NET Framework 4.8. +## Installation -## Instalação +### NuGet Package Manager (recommended) -### NuGet Package Manager ```bash Install-Package QRCoder.Core ``` ### .NET CLI + ```bash dotnet add package QRCoder.Core ``` ### PackageReference + ```xml - + ``` -## Como Começar -Você pode gerar e visualizar seu primeiro código QR com apenas algumas linhas de código C#. +## Quick Start + +Generate your first QR code with just a few lines of code: ```csharp using QRCoder.Core; @@ -132,11 +131,7 @@ using var qrCode = new QRCode(data); using var bitmap = qrCode.GetGraphic(10); ``` -### More Examples / Mais Exemplos - -See the full documentation for all output formats and payload types: -- **[English Guide](docs/en-US/usage-guide.md)** — PNG, SVG, PDF, ASCII, Base64, Postscript, Artistic -- **[Guia Português](docs/pt-BR/guia-de-uso.md)** — PNG, SVG, PDF, ASCII, Base64, Postscript, Artístico +### More Output Formats ```csharp // SVG output @@ -144,134 +139,194 @@ using var svg = new SvgQRCode(data); string svgString = svg.GetGraphic(10); // ASCII output (great for terminal) -using var ascii = new AsciiQRCode(data); +using var ascii = new ASCIIQRCode(data); Console.WriteLine(ascii.GetGraphic(1)); // PDF output using var pdf = new PdfByteQRCode(data); byte[] pdfBytes = pdf.GetGraphic(5); -// With colors +// Base64 PNG (embed in HTML) +using var b64 = new Base64QRCode(data); +string base64Img = b64.GetGraphic(10); +// Use in HTML: + +// With custom colors using var colorQr = new QRCode(data); using var colorBmp = colorQr.GetGraphic(10, "#1a1a2e", "#e0e0e0"); + +// Postscript / EPS +using var ps = new PostscriptQRCode(data); +string psString = ps.GetGraphic(5); +``` + +### Payload Examples + +```csharp +using QRCoder.Core; + +// Wi-Fi QR Code +var wifiPayload = new PayloadGenerator.WiFi("MyNetwork", "MyPassword", + PayloadGenerator.WiFi.Authentication.WPA); +using var gen = new QRCodeGenerator(); +using var wifiData = gen.CreateQrCode(wifiPayload.ToString(), QRCodeGenerator.ECCLevel.M); + +// URL QR Code +var urlPayload = new PayloadGenerator.Url("https://github.com/afonsoft/QRCoder.Core"); +using var urlData = gen.CreateQrCode(urlPayload.ToString(), QRCodeGenerator.ECCLevel.M); + +// Email QR Code +var mailPayload = new PayloadGenerator.Mail("test@example.com", "Subject", "Body text"); +using var mailData = gen.CreateQrCode(mailPayload.ToString(), QRCodeGenerator.ECCLevel.M); + +// Phone Number +var phonePayload = new PayloadGenerator.PhoneNumber("+5511999999999"); +using var phoneData = gen.CreateQrCode(phonePayload.ToString(), QRCodeGenerator.ECCLevel.M); + +// Contact Card (vCard) +var contactPayload = new PayloadGenerator.ContactData( + PayloadGenerator.ContactData.ContactOutputType.VCard3, + "Doe", "John", + phone: "+5511999999999", + email: "john.doe@example.com"); +using var contactData = gen.CreateQrCode(contactPayload.ToString(), QRCodeGenerator.ECCLevel.M); +``` + +See the full **[Usage Guide](docs/en-US/usage-guide.md)** for all output formats, payload types, advanced settings, and error correction levels. + +## Error Correction Levels + +| Level | Recovery | Use Case | +|-------|----------|----------| +| `ECCLevel.L` | ~7% | Maximum data capacity | +| `ECCLevel.M` | ~15% | General purpose (recommended) | +| `ECCLevel.Q` | ~25% | Higher reliability | +| `ECCLevel.H` | ~30% | Maximum error recovery (logos, artistic QR) | + +## Repository Structure + +``` +. +├── QRCoder.Core/ # Core library source code +│ ├── QRCodeGenerator.cs # Main QR code data generator +│ ├── QRCodeData.cs # QR code data structure +│ ├── QRCode.cs # SKBitmap renderer +│ ├── PngByteQRCode.cs # PNG byte array renderer +│ ├── SvgQRCode.cs # SVG string renderer +│ ├── PdfByteQRCode.cs # PDF byte array renderer +│ ├── ASCIIQRCode.cs # ASCII art renderer +│ ├── Base64QRCode.cs # Base64 image renderer +│ ├── PostscriptQRCode.cs # Postscript/EPS renderer +│ ├── ArtQRCode.cs # Artistic QR code renderer +│ ├── BitmapByteQRCode.cs # BMP byte array renderer +│ ├── AbstractQRCode.cs # Base class for renderers +│ ├── PayloadGenerator.cs # Payload formatters (WiFi, URL, etc.) +│ └── Assets/ # NuGet assets +├── QRCoder.Core.Tests/ # Unit tests (300+ tests) +├── docs/ +│ ├── en-US/usage-guide.md # English usage guide +│ └── pt-BR/guia-de-uso.md # Portuguese usage guide +└── Docs/media/ # Documentation media assets ``` -## Fluxo do Projeto -O projeto `QRCoder.Core` é uma biblioteca que facilita a geração de códigos QR em aplicações .NET. O fluxo principal envolve: -1. **Geração de Dados**: A classe `QRCodeGenerator` é responsável por pegar uma string de entrada e convertê-la em `QRCodeData`, que é uma representação binária do Código QR, considerando o nível de correção de erro (ECCLevel). -2. **Renderização**: Classes que herdam de `AbstractQRCode` (como `QRCode`, `PngByteQRCode`, `SvgQRCode`, `ASCIIQRCode`, etc.) usam `QRCodeData` para renderizar o Código QR em diferentes formatos gráficos (Bitmap, PNG, SVG, ASCII, etc.). -3. **Geração de Payload**: A classe `PayloadGenerator` oferece métodos para criar payloads formatados para tipos específicos de Código QR, como URLs, SMS, contatos, Wi-Fi, entre outros, simplificando a criação de Códigos QR para casos de uso comuns. -4. **Tratamento de Exceções**: O projeto inclui exceções personalizadas, como `DataTooLongException`, para lidar com cenários onde os dados fornecidos excedem a capacidade máxima de um Código QR. - -## CI/CD e Build -O projeto utiliza um pipeline completo de CI/CD com GitHub Actions para garantir qualidade e automação: - -### Workflows Disponíveis: -- **🚀 Build & Pack**: Build principal com testes, coverage e criação de pacotes -- **📊 Code Quality**: Análise de código com Qodana e SonarCloud -- **🔒 Security Scans**: Análises de segurança com CodeQL, Snyk e SonarCloud -- **📦 Publish NuGet**: Publicação automática para NuGet.org e GitHub Packages -- **🧪 CI Build & Test**: Build contínuo e testes automatizados - -### 📊 Test Results & Coverage -- **Total Tests**: 300+ testes unitários -- **Test Status**: All passing -- **Coverage Metrics**: Line 78%+, Branch 83%+, Method 78%+ -- **Frameworks Testados**: .NET Standard 2.1, .NET 8.0, .NET 10.0, .NET Framework 4.8 -- **Relatórios**: HTML coverage reports disponíveis em cada build - -### 🧪 Executando Testes Localmente -Para executar os testes e verificar a cobertura localmente: +## CI/CD and Build + +This project uses a complete CI/CD pipeline with GitHub Actions: + +### Available Workflows + +- **Build & Pack** — Main build with tests, coverage, and package creation +- **Code Quality** — Code analysis with Qodana and SonarCloud +- **Security Scans** — Security analysis with CodeQL, Snyk, and SonarCloud +- **Publish NuGet** — Automatic publishing to NuGet.org and GitHub Packages +- **CI Build & Test** — Continuous build and automated testing + +### Running Tests Locally ```bash -# Build do projeto +# Build the project dotnet build QRCoder.Core.sln --configuration Release -# Executar todos os testes com coverage -dotnet test QRCoder.Core.Tests/QRCoder.Core.Tests.csproj --configuration Release --logger "trx;LogFileName=test-results.trx" --results-directory TestResults --collect:"XPlat Code Coverage" +# Run all tests with coverage +dotnet test QRCoder.Core.Tests/QRCoder.Core.Tests.csproj \ + --configuration Release \ + --logger "trx;LogFileName=test-results.trx" \ + --results-directory TestResults \ + --collect:"XPlat Code Coverage" -# Gerar relatório de coverage HTML +# Generate HTML coverage report dotnet tool install -g dotnet-reportgenerator-globaltool -reportgenerator -reports:"TestResults/**/coverage.cobertura.xml" -targetdir:"TestResults/CoverageReport" -reporttypes:"Html;XmlSummary;TextSummary" +reportgenerator \ + -reports:"TestResults/**/coverage.cobertura.xml" \ + -targetdir:"TestResults/CoverageReport" \ + -reporttypes:"Html;XmlSummary;TextSummary" -# Visualizar relatório -# Abra: TestResults/CoverageReport/index.html +# View report: open TestResults/CoverageReport/index.html ``` -## Desenvolvedores/Contribuintes -* **Afonso Dutra Nogueira Filho** (AFONSOFT) - Desenvolvedor principal. +## Contributing + +1. **Create a branch** from `main`: + ```bash + git checkout -b feature/your-feature + ``` + +2. **Make your changes** following code conventions + +3. **Automated workflows** will run: + - **Build & Pack** — Validates your code + - **Code Quality** — Analyzes quality + - **Security Scan** — Checks security + +4. **Pull Request**: Create a PR to `main` + +5. **Review and Merge**: After approval, your code will be merged + +## Developers -## Licença -Este projeto está licenciado sob a Licença MIT. Para mais detalhes, consulte o arquivo [LICENSE.txt](LICENSE.txt). +- **Afonso Dutra Nogueira Filho** (AFONSOFT) — Lead developer + +## License + +This project is licensed under the MIT License. See the [LICENSE.txt](LICENSE.txt) file for details. ## Changelog +### [2.0.0] - Latest +#### Changed +- Multi-language documentation (en-US default + pt-BR) +- Updated NuGet package README with examples + ### [1.0.6] - 2025-02-17 #### Added -- Comprehensive test coverage reporting (78% line coverage, 83.1% branch coverage, 78.1% method coverage) +- Comprehensive test coverage reporting (78% line, 83.1% branch, 78.1% method) - 239 unit tests across all target frameworks -- Performance optimization packages (Microsoft.Extensions.ObjectPool, System.Buffers, System.Memory) -- Local test execution documentation -- HTML coverage reports generation -- Test results badges and metrics +- Performance optimization packages - Complete CI/CD pipeline with GitHub Actions - Support for .NET 10.0 target framework - Multiple security scans (CodeQL, Snyk, SonarCloud) -- Automated NuGet publishing workflow -- Code quality analysis with Qodana -- Multi-framework build matrix #### Changed - Updated README with detailed test coverage information -- Enhanced CI/CD section with test results -- Improved project documentation with test metrics -- Added test execution guide for developers - Updated target frameworks: .NET Standard 2.1, .NET 8.0, .NET 10.0, .NET Framework 4.8 -- Improved GitHub Actions workflows -- Enhanced documentation with CI/CD badges -- Updated project dependencies #### Fixed - GitHub Actions syntax issues - Environment variable references -- Code analysis integration - -#### Coverage Details -- **Excellent Coverage (95%+)**: 10 classes including core QRCode, PngByteQRCode, SvgQRCode, PayloadGenerator -- **Good Coverage (70-94%)**: 4 classes including main QRCode and AbstractQRCode -- **Needs Improvement**: QRCodeData (20%) -- **No Coverage**: 8 alternative renderers (Base64QRCode, PdfByteQRCode, PostscriptQRCode, SKBitmapByteQRCode, etc.) ### [1.0.5] - 2025-02-17 #### Added - Support for .NET 10.0 target framework -- Complete CI/CD pipeline with GitHub Actions -- Multiple security scans (CodeQL, Snyk, SonarCloud) +- Complete CI/CD pipeline - Automated NuGet publishing workflow -- Code quality analysis with Qodana -- Enhanced test coverage reporting -- Multi-framework build matrix -#### Changed -- Updated target frameworks: .NET Standard 2.1, .NET 8.0, .NET 10.0, .NET Framework 4.8 -- Improved GitHub Actions workflows -- Enhanced documentation with CI/CD badges -- Updated project dependencies -#### Fixed -- GitHub Actions syntax issues -- Environment variable references -- Code analysis integration ### [1.0.4] - 2025-07-13 #### Changed -- General adjustments in the project and documentation. -- Improvements in README.md formatting. -- Typo corrections in README.md. -- Wiki link updates in README.md. -- Adjustments related to SkiaSharp. +- General adjustments in the project and documentation +- SkiaSharp adjustments ### [1.0.3] - 2024-04-01 #### Fixed -- Action corrections (fix actions). +- Action corrections #### Changed -- Dependency updates (codecov/codecov-action from 4 to 5, NuGet/setup-nuget from 2.0.0 to 2.0.1). -- Condition adjustments. +- Dependency updates (codecov/codecov-action, NuGet/setup-nuget) diff --git a/README.pt-br.md b/README.pt-br.md new file mode 100644 index 0000000..6d16ebf --- /dev/null +++ b/README.pt-br.md @@ -0,0 +1,254 @@ +# QRCoder.Core - Biblioteca Geradora de QR Code + +[![Build status](https://github.com/afonsoft/QRCoder.Core/actions/workflows/build-and-pack.yml/badge.svg?branch=main)](https://github.com/afonsoft/QRCoder.Core/actions/workflows/build-and-pack.yml) +[![codecov](https://codecov.io/gh/afonsoft/QRCoder.Core/graph/badge.svg?token=N8RED1A0D7)](https://codecov.io/gh/afonsoft/QRCoder.Core) +[![NuGet Badge](https://buildstats.info/nuget/QRCoder.Core?rnd=0892982314)](https://www.nuget.org/packages/QRCoder.Core/) +[![Code Quality](https://sonarcloud.io/api/project_badges/measure?project=QrCode.Core&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=QrCode.Core) +[![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=QrCode.Core&metric=security_rating)](https://sonarcloud.io/summary/new_code?id=QrCode.Core) + +> **[Read in English (en-US)](README.md)** + +## Documentacao + +- **[Guia de Uso (Portugues)](docs/pt-BR/guia-de-uso.md)** — PNG, SVG, PDF, ASCII, Base64, Postscript, QR Codes Artisticos +- **[Usage Guide (English)](docs/en-US/usage-guide.md)** — PNG, SVG, PDF, ASCII, Base64, Postscript, Artistic QR Codes + +## Descricao do Projeto + +QRCoder.Core e uma biblioteca .NET multiplataforma para geracao de QR Codes usando **SkiaSharp** para renderizacao de imagens. Compativel com **Windows**, **Linux**, **macOS** e **mobile** (Xamarin / MAUI). + +Baseado em [QRCoder](https://github.com/codebude/QRCoder). Desenvolvido e mantido por [AFONSOFT](https://github.com/afonsoft). + +### Formatos de Saida Suportados + +| Formato | Classe | Descricao | +|---------|--------|-----------| +| **SKBitmap** | `QRCode` | Imagem bitmap SkiaSharp (multiplataforma) | +| **PNG** | `PngByteQRCode` | Array de bytes PNG (sem System.Drawing) | +| **SVG** | `SvgQRCode` | String de graficos vetoriais escalaveis | +| **PDF** | `PdfByteQRCode` | Documento PDF como array de bytes | +| **ASCII** | `ASCIIQRCode` | Arte ASCII para saida em terminal | +| **Base64** | `Base64QRCode` | String de imagem codificada em Base64 | +| **Postscript** | `PostscriptQRCode` | Formato Postscript/EPS | +| **Artistico** | `ArtQRCode` | QR personalizado com pontos arredondados e fundos | +| **BMP Bytes** | `BitmapByteQRCode` | Array de bytes Bitmap | + +### Tipos de Payload Suportados + +A classe `PayloadGenerator` fornece strings formatadas para casos de uso comuns de QR code: + +| Payload | Descricao | +|---------|-----------| +| `Url` | URL de website | +| `WiFi` | Credenciais de rede Wi-Fi | +| `Mail` | Email com assunto e corpo | +| `SMS` | Mensagem SMS | +| `PhoneNumber` | Numero de telefone | +| `MMS` | Mensagem multimidia | +| `Geolocation` | Coordenadas GPS | +| `CalendarEvent` | Evento de calendario (iCal/vEvent) | +| `ContactData` | Contato vCard / MeCard | +| `BitcoinLikeCryptoCurrencyAddress` | Pagamento Bitcoin/cripto | +| `Girocode` | Pagamento SEPA europeu | +| `BezahlCode` | Padrao de pagamento alemao | +| `SwissQrCode` | Pagamento QR-bill suico | +| `OneTimePassword` | TOTP/HOTP para 2FA | +| `ShadowSocksConfig` | Configuracao de proxy ShadowSocks | +| `Bookmark` | Favorito do navegador | +| `SkypeCall` | Link de chamada Skype | +| `WhatsAppMessage` | Mensagem WhatsApp | +| `RussiaPaymentOrder` | Ordem de pagamento russa | +| `SlovenianUpnQr` | Pagamento UPN QR esloveno | + +## Cobertura de Testes + +| Metrica | Cobertura | Status | +|---------|-----------|--------| +| **Cobertura de Linhas** | 78%+ | Bom | +| **Cobertura de Branches** | 83%+ | Excelente | +| **Cobertura de Metodos** | 78%+ | Bom | +| **Total de Testes** | 300+ | Todos Passaram | + +## Status do Projeto + +**Concluido** - Mantido ativamente com pipelines modernos de CI/CD. + +## Pre-requisitos + +Esta biblioteca e compativel com multiplas versoes do .NET: + +- **.NET Standard 2.1** — Compatibilidade maxima +- **.NET 8.0** — LTS recomendado +- **.NET 10.0** — Versao mais recente +- **.NET Framework 4.8** — Suporte legado + +## Instalacao + +### NuGet Package Manager (recomendado) + +```bash +Install-Package QRCoder.Core +``` + +### .NET CLI + +```bash +dotnet add package QRCoder.Core +``` + +### PackageReference + +```xml + +``` + +## Inicio Rapido + +Gere seu primeiro QR code com apenas algumas linhas de codigo: + +```csharp +using QRCoder.Core; +using SkiaSharp; + +// Criar o gerador de QR Code +using var generator = new QRCodeGenerator(); +using var data = generator.CreateQrCode("https://github.com/afonsoft/QRCoder.Core", + QRCodeGenerator.ECCLevel.M); + +// Renderizar como bytes PNG (multiplataforma, sem System.Drawing) +using var png = new PngByteQRCode(data); +byte[] pngBytes = png.GetGraphic(10); +File.WriteAllBytes("qrcode.png", pngBytes); + +// Ou renderizar como SKBitmap +using var qrCode = new QRCode(data); +using var bitmap = qrCode.GetGraphic(10); +``` + +### Mais Formatos de Saida + +```csharp +// Saida SVG +using var svg = new SvgQRCode(data); +string svgString = svg.GetGraphic(10); + +// Saida ASCII (otimo para terminal) +using var ascii = new ASCIIQRCode(data); +Console.WriteLine(ascii.GetGraphic(1)); + +// Saida PDF +using var pdf = new PdfByteQRCode(data); +byte[] pdfBytes = pdf.GetGraphic(5); + +// Base64 PNG (embutir em HTML) +using var b64 = new Base64QRCode(data); +string base64Img = b64.GetGraphic(10); + +// Com cores personalizadas +using var colorQr = new QRCode(data); +using var colorBmp = colorQr.GetGraphic(10, "#1a1a2e", "#e0e0e0"); +``` + +### Exemplos de Payload + +```csharp +using QRCoder.Core; + +// QR Code Wi-Fi +var wifiPayload = new PayloadGenerator.WiFi("MinhaRede", "MinhaSenha", + PayloadGenerator.WiFi.Authentication.WPA); +using var gen = new QRCodeGenerator(); +using var wifiData = gen.CreateQrCode(wifiPayload.ToString(), QRCodeGenerator.ECCLevel.M); + +// QR Code URL +var urlPayload = new PayloadGenerator.Url("https://github.com/afonsoft/QRCoder.Core"); +using var urlData = gen.CreateQrCode(urlPayload.ToString(), QRCodeGenerator.ECCLevel.M); + +// QR Code Email +var mailPayload = new PayloadGenerator.Mail("teste@exemplo.com", "Assunto", "Corpo do texto"); +using var mailData = gen.CreateQrCode(mailPayload.ToString(), QRCodeGenerator.ECCLevel.M); + +// Numero de Telefone +var phonePayload = new PayloadGenerator.PhoneNumber("+5511999999999"); +using var phoneData = gen.CreateQrCode(phonePayload.ToString(), QRCodeGenerator.ECCLevel.M); + +// Cartao de Contato (vCard) +var contactPayload = new PayloadGenerator.ContactData( + PayloadGenerator.ContactData.ContactOutputType.VCard3, + "Silva", "Joao", + phone: "+5511999999999", + email: "joao.silva@exemplo.com"); +using var contactData = gen.CreateQrCode(contactPayload.ToString(), QRCodeGenerator.ECCLevel.M); +``` + +Consulte o **[Guia de Uso](docs/pt-BR/guia-de-uso.md)** completo para todos os formatos de saida, tipos de payload, configuracoes avancadas e niveis de correcao de erro. + +## Niveis de Correcao de Erro + +| Nivel | Recuperacao | Caso de Uso | +|-------|-------------|-------------| +| `ECCLevel.L` | ~7% | Capacidade maxima de dados | +| `ECCLevel.M` | ~15% | Uso geral (recomendado) | +| `ECCLevel.Q` | ~25% | Maior confiabilidade | +| `ECCLevel.H` | ~30% | Recuperacao maxima de erros (logos, QR artistico) | + +## CI/CD e Build + +O projeto utiliza um pipeline completo de CI/CD com GitHub Actions: + +### Workflows Disponiveis + +- **Build & Pack** — Build principal com testes, cobertura e criacao de pacotes +- **Code Quality** — Analise de codigo com Qodana e SonarCloud +- **Security Scans** — Analise de seguranca com CodeQL, Snyk e SonarCloud +- **Publish NuGet** — Publicacao automatica para NuGet.org e GitHub Packages +- **CI Build & Test** — Build continuo e testes automatizados + +### Executando Testes Localmente + +```bash +# Build do projeto +dotnet build QRCoder.Core.sln --configuration Release + +# Executar todos os testes com cobertura +dotnet test QRCoder.Core.Tests/QRCoder.Core.Tests.csproj \ + --configuration Release \ + --logger "trx;LogFileName=test-results.trx" \ + --results-directory TestResults \ + --collect:"XPlat Code Coverage" + +# Gerar relatorio de cobertura HTML +dotnet tool install -g dotnet-reportgenerator-globaltool +reportgenerator \ + -reports:"TestResults/**/coverage.cobertura.xml" \ + -targetdir:"TestResults/CoverageReport" \ + -reporttypes:"Html;XmlSummary;TextSummary" + +# Visualizar relatorio: abra TestResults/CoverageReport/index.html +``` + +## Como Contribuir + +1. **Crie uma branch** a partir da `main`: + ```bash + git checkout -b feature/sua-feature + ``` + +2. **Faca suas alteracoes** seguindo as convencoes de codigo + +3. **Os workflows automaticos** serao executados: + - **Build & Pack** — Valida seu codigo + - **Code Quality** — Analisa qualidade + - **Security Scan** — Verifica seguranca + +4. **Pull Request**: Crie um PR para `main` + +5. **Review e Merge**: Apos aprovacao, seu codigo sera mergeado + +## Desenvolvedores + +- **Afonso Dutra Nogueira Filho** (AFONSOFT) — Desenvolvedor principal + +## Licenca + +Este projeto esta licenciado sob a Licenca MIT. Consulte o arquivo [LICENSE.txt](LICENSE.txt) para mais detalhes.