### Builder: EXIF metadata Source: https://github.com/zeejfps/pngsharp/blob/main/README.md Embed raw EXIF data into a PNG using the eXIf chunk. The Data must start with the 'MM' or 'II' byte order mark. The builder chains WithIhdr, WithPixelData, and WithExif. ```C# // Embed raw EXIF data (must start with "MM" or "II" byte order mark) var png = Png.Builder() .WithIhdr(ihdr) .WithPixelData(pixelData) .WithExif(new ExifChunkData { Data = exifBytes }) .Build(); ``` -------------------------------- ### Builder: ICC color profile (iCCP) and reading it back Source: https://github.com/zeejfps/pngsharp/blob/main/README.md Embed an ICC profile using IccpChunkData.Encode, which is mutually exclusive with sRGB. The example shows building the PNG with the profile and then reading it back via png.Iccp.Value.Decode() to access the profile name and raw bytes. ```C# // Embed an ICC profile (mutually exclusive with sRGB) var content = new IccpChunkContent { ProfileName = "sRGB IEC61966-2.1", RawProfile = iccBytes }; var png = Png.Builder() .WithIhdr(ihdr) .WithPixelData(pixelData) .WithIccp(IccpChunkData.Encode(content)) .Build(); // Read it back var profile = png.Iccp!.Value.Decode(); Console.WriteLine($"Profile: {profile.ProfileName}, {profile.RawProfile.Length} bytes"); ``` -------------------------------- ### Reading text chunks (tEXt, zTXt, iTXt) Source: https://github.com/zeejfps/pngsharp/blob/main/README.md Decode a PNG from a file and iterate over its text chunks. For tEXt chunks, access Keyword and Text directly. For zTXt chunks, call DecodeContent() to get the decompressed text. For iTXt chunks, DecodeContent() returns the text along with the language tag. ```C# var png = Png.DecodeFromFile("image.png"); foreach (var txt in png.TxtChunks) Console.WriteLine($"{txt.Keyword}: {txt.Text}"); foreach (var ztxt in png.ZTxtChunks) { var content = ztxt.DecodeContent(); Console.WriteLine($"{content.Keyword}: {content.Text}"); } foreach (var itxt in png.ITxtChunks) { var content = itxt.DecodeContent(); Console.WriteLine($"{content.Keyword} [{content.LanguageTag}]: {content.Text}"); } ``` -------------------------------- ### Configure PngSharp with logger and custom file system Source: https://github.com/zeejfps/pngsharp/blob/main/README.md Sets an optional logger to see debug information and assigns a custom file system implementation. Both assignments are optional and can be used independently. ```C# // Optional: specify a logger to see debug information Png.Logger = new ConsoleLogger(); // Optional: specify a custom file system Png.FileSystem = new CustomFileSystem(); ``` -------------------------------- ### Create images from raw pixel data Source: https://github.com/zeejfps/pngsharp/blob/main/README.md Shows how to create PNG image objects from raw pixel data in various formats: RGBA, RGB, grayscale, and grayscale with alpha. The final line demonstrates encoding the created image to a file. ```C# // RGBA (4 bytes per pixel) var rgba = Png.CreateRgba(width, height, pixelData); ``` ```C# // RGB (3 bytes per pixel) var rgb = Png.CreateRgb(width, height, pixelData); ``` ```C# // Grayscale (1 byte per pixel) var gray = Png.CreateGrayscale(width, height, pixelData); ``` ```C# // Grayscale with alpha (2 bytes per pixel) var grayAlpha = Png.CreateGrayscaleWithAlpha(width, height, pixelData); ``` ```C# // Then encode Png.EncodeToFile(rgba, "output.png"); ``` -------------------------------- ### Builder: Indexed color with palette and transparency Source: https://github.com/zeejfps/pngsharp/blob/main/README.md Create an indexed-color PNG with a palette (PLTE) and transparency (tRNS) chunk. The palette entries are specified as RGB triplets, and the tRNS data provides alpha values for each palette entry. The pixel data is provided as indices into the palette. ```C# var png = Png.Builder() .WithIhdr(new IhdrChunkData { Width = 16, Height = 16, BitDepth = 8, ColorType = ColorType.IndexedColor, CompressionMethod = CompressionMethod.DeflateWithSlidingWindow, FilterMethod = FilterMethod.AdaptiveFiltering, InterlaceMethod = InterlaceMethod.None, }) .WithPlte(new PlteChunkData { Entries = [255, 0, 0, 0, 255, 0, 0, 0, 255] }) // red, green, blue .WithTrns(new TrnsChunkData { Data = [255, 128, 0] }) // fully opaque, semi-transparent, fully transparent .WithPixelData(pixelIndices) .Build(); ``` -------------------------------- ### Builder: Basic PNG with IHDR, pixel data, sRGB, gamma, and physical dimensions Source: https://github.com/zeejfps/pngsharp/blob/main/README.md Use the Png.Builder fluent API to create a PNG with an IHDR chunk, pixel data, sRGB rendering intent, gamma value, and physical pixel dimensions. The gamma is set via GammaChunkData.FromDouble(0.45455) and physical dimensions via PhysChunkData.FromDpi(96, 96). The resulting Png object is encoded to a file with Png.EncodeToFile. ```C# var png = Png.Builder() .WithIhdr(new IhdrChunkData { Width = 256, Height = 256, BitDepth = 8, ColorType = ColorType.TrueColorWithAlpha, CompressionMethod = CompressionMethod.DeflateWithSlidingWindow, FilterMethod = FilterMethod.AdaptiveFiltering, InterlaceMethod = InterlaceMethod.None, }) .WithPixelData(pixelData) .WithSrgb(new SrgbChunkData { RenderingIntent = RenderingIntent.Perceptual }) .WithGama(GammaChunkData.FromDouble(0.45455)) // or set raw: new GammaChunkData { Value = 45455 } .WithPhys(PhysChunkData.FromDpi(96, 96)) // or set raw PPU values .Build(); Png.EncodeToFile(png, "output.png"); ``` -------------------------------- ### Encode PNG to file, byte array, and stream Source: https://github.com/zeejfps/pngsharp/blob/main/README.md Shows three ways to encode a PNG image using PNGSharp: to a file, to a byte array, and to a stream. Use the appropriate method based on your output target. ```C# // Encode to a file Png.EncodeToFile(png, "output.png"); ``` ```C# // Encode to a byte array byte[] bytes = Png.EncodeToByteArray(png); ``` ```C# // Encode to a stream Png.EncodeToStream(png, stream); ``` -------------------------------- ### Builder: Text metadata (tEXt, zTXt, iTXt) Source: https://github.com/zeejfps/pngsharp/blob/main/README.md Add text metadata to a PNG using three chunk types: uncompressed Latin-1 (tEXt), compressed Latin-1 (zTXt), and international UTF-8 (iTXt). The iTXt chunk uses ITextChunk.Create with a language tag and translated keyword. The builder chains WithTxtChunk, WithZTxtChunk, and WithITxtChunk. ```C# var png = Png.Builder() .WithIhdr(ihdr) .WithPixelData(pixelData) // Uncompressed Latin-1 text (tEXt) .WithTxtChunk(new TextChunk { Keyword = "Author", Text = "Jane Doe" }) // Compressed Latin-1 text (zTXt) .WithZTxtChunk(ZTextChunk.Create(new ZTextContent { Keyword = "Comment", Text = "A long description..." })) // International UTF-8 text (iTXt) .WithITxtChunk(ITextChunk.Create(new ITextContent { Keyword = "Title", Text = "タイトル", LanguageTag = "ja", TranslatedKeyword = "タイトル", })) .Build(); ``` -------------------------------- ### Builder: Chromaticities, background color, and modification time Source: https://github.com/zeejfps/pngsharp/blob/main/README.md Add chromaticities (cHRM), background color (bKGD), and modification time (tIME) chunks to a PNG. The background data is specified as raw RGB values (2 bytes each). The modification time is set from a DateTimeOffset. ```C# var png = Png.Builder() .WithIhdr(ihdr) .WithPixelData(pixelData) .WithChrm(new ChrmChunkData { WhitePointX = 31270, WhitePointY = 32900, RedX = 64000, RedY = 33000, GreenX = 30000, GreenY = 60000, BlueX = 15000, BlueY = 6000, }) .WithBkgd(new BkgdChunkData { Data = [0, 0, 0, 0, 0, 0] }) // black background (RGB, 2 bytes each) .WithTime(TimeChunkData.FromDateTimeOffset(DateTimeOffset.UtcNow)) .Build(); ``` -------------------------------- ### Chunk Data Conversion Helpers (C#) Source: https://github.com/zeejfps/pngsharp/blob/main/README.md Shows convenience methods for converting PNG chunk data: pHYs DPI, gAMA gamma, tIME time, iCCP compress/decompress, cHRM chromaticities, and IHDR pixel/scanline helpers. Use these to avoid manual byte manipulation when working with chunk data. ```C# // Physical dimensions (pHYs) — DPI conversion var phys = PhysChunkData.FromDpi(300, 300); double dpiX = phys.GetDpiX(); // 300.0 double dpiY = phys.GetDpiY(); // 300.0 // Gamma (gAMA) — double conversion var gama = GammaChunkData.FromDouble(0.45455); double gamma = gama.ToDouble(); // 0.45455 // Modification time (tIME) — DateTimeOffset conversion var time = TimeChunkData.FromDateTimeOffset(DateTimeOffset.UtcNow); DateTimeOffset dt = time.ToDateTimeOffset(); // ICC profile (iCCP) — compress/decompress var iccp = IccpChunkData.Encode(new IccpChunkContent { ProfileName = "sRGB", RawProfile = rawBytes }); IccpChunkContent content = iccp.Decode(); // Chromaticities (cHRM) — scaled double conversion var chrm = ChrmChunkData.Create(new ChrmChunkContent { WhitePointX = 0.3127, WhitePointY = 0.3290, ... }); ChrmChunkContent values = chrm.DecodeContent(); // IHDR helpers int bpp = ihdr.GetBytesPerPixel(); int bitsPerPixel = ihdr.GetBitsPerPixel(); int scanlineBytes = ihdr.GetScanlineByteWidth(); ``` -------------------------------- ### Builder: Significant bits (sBIT) Source: https://github.com/zeejfps/pngsharp/blob/main/README.md Add an sBIT chunk to specify the original significant bits per channel, useful for sources like 5-6-5 RGB. The Data array length depends on the color type. The builder chains WithIhdr, WithPixelData, and WithSbit. ```C# var png = Png.Builder() .WithIhdr(ihdr) .WithPixelData(pixelData) // sBIT: original significant bits per channel (e.g. 5-6-5 RGB source) .WithSbit(new SbitChunkData { Data = [5, 6, 5] }) // length depends on color type .Build(); ``` -------------------------------- ### Decode PNG from file, byte array, and stream Source: https://github.com/zeejfps/pngsharp/blob/main/README.md Shows how to decode a PNG from a file, byte array, or stream using PngSharp. Access image data via the Ihdr property and PixelData array. Helper extension methods provide dimensions, memory size, and color type checks. ```C# // Decode from a file var png = Png.DecodeFromFile("image.png"); // Decode from a byte array var png = Png.DecodeFromByteArray(bytes); // Decode from a stream var png = Png.DecodeFromStream(stream); // Access image data var ihdr = png.Ihdr; Console.WriteLine($"{ihdr.Width}x{ihdr.Height}, {ihdr.GetBytesPerPixel()} bytes per pixel"); byte[] pixels = png.PixelData; // Helper extension methods PngSize size = png.GetDimensions(); // (Width, Height) tuple long bytes = png.GetMemorySize(); // total pixel data size in bytes bool alpha = png.HasAlphaChannel(); // true for GrayscaleWithAlpha / TrueColorWithAlpha bool palette = png.HasPalette(); // true for IndexedColor bool gray = png.IsGrayscale(); // true for Grayscale / GrayscaleWithAlpha ``` -------------------------------- ### PngSharp Encoding and Image Creation Source: https://github.com/zeejfps/pngsharp/blob/main/README.md C# API for PngSharp: methods to encode Png objects to files, byte arrays, or streams, and static factory methods to create Png objects from raw pixel data in various formats. ```APIDOC ## [C#] Png.EncodeToFile ### Description Encodes a Png object to a file. ### Method C# static method ### Endpoint Png.EncodeToFile(png, outputFilePath) ### Parameters - **png** (Png object) - Required - The Png object to encode. - **outputFilePath** (string) - Required - The path to the output file. ### Request Example ```csharp Png.EncodeToFile(png, "output.png"); ``` ### Response No return value. ``` ```APIDOC ## [C#] Png.EncodeToByteArray ### Description Encodes a Png object to a byte array. ### Method C# static method ### Endpoint Png.EncodeToByteArray(png) ### Parameters - **png** (Png object) - Required - The Png object to encode. ### Request Example ```csharp byte[] bytes = Png.EncodeToByteArray(png); ``` ### Response #### Success Response - **byte[]** - The encoded PNG data as a byte array. ``` ```APIDOC ## [C#] Png.EncodeToStream ### Description Encodes a Png object to a stream. ### Method C# static method ### Endpoint Png.EncodeToStream(png, stream) ### Parameters - **png** (Png object) - Required - The Png object to encode. - **stream** (Stream) - Required - The stream to write the encoded data to. ### Request Example ```csharp Png.EncodeToStream(png, stream); ``` ### Response No return value. ``` ```APIDOC ## [C#] Png.CreateRgba ### Description Creates a Png object from raw RGBA pixel data. ### Method C# static method ### Endpoint Png.CreateRgba(width, height, pixelData) ### Parameters - **width** (int) - Required - The width of the image. - **height** (int) - Required - The height of the image. - **pixelData** (byte[]) - Required - Raw pixel data in RGBA format (4 bytes per pixel). ### Request Example ```csharp var rgba = Png.CreateRgba(width, height, pixelData); ``` ### Response #### Success Response - **Png object** - The created Png object. ``` ```APIDOC ## [C#] Png.CreateRgb ### Description Creates a Png object from raw RGB pixel data. ### Method C# static method ### Endpoint Png.CreateRgb(width, height, pixelData) ### Parameters - **width** (int) - Required - The width of the image. - **height** (int) - Required - The height of the image. - **pixelData** (byte[]) - Required - Raw pixel data in RGB format (3 bytes per pixel). ### Request Example ```csharp var rgb = Png.CreateRgb(width, height, pixelData); ``` ### Response #### Success Response - **Png object** - The created Png object. ``` ```APIDOC ## [C#] Png.CreateGrayscale ### Description Creates a Png object from raw grayscale pixel data. ### Method C# static method ### Endpoint Png.CreateGrayscale(width, height, pixelData) ### Parameters - **width** (int) - Required - The width of the image. - **height** (int) - Required - The height of the image. - **pixelData** (byte[]) - Required - Raw pixel data in grayscale format (1 byte per pixel). ### Request Example ```csharp var gray = Png.CreateGrayscale(width, height, pixelData); ``` ### Response #### Success Response - **Png object** - The created Png object. ``` ```APIDOC ## [C#] Png.CreateGrayscaleWithAlpha ### Description Creates a Png object from raw grayscale-with-alpha pixel data. ### Method C# static method ### Endpoint Png.CreateGrayscaleWithAlpha(width, height, pixelData) ### Parameters - **width** (int) - Required - The width of the image. - **height** (int) - Required - The height of the image. - **pixelData** (byte[]) - Required - Raw pixel data in grayscale-with-alpha format (2 bytes per pixel). ### Request Example ```csharp var grayAlpha = Png.CreateGrayscaleWithAlpha(width, height, pixelData); ``` ### Response #### Success Response - **Png object** - The created Png object. ``` -------------------------------- ### Gamma Correction Extension Methods (C#) Source: https://github.com/zeejfps/pngsharp/blob/main/README.md Shows gamma correction and color space conversion methods on decoded PNG data. All methods return new byte[] without mutating the original; alpha channels are never gamma corrected. Use GetFileGamma to query effective gamma (sRGB takes precedence over gAMA), ApplyGammaCorrection for spec gamma, ToLinear for linear light, ToSrgb for sRGB encoding, and GetGammaCorrectedPalette for indexed images. ```C# var png = Png.DecodeFromFile("image.png"); // Query the effective file gamma (sRGB > gAMA precedence) double? gamma = png.GetFileGamma(); // ~0.45455 for sRGB, or the gAMA value, or null // Apply PNG spec gamma correction: output = input ^ (1 / (fileGamma * displayGamma)) byte[] corrected = png.ApplyGammaCorrection(); // default displayGamma = 2.2 byte[] corrected = png.ApplyGammaCorrection(1.8); // custom display gamma // Convert to linear light (gamma 1.0) // Uses precise sRGB piecewise transfer when sRGB chunk is present byte[] linear = png.ToLinear(); // Convert to sRGB encoding // If already sRGB-tagged, returns a clone; otherwise linearizes then applies sRGB transfer byte[] srgb = png.ToSrgb(); // Get a gamma-corrected palette (for indexed color images) PlteChunkData? palette = png.GetGammaCorrectedPalette(); ``` -------------------------------- ### Builder: Adam7 interlaced encoding Source: https://github.com/zeejfps/pngsharp/blob/main/README.md Create an Adam7 interlaced PNG by setting InterlaceMethod to InterlaceMethod.Adam7 in the IHDR chunk. The pixel data is provided as usual, and the resulting PNG is saved to 'interlaced.png'. Interlaced images are automatically deinterlaced when decoded, so png.PixelData always contains the final non-interlaced data. ```C# var png = Png.Builder() .WithIhdr(new IhdrChunkData { Width = 256, Height = 256, BitDepth = 8, ColorType = ColorType.TrueColorWithAlpha, CompressionMethod = CompressionMethod.DeflateWithSlidingWindow, FilterMethod = FilterMethod.AdaptiveFiltering, InterlaceMethod = InterlaceMethod.Adam7, }) .WithPixelData(pixelData) .Build(); Png.EncodeToFile(png, "interlaced.png"); ```