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 69 70 71 72 73 74 75 76 77 78 79 80 81
| from PIL import Image
def interpolate_color(config: list, value: int) -> tuple: if value is None: return 0, 0, 0, 0 lower_entry = None higher_entry = None for entry in config: if entry[0] <= value: lower_entry = entry if entry[0] >= value: higher_entry = entry break
if lower_entry is None: return tuple(higher_entry[1]) elif higher_entry is None: return tuple(lower_entry[1])
check = (higher_entry[0] - lower_entry[0]) if check == 0: return lower_entry[1][0], lower_entry[1][1], lower_entry[1][2], 255 else: ratio = (value - lower_entry[0]) / (higher_entry[0] - lower_entry[0]) result = interpolate_color_between(lower_entry[1], higher_entry[1], ratio) return result
def interpolate_color_between(color1: tuple, color2: tuple, ratio: int) -> tuple: r1, g1, b1 = color1 r2, g2, b2 = color2
r = int(r1 + (r2 - r1) * ratio) g = int(g1 + (g2 - g1) * ratio) b = int(b1 + (b2 - b1) * ratio) a = 255 return r, g, b, a
def draw_image(rgba_array: list, width: int, height: int) -> Image: image = Image.new("RGBA", (width, height)) image.putdata(rgba_array) return image
def get_rgba_list(data: list, config: dict) -> list: cache = [] for d in data: cache.append(interpolate_color(config, d)) return cache
def fake_data_generator(x: int, y: int, value: int) -> list: cache = [] for i in range(x * y): cache.append(value) return cache;
if __name__ == "__main__": x = 45 y = 45 data = fake_data_generator(45, 45, 305)
config = [ [193, [255, 255, 255]], [215, [237, 220, 237]], [230, [227, 204, 229]], [245, [206, 169, 212]], [260, [139, 97, 184]], [275, [51, 76, 160]], [290, [76, 159, 199]], [305, [211, 243, 149]], [320, [248, 144, 43]], [335, [148, 21, 50]], [350, [44, 0, 15]], ] rgba_list = get_rgba_list(data, config) img = draw_image(rgba_list, y, x).resize((256, 256)) img.save("tile.webp", "WEBP")
|