gif_to_360: retry with sharp scaling when too large; add new GIF
Smooth upscaling blends pixels and dithers per-frame palettes, which breaks GIF delta compression (7.2 MB source -> 24.9 MB). Nearest- neighbour scaling keeps it at 7.2 MB, under the 11.5 MB flash limit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
15b4ef5cef
commit
b2f6a52902
3 files changed
+9
-2
No files matched your search
+8
-2
@@ -2,6 +2,7 @@
|
||||
|
||||
Each frame is scaled so the GIF covers 360x360, then center-cropped. Frame durations and looping are kept.
|
||||
Pillow stores only the changed part of each frame, which keeps files small.
|
||||
If the result is too large, the GIF is redone with sharp (nearest-neighbour) scaling, which is often much smaller.
|
||||
|
||||
Usage:
|
||||
pip install pillow
|
||||
@@ -19,7 +20,7 @@ SIZE = 360
|
||||
MAX_BYTES = 11_500_000
|
||||
|
||||
|
||||
def convert(src, dst):
|
||||
def convert(src, dst, resample=Image.LANCZOS):
|
||||
im = Image.open(src)
|
||||
w, h = im.size
|
||||
scale = max(SIZE / w, SIZE / h)
|
||||
@@ -31,7 +32,7 @@ def convert(src, dst):
|
||||
durations.append(frame.info.get("duration", im.info.get("duration", 100)) or 100)
|
||||
rgba = frame.convert("RGBA") # fully composited frame
|
||||
if (nw, nh) != (w, h):
|
||||
rgba = rgba.resize((nw, nh), Image.LANCZOS)
|
||||
rgba = rgba.resize((nw, nh), resample)
|
||||
rgba = rgba.crop((left, top, left + SIZE, top + SIZE))
|
||||
# the device shows the GIF on black: flatten transparency onto black
|
||||
bg = Image.new("RGBA", rgba.size, (0, 0, 0, 255))
|
||||
@@ -41,6 +42,11 @@ def convert(src, dst):
|
||||
frames[0].save(dst, save_all=True, append_images=frames[1:], duration=durations,
|
||||
loop=im.info.get("loop", 0), optimize=True, disposal=1)
|
||||
size = os.path.getsize(dst)
|
||||
if size > MAX_BYTES and resample != Image.NEAREST and (nw, nh) != (w, h):
|
||||
# smooth scaling blends pixels, so frames change everywhere and the per-frame palettes get
|
||||
# dithered: the GIF's delta compression stops working. Sharp scaling keeps it small.
|
||||
print(f"{os.path.basename(src)}: {size / 1e6:.2f} MB with smooth scaling, retrying with sharp scaling")
|
||||
return convert(src, dst, Image.NEAREST)
|
||||
fps = len(durations) * 1000 / max(1, sum(durations))
|
||||
note = "" if size <= MAX_BYTES else " ** TOO LARGE for the device (max 11.5 MB) **"
|
||||
print(f"{os.path.basename(src)}: {w}x{h}, {len(frames)} frames, {fps:.1f} fps "
|
||||
|
||||
Reference in new issue
Block a user