Skip to content

Instantly share code, notes, and snippets.

@7shi
Last active October 19, 2025 14:47
Show Gist options
  • Save 7shi/d987aaf60362351bf43f3e64da22579a to your computer and use it in GitHub Desktop.
Save 7shi/d987aaf60362351bf43f3e64da22579a to your computer and use it in GitHub Desktop.
Converts an image to Sixel format with optional resizing by width and/or height.
import sys
import argparse
import io
from PIL import Image
# https://github.com/sbamboo/python-sixel
import sixel
def main():
parser = argparse.ArgumentParser(description="Display image in Sixel format with optional resizing.")
parser.add_argument("image_path", help="Path to the image file")
parser.add_argument("-W", "--width", type=int, help="Resize width while maintaining aspect ratio")
parser.add_argument("-H", "--height", type=int, help="Resize height while maintaining aspect ratio")
args = parser.parse_args()
# Load the image
img = Image.open(args.image_path)
# Resize logic
if args.width and args.height:
# Both specified: resize to the given size
img = img.resize((args.width, args.height), Image.LANCZOS)
elif args.width:
# Only width specified: keep aspect ratio
w_percent = args.width / float(img.size[0])
h_size = int(float(img.size[1]) * w_percent)
img = img.resize((args.width, h_size), Image.LANCZOS)
elif args.height:
# Only height specified: keep aspect ratio
h_percent = args.height / float(img.size[1])
w_size = int(float(img.size[0]) * h_percent)
img = img.resize((w_size, args.height), Image.LANCZOS)
# Save to memory buffer and output as Sixel
with io.BytesIO() as buf:
img.save(buf, format="PNG")
buf.seek(0)
sixel.converter.SixelConverter(buf).write(sys.stdout)
if __name__ == "__main__":
main()
@7shi
Copy link
Author

7shi commented Oct 19, 2025

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment