using System.Buffers.Binary; using System.IO.Compression; namespace GamePort.Assets; public sealed record PngImage(uint Width, uint Height, byte[] Rgba) { public static PngImage White => new(1, 1, [255,255,255,255]); public static PngImage Load(string path) { using var file = File.OpenRead(path); Span signature = stackalloc byte[8]; file.ReadExactly(signature); if(signature[0]==(byte)'B' && signature[1]==(byte)'M')return LoadBmp(path); if (!signature.SequenceEqual(new byte[] {137,80,78,71,13,10,26,10})) throw new InvalidDataException("Invalid PNG signature."); uint width=0, height=0; byte color=0; byte[] palette=[], alpha=[]; using var compressed = new MemoryStream(); Span header = stackalloc byte[8]; Span crc = stackalloc byte[4]; while (true) { file.ReadExactly(header); var size = BinaryPrimitives.ReadUInt32BigEndian(header); if (size > 64*1024*1024) throw new InvalidDataException("PNG chunk exceeds limit."); var data = new byte[(int)size]; file.ReadExactly(data); file.ReadExactly(crc); var kind = System.Text.Encoding.ASCII.GetString(header[4..]); if (kind == "IHDR") { if (data.Length != 13) throw new InvalidDataException("Invalid PNG IHDR."); width=BinaryPrimitives.ReadUInt32BigEndian(data); height=BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(4)); if (width==0 || height==0 || width>8192 || height>8192 || data[8]!=8 || data[10]!=0 || data[11]!=0 || data[12]!=0) throw new NotSupportedException("Only non-interlaced 8-bit PNGs up to 8192 pixels are supported."); color=data[9]; } else if (kind == "PLTE") palette=data; else if (kind == "tRNS") alpha=data; else if (kind == "IDAT") compressed.Write(data); else if (kind == "IEND") break; } var channels = color switch {0=>1,2=>3,3=>1,4=>2,6=>4,_=>throw new NotSupportedException($"PNG color type {color} unsupported.")}; var stride = checked((int)width*channels); var scan = new byte[checked((stride+1)*(int)height)]; compressed.Position=0; using (var z = new ZLibStream(compressed, CompressionMode.Decompress, true)) {z.ReadExactly(scan); if(z.ReadByte()!=-1)throw new InvalidDataException("Excess PNG data.");} var pixels=new byte[checked(stride*(int)height)]; for(int y=0;y=channels?pixels[i-channels]:0; var b=y>0?pixels[i-stride]:0; var c=y>0&&x>=channels?pixels[i-stride-channels]:0; var predictor=scan[y*(stride+1)] switch {0=>0,1=>a,2=>b,3=>(a+b)/2,4=>Paeth(a,b,c),_=>throw new InvalidDataException("Invalid PNG filter.")}; pixels[i]=unchecked((byte)(scan[y*(stride+1)+x+1]+predictor)); } var rgba=new byte[checked((int)(width*height*4))]; for(int i=0;i=palette.Length)throw new InvalidDataException("PNG palette index out of bounds."); rgba[d]=palette[p*3];rgba[d+1]=palette[p*3+1];rgba[d+2]=palette[p*3+2];rgba[d+3]=p8192 || h==0 || h< -8192 || h>8192 || compression!=0 || depth is not (8 or 24 or 32))throw new NotSupportedException("Only uncompressed 8/24/32-bit BMP is supported."); var height=Math.Abs(h);var stride=checked((w*depth+31)/32*4); if((ulong)offset+(ulong)stride*(uint)height>(ulong)bytes.Length)throw new InvalidDataException("Truncated BMP pixels."); var palette=14+checked((int)BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(14))); var rgba=new byte[checked(w*height*4)]; for(var y=0;y0?height-1-y:y)*stride+x*(depth/8); if(depth==8){src=palette+bytes[src]*4;if(src+4>offset)throw new InvalidDataException("BMP palette index out of range.");} var dst=(y*w+x)*4;rgba[dst]=bytes[src+2];rgba[dst+1]=bytes[src+1];rgba[dst+2]=bytes[src];rgba[dst+3]=255; } return new PngImage((uint)w,(uint)height,rgba); } private static int Paeth(int a,int b,int c){var p=a+b-c;var pa=Math.Abs(p-a);var pb=Math.Abs(p-b);var pc=Math.Abs(p-c);return pa<=pb&&pa<=pc?a:pb<=pc?b:c;} }