Last active
March 3, 2022 05:41
-
-
Save frostming/a424f6875869d86ad579a645c29fefbf to your computer and use it in GitHub Desktop.
Render image in iTerm2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Render Image in iTerm2 without pixelization | |
This small snippet is ported from https://github.com/sindresorhus/ansi-escapes. | |
It leverages iTerm2's image protocol: https://iterm2.com/documentation-images.html | |
so it only works on iTerm2. | |
Released to the public domain, feel free to copy and modify. | |
- Frost Ming | |
""" | |
import base64 | |
from pathlib import Path | |
def iterm_image( | |
image: str|Path|bytes, # The path to the image file(JPG/PNG), or image bytes | |
*, | |
width: int|str|None = None, # The image width: 5/5px/50% | |
height: int|str|None = None, # The image height: 5/5px/50% | |
preserve_aspect_ratio: bool = True # Whether to keep the aspect ratio | |
) -> str: | |
if not isinstance(image, bytes): | |
with open(image, 'rb') as f: | |
image = f.read() | |
image_data = base64.b64encode(image).decode() | |
stream = '\u001b]1337;File=inline=1' | |
if width is not None: | |
stream += f';{width=}' | |
if height is not None: | |
stream += f';{height=}' | |
if not preserve_aspect_ratio: | |
stream += ';preserveAspectRatio=0' | |
return f'{stream}:{image_data}\u0007' | |
if __name__ == '__main__': | |
print(iterm_image('test_image.png')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment