Skip to content

Instantly share code, notes, and snippets.

@iwasakishuto
Created October 22, 2021 01:11
Show Gist options
  • Save iwasakishuto/440c3a9b943630e06d6968e0249d2a9c to your computer and use it in GitHub Desktop.
Save iwasakishuto/440c3a9b943630e06d6968e0249d2a9c to your computer and use it in GitHub Desktop.
Aspect 比が決まっている時の Sample Image を生成する。
# coding: utf-8
#!/Users/iwasakishuto/Github/portfolio/PyVideoEditor/.venv/bin/python
"""Generate sample image
Examples:
$ python gen_sample_size_image.py -W 1280 \
--aspect 16x9 \
-BC 64,64,64 \
-FC 239,239,239 \
--ttfontname /Users/iwasakishuto/Library/Fonts/数式フォントver1.5.ttf \
--fontsize 400
"""
import argparse
import os
import random
from typing import Any, Dict
from PIL import Image
from veditor.utils import check_font_size, draw_text_in_pil, now_str
rgbTp = lambda x: tuple(list(map(int, x.split(","))))
aspectTp = lambda x: list(map(int, x.split("x")))
if __name__ == "__main__":
parser = argparse.ArgumentParser(prog="", description="", add_help=True)
parser.add_argument("-W", "--width", type=int, default=1280)
parser.add_argument("--aspect", type=aspectTp, default="16x9")
parser.add_argument("-BC", "--bgcolor", type=rgbTp, default="64,64,64")
parser.add_argument("-FC", "--facecolor", type=rgbTp, default="239,239,239")
parser.add_argument("--ttfontname", type=str)
parser.add_argument("--fontsize", type=int, default=400)
parser.add_argument("-O", "--out", type=str, default=now_str() + ".png")
args = parser.parse_args()
out_path = args.out
w, h = args.aspect
width = args.width
height: float = width * (h / w)
bgColor = args.bgcolor
faceColor = args.facecolor
ttfontname = args.ttfontname
fontsize = args.fontsize
if ttfontname is None:
DefaultFontDir = os.path.join(os.path.expanduser("~"), "Library/Fonts/")
if os.path.exists(DefaultFontDir):
ttfontname: str = os.path.join(
DefaultFontDir,
random.choice([e for e in os.listdir(DefaultFontDir) if e.endswith(".ttf")]),
)
img = Image.new(size=(width, int(height)), mode="RGB", color=bgColor)
kwargs: Dict[str, Any] = dict(
text=f"{w}x{h}",
ttfontname=ttfontname,
textRGB=faceColor,
fontsize=fontsize,
)
tw, th = check_font_size(**kwargs)
img, _ = draw_text_in_pil(
img=img, xy=((width - tw) // 2, (int(height) - fontsize) // 2), **kwargs
)
img.save(out_path)
print(
f"""[IMAGE INFO]
* size (W,H): ({width},{height})
* ttfontname: {ttfontname}
* Saved at '{out_path}'
"""
)
@iwasakishuto
Copy link
Author

16x9 4x3 1x1
2021-10-22@05 02 18 2021-10-22@10 11 29 2021-10-22@10 11 49

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