diff options
| author | Sarah Bradley <git@sarahduck.ca> | 2023-12-25 16:24:47 -0800 |
|---|---|---|
| committer | Sarah Bradley <git@sarahduck.ca> | 2023-12-25 16:24:47 -0800 |
| commit | f6100c020613de7980861b7d77f4c37e1a65a025 (patch) | |
| tree | a73f5a0b0f133a34bfd0e171cf7af01d43e72279 /Bitmap.cs | |
| parent | 626c005b5217b70089fdd6956f2736f600015026 (diff) | |
Added image size limits
Diffstat (limited to 'Bitmap.cs')
| -rw-r--r-- | Bitmap.cs | 29 |
1 files changed, 23 insertions, 6 deletions
@@ -1,5 +1,6 @@ using System.Buffers.Binary; using System.IO.Compression; +using System.Numerics; using Raylib_cs; namespace OnekoOnline; @@ -12,10 +13,16 @@ class Bitmap : IDisposable readonly byte[] SerializedData; - public Bitmap(Image img) + const int MaxWidth = 256; + const int MaxHeight = 256; + + public Bitmap(Image img, int MaxW = 256, int MaxH = 256) { Width = img.Width; Height = img.Height; + //Crop image if too big + if (Width > MaxW || Height > MaxH) Raylib.ImageCrop(ref img, new Rectangle(0f, 0f, MaxW, MaxH)); + Texture = Raylib.LoadTextureFromImage(img); //Get Data for Serialization @@ -59,21 +66,21 @@ class Bitmap : IDisposable Raylib.UnloadImage(img); } - public static Bitmap FromFile(string path) + public static Bitmap FromFile(string path, int MaxW = MaxWidth, int MaxH = MaxHeight) { if (!File.Exists(path) || new FileInfo(path).Length > 40000 || !path.Contains(".png")) return new Bitmap(Raylib.GenImageChecked(32, 32, 4, 4, Color.BLACK, Color.PINK)); byte[] memory = File.ReadAllBytes(path); - return FromPNGMemory(memory); + return FromPNGMemory(memory, MaxW, MaxH); } - public static Bitmap FromPNGMemory(byte[] memory) + public static Bitmap FromPNGMemory(byte[] memory, int MaxW = MaxWidth, int MaxH = MaxHeight) { - return new Bitmap(Raylib.LoadImageFromMemory(".png", memory)); + return new Bitmap(Raylib.LoadImageFromMemory(".png", memory), MaxW, MaxH); } - public static Bitmap Deserialize(ReadOnlySpan<byte> span) + public static Bitmap Deserialize(ReadOnlySpan<byte> span, int MaxW = MaxWidth, int MaxH = MaxHeight, byte[]? fallbackImage = null) { byte[] compressed = span.ToArray(); byte[] data; @@ -87,8 +94,18 @@ class Bitmap : IDisposable int width = BinaryPrimitives.ReadInt16LittleEndian(data.AsSpan(0, sizeof(short))); int height = BinaryPrimitives.ReadInt16LittleEndian(data.AsSpan(sizeof(short), sizeof(short))); + + bool TooBig = width > MaxW || height > MaxH; + if (TooBig) { + width = Math.Clamp(width, 0, MaxW); + height = Math.Clamp(height, 0, MaxH); + if (fallbackImage != null) return FromPNGMemory(fallbackImage, MaxW, MaxH); + } + Image img = Raylib.GenImageChecked(width, height, 4, 4, Color.PINK, Color.BLACK); + if (TooBig) return new Bitmap(img); + int i = sizeof(short)*2; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { |
