Welcome to mirror list, hosted at ThFree Co, Russian Federation.

FastBitmap.cs « NesTiler - github.com/ClusterM/NesTiler.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 07b33e504a53bbdf7fba4ecd6640e6c974ef8744 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;

namespace com.clusterrr.Famicom.NesTiler
{
    public class FastBitmap
    {
        public int Width { get; }
        public int Height { get; }

        private readonly Color[] colors;
        private static Dictionary<string, SKBitmap> imagesCache = new Dictionary<string, SKBitmap>();

        private FastBitmap(SKBitmap skBitmap, int verticalOffset = 0, int height = -1)
        {
            Width = skBitmap.Width;
            Height = height <= 0 ? skBitmap.Height - verticalOffset : height;
            if (skBitmap.Height - verticalOffset - Height < 0 || Height <= 0) throw new InvalidOperationException("Invalid image height.");
            var pixels = skBitmap.Pixels;
            colors = skBitmap.Pixels.Skip(verticalOffset * Width).Take(Width * Height).Select(p => Color.FromArgb(p.Alpha, p.Red, p.Green, p.Blue)).ToArray();
        }

        public static FastBitmap? Decode(string filename, int verticalOffset = 0, int height = -1)
        {
            try
            {
                using (var image = SKBitmap.Decode(filename))
                {
                    if (image == null) return null;
                    imagesCache[filename] = image;
                    return new FastBitmap(image, verticalOffset, height);
                }
            }
            finally
            {
                GC.Collect();
            }
        }

        public Color GetPixelColor(int x, int y)
        {
            return colors[(y * Width) + x];
        }

        public void SetPixelColor(int x, int y, Color color)
        {
            colors[(y * Width) + x] = color;
        }

        public byte[] Encode(SKEncodedImageFormat format, int v)
        {
            using var skImage = new SKBitmap(Width, Height);
            for (int y = 0; y < Height; y++)
            {
                for (int x = 0; x < Width; x++)
                {
                    var color = colors[(y * Width) + x];
                    var skColor = new SKColor(color.R, color.G, color.B);
                    skImage.SetPixel(x, y, skColor);
                }
            }
            return skImage.Encode(format, v).ToArray();
        }
    }
}