libvips/lua-vips

gif and animated webp support

Closed this issue · 3 comments

Hi,

is there any gif or animated webp manipulation support? can I have an example to resize or crop a gif image?

Hello @Ara4Sh,

Sure, to resize a GIF something like:

local image = vips.Image.thumbnail("somefile.jpg", 128, {n = -1})

The n = -1 means process all frames. You can use page = and n = to set a start page and number of pages to process. It'll work for any multi-page format.

Cropping a GIF is a little harder: you need to load the image, split into frames, crop each frame, reassemble, and set the page-height.

Here's a gif crop inn python, it should be easy to make a lua version:

#!/usr/bin/python3

import sys
import pyvips

# load all frames from file using n=-1
image = pyvips.Image.new_from_file(sys.argv[1], n=-1)
outfile = sys.argv[2]
left = int(sys.argv[3])
top = int(sys.argv[4])
width = int(sys.argv[5])
height = int(sys.argv[6])

# the image will be a very tall, thin strip, with "page-height" being the height
# of each frame
page_height = image.get("page-height")
n_frames = image.height // page_height

# make a list of new frames
frames = [image.crop(left, i * page_height + top, width, height)
          for i in range(0, n_frames)]
          
image = pyvips.Image.arrayjoin(frames, across=1)

# set the new page-height
image.set("page-height", height)

image.write_to_file(outfile)

In Lua:

#!/usr/bin/luajit

vips = require 'vips'

-- load all frames from file using n=-1
image = vips.Image.new_from_file(arg[1], {n = -1})

left = tonumber(arg[3])
top = tonumber(arg[4])
width = tonumber(arg[5])
height = tonumber(arg[6])
    
-- the image will be a very tall, thin strip, with "page-height" being the 
-- height of each frame
page_height = image:get('page-height')
n_frames = image:height() / page_height

-- make a list of new frames
frames = {}
for i = 0, n_frames - 1 do
    table.insert(frames, image:crop(left, i * page_height + top, width, height))
end

image = vips.Image.arrayjoin(frames, {across = 1})

-- set the new page-height
image:set("page-height", height)

image:write_to_file(arg[2])

@jcupitt thank you very much