jimp-dev / gifwrap

A Jimp-compatible library for working with GIFs
MIT License
73 stars 17 forks source link

Editing gif frames with Jimp -> The value of "offset" is out of range #24

Open Bitware32 opened 4 years ago

Bitware32 commented 4 years ago

Using this gif with the code below https://media1.giphy.com/media/HnKSuvC39SdOM/source.gif

I am getting this error on GifUtil.write():

RangeError [ERR_OUT_OF_RANGE]: The value of "offset" is out of range. It must be >= 0 and <= 43818. Received 43820

Is this a bug or am I doing something wrong? I'm trying to downsize the gif to 160x160px.

var filePath = "pathtofile.gif"

await GifUtil.read(filePath)
.then(async inputGif => {
    //Loop through each frame
    for (var i=0; i<inputGif.frames.length; i++){
        //Modify the frame image buffer with jimp
        var newImgBuffer = await GifUtil.copyAsJimp(jimp, inputGif.frames[i])
        .resize(160, 160) // resize
        .getBufferAsync(jimp.AUTO)

        inputGif.frames[i].bitmap.height = 160
        inputGif.frames[i].bitmap.width = 160
        inputGif.frames[i].bitmap.data = newImgBuffer
    }

    //Pass inputGif to write() to preserve the original GIF's specs.
    return GifUtil.write(filePath, inputGif.frames, inputGif)
});
paintoshi commented 1 year ago

Probably not relevant anymore but here is what worked for me. However, some GIFs turns into a mess. Destroyed colors and play too fast. I don't know what's wrong with it.

import { BitmapImage, GifFrame, GifUtil, GifCodec } from 'gifwrap'

const resizeFrame = async (frame, width, height) => {
  try {
    const image = await GifUtil.copyAsJimp(Jimp, frame)
    const resizedGif = await image.resize(width, height)
    const bitmap = new BitmapImage(resizedGif.bitmap)
    GifUtil.quantizeDekker(bitmap, 256) // reduce the colors added by Jimp back to 256
    return new GifFrame(bitmap)
  } catch (e) {
    console.error("Resizing gifwrap frame failed")
    console.error(e)
  }
}

const resizeGif = async (file, width, height) => {
  try {
    const gif = await GifUtil.read(file.buffer)
    const uresolvedFrames = gif.frames.map(async (frame) => {
      const resizedFrame = await resizeFrame(frame, width, height)
      return resizedFrame
    })
    const newFrames = await Promise.all(uresolvedFrames)
    const codec = new GifCodec()
    const buffer = (await codec.encodeGif(newFrames, { loops: 0 })).buffer
    return buffer
  } catch (e) {
    console.error("Resizing gif failed")
    console.error(e)
  }
}

Here is a gif that does NOT work. test3

Turns into this: fail