diff --git a/minecraft/Convert NFP/convert.bat b/minecraft/Convert NFP/convert.bat new file mode 100644 index 0000000..27de41a --- /dev/null +++ b/minecraft/Convert NFP/convert.bat @@ -0,0 +1,3 @@ +@echo off +python.exe .\main.py %1 +@REM pause \ No newline at end of file diff --git a/minecraft/Convert NFP/main.py b/minecraft/Convert NFP/main.py new file mode 100644 index 0000000..dfe0f23 --- /dev/null +++ b/minecraft/Convert NFP/main.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +from PIL import Image +import nfp +import pastebin +import argparse +import pyperclip +import os + +# default resize width/height when converting image -> nfp +DEFAULT_WIDTH, DEFAULT_HEIGHT = 164, 81 + +desc = ( + "Convert standard image files to ComputerCraft nfp files, and vice " + "versa. Input file type is identified by extension (.nfp, .jpg, etc.), " + "and output files use the input filename with a new extension." +) +files_help = "input files, nfp or image (must have correct file extension)" +nfp_desc = "optional arguments when converting image -> nfp" +skip_help = "skip default behavior of resizing image before conversion" +width_help = "if resizing, new width (default: {})".format(DEFAULT_WIDTH) +height_help = "if resizing, new height (default: {})".format(DEFAULT_HEIGHT) +im_desc = "optional arguments when converting nfp -> image" +format_help = ( + "output format passed to Image.save() (also output file extension " + "unless -e argument specified), see PIL docs for supported formats, " + "default: PNG" +) +ext_help = ( + "if specified, will be used as the output file extension instead of " "FORMAT" +) +rm_help = "remove the original image after converting" +dither_help = "enables dithering" + +parser = argparse.ArgumentParser(description=desc) +parser.add_argument("files", help=files_help, nargs="+") +nfp_group = parser.add_argument_group("nfp arguments", description=nfp_desc) +nfp_group.add_argument( + "--skip-resize", "-s", help=skip_help, action="store_true", default=False +) +nfp_group.add_argument( + "--resize-width", + "-w", + help=width_help, + metavar="WIDTH", + type=int, + default=DEFAULT_WIDTH, +) +nfp_group.add_argument( + "--resize-height", + "-H", + help=height_help, + metavar="HEIGHT", + type=int, + default=DEFAULT_HEIGHT, +) +im_group = parser.add_argument_group("image arguments", description=im_desc) +im_group.add_argument( + "--format", "-f", help=format_help, metavar="FORMAT", dest="f_format", default="PNG" +) +im_group.add_argument("--extension", "-e", help=ext_help) +im_group.add_argument("--remove", "-r", help=rm_help, action="store_true") +im_group.add_argument("--dither", "-d", help=dither_help, action="store_true") + +args = parser.parse_args() + +for file in args.files: + filename, ext = os.path.splitext(file) + if not ext: + parser.error("filename must have appropriate extension") + if ext.upper() == ".NFP": + with open(file, "rt") as f: + nfp_file = f.read() + im = nfp.nfp_to_img(nfp_file) + new_ext = args.f_format.replace(" ", "").lower() + if args.extension: + new_ext = args.extension + im.save("{}.{}".format(filename, new_ext), args.f_format) + else: + im = Image.open(file) + if args.skip_resize: + nfp_file = nfp.img_to_nfp(im, dither=1 if args.dither else 0) + else: + nfp_file = nfp.img_to_nfp( + im, + (args.resize_width, args.resize_height), + dither=1 if args.dither else 0, + ) + code = pastebin.upload(nfp_file) + if code.startswith("FAILURE"): + print(code) + _ = input() + else: + pyperclip.copy(code) + if args.remove: + os.remove(file) diff --git a/minecraft/Convert NFP/nfp.py b/minecraft/Convert NFP/nfp.py new file mode 100644 index 0000000..b65167d --- /dev/null +++ b/minecraft/Convert NFP/nfp.py @@ -0,0 +1,93 @@ +from PIL import Image +import numpy as np + +# NFP is a simple text-based 16-color image format used by ComputerCraft's paint +# program. Each pixel is represented by a one-digit hex value from 0-f (decimal +# 0-15) corresponding to an index into the 16-color ComputerCraft color palette. +# Each row is terminated by a newline. +# +# Example of a 4x4 black/white checkerboard pattern NFP image: +# f0f0 +# 0f0f +# f0f0 +# 0f0f + +# values come from http://www.computercraft.info/wiki/Colors_(API) +CC_COLORS = ( + (240, 240, 240), # white, 0 + (242, 178, 51), # orange, 1 + (229, 127, 216), # magenta, 2 + (153, 178, 242), # lightBlue, 3 + (222, 222, 108), # yellow, 4 + (127, 204, 25), # lime, 5 + (242, 178, 204), # pink, 6 + (76, 76, 76), # gray, 7 + (153, 153, 153), # lightGray, 8 + (76, 153, 178), # cyan, 9 + (178, 102, 229), # purple, a + (51, 102, 204), # blue, b + (127, 102, 76), # brown, c + (87, 166, 78), # green, d + (204, 76, 76), # red, e + (25, 25, 25), # black, f +) + + +# Takes a PIL image and converts to nfp. Returns nfp data as string. +# If new_size is provided, image will be resized before conversion. +# new_size should be a 2-tuple: (width, height). +# Recommended size for CC monitors at text scale 0.5 is (164, 81). +def img_to_nfp(im, new_size=None, dither=0): + if new_size: + im = im.resize(new_size) + # A technique called image quantization is used to reduce the input image's + # color palette to only the 16 ComputerCraft colors. + im = _quantize_with_colors(im, CC_COLORS, dither) + # After quantize, im is mode "P" (palletized), so im.getdata() returns a + # sequence of ints representing indexes into the image's 16-color palette + # from 0-15 (hex 0-f) for each pixel in the image. This is flattened, so + # the values for image line two immediately follow image line one's values. + # We use np.reshape() to turn it into a 2D numpy array whose values can be + # accessed through arr[row][col] notation. + data = im.getdata() + width, height = im.size + data_2d = np.reshape(np.array(data), (height, width)) + # convert from np array back to list for faster iteration + data_2d = data_2d.tolist() + nfp_im = "" + for row in range(height): + for col in range(width): + # convert 0-15 decimal value to hex string (0-f) + nfp_im += format(data_2d[row][col], "x") + if row != len(data_2d) - 1: + nfp_im += "\n" + return nfp_im + + +# Takes nfp (as string data) and returns a PIL image. +def nfp_to_img(nfp): + nfp = nfp.splitlines() + height = len(nfp) + width = len(nfp[0]) + im = Image.new("RGB", (width, height)) + px = im.load() + for row in range(height): + for col in range(width): + nfp_pixel = nfp[row][col] + color_idx = int(nfp_pixel, 16) + pixel_color = CC_COLORS[color_idx] + px[col, row] = pixel_color + return im + + +# Colors is a list/tuple of 3-item (R, G, B) tuples. +def _quantize_with_colors(image, colors, dither=0): + pal_im = Image.new("P", (1, 1)) + color_vals = [] + for color in colors: + for val in color: + color_vals.append(val) + color_vals = tuple(color_vals) + pal_im.putpalette(color_vals + colors[-1] * (256 - len(colors))) + image = image.convert(mode="RGB") + return image.quantize(palette=pal_im, dither=dither) diff --git a/minecraft/Convert NFP/pastebin.py b/minecraft/Convert NFP/pastebin.py new file mode 100644 index 0000000..9e69156 --- /dev/null +++ b/minecraft/Convert NFP/pastebin.py @@ -0,0 +1,12 @@ +import requests + +_KEY = "xxxxxx" # TODO: Provide this key on your own! + + +def upload(nfp_contents: str) -> str: + data = {"api_dev_key": _KEY, "api_paste_code": nfp_contents, "api_option": "paste"} + + resp = requests.post("https://pastebin.com/api/api_post.php", data=data) + if resp.status_code == 200: + return resp.text.replace("https://pastebin.com/", "") + return f"FAILURE: {resp.text}" diff --git a/minecraft/Convert NFP/requirements.txt b/minecraft/Convert NFP/requirements.txt new file mode 100644 index 0000000..c380c4b --- /dev/null +++ b/minecraft/Convert NFP/requirements.txt @@ -0,0 +1,4 @@ +Pillow>=6 +numpy>=1.16 +pyperclip==1.8.2 +requests==2.28.1 \ No newline at end of file