jimp-dev / gifwrap

A Jimp-compatible library for working with GIFs

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

example of using jimp and gifwrap to resize and crop gif to gif

wobeng opened this issue · comments

Hi,

Does anyone have an example of using jimp and gifwrap to resize and crop gif to gif.

Thanks in advance

This isn't exactly what you are looking for, but these (typescript) functions can replace Jimp.read and Jimp.getBufferAsync to allow you to convert the first frame of a gif into a Jimp image and back to a buffer.

We use it like:


readImage(imageUrl)
.then((image) => image.cover(size.width, size.height))
.then((image) => getBuffer(image))
.then((imageBuffer) => {
  // now you can write the image somewhere
});

Note: will only work with the first frame....


/* This is a way of handing Jimp.read that will also take gif format.
   Ideally, we wouldn't need this, but Jimp cant handle gifs natively */
const readImage = (imageUrl: string): Promise<Jimp> => {
  var promise = new Promise<Jimp>((resolve, reject) => {
    Jimp.read(imageUrl)
      .then((jimp) => {
        resolve(jimp);
      })
      .catch((err) => {
        if (err.toString() === 'Unsupported MIME type: image/gif') {
          GifUtil.read(imageUrl)
            .then((gif) => {
              let image = GifUtil.copyAsJimp(Jimp, gif.frames[0]);
              resolve(image);
            })
            .catch((giferror) => {
              reject(giferror);
            });
        } else {
          reject(err);
        }
      });
  });
  return promise;
};

/* This is a way of handing Jimp.getBufferAsync that will also handle gif format.
   Ideally, we wouldn't need this, but Jimp cant handle gifs natively */
const getBuffer = (image: Jimp): Promise<Buffer> => {
  var promise = new Promise<Buffer>((resolve, reject) => {
    image
      .getBufferAsync(image._originalMime)
      .then((buffer) => {
        resolve(buffer);
      })
      .catch((err) => {
        if (err.toString() === 'Unsupported MIME type: image/gif') {
          let bitmap = new BitmapImage(image.bitmap);
          GifUtil.quantizeDekker(bitmap, 256);
          let newFrame = new GifFrame(bitmap);
          let gifCodec = new GifCodec();
          gifCodec
            .encodeGif([newFrame], {})
            .then((gif) => {
              resolve(gif.buffer);
            })
            .catch((giferror) => {
              reject(giferror);
            });
        } else {
          reject(err);
        }
      });
  });
  return promise;
};