npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

sharp-gif

v0.1.7

Published

Generate animated GIF/WebP for sharp base on gif-encoder.

Downloads

499

Readme

Note: you can try sharp-gif2 first, it is base on gifenc, has faster encoding speed.


sharp-gif

Generate animated GIF/WebP for sharp base on gif-encoder.

+ + =

Install

npm install sharp-gif

Usage

Generate animated GIF

const fs = require("fs");
const sharp = require("sharp");
const GIF = require("sharp-gif");

(async () => {
  // Simple use case
  const image = await GIF
    .createGif()
    .addFrame([
      sharp("./frames/0000.png"),
      sharp("./frames/0001.png"),
      sharp("./frames/0002.png"),
    ])
    .toSharp();
  image.toFile("./frames.gif");
  // Can also generate an animated WebP
  image.toFile("./frames.webp");

  // Options
  const gif = GIF.createGif({
    // GifEncoder constructor options
    gifEncoderOptions: { highWaterMark: 64 },
    // Sharp constructor options
    sharpOptions: {},
    // Custom size
    width: 300,
    height: 200,
    // Amount of milliseconds to delay between frames
    delay: 200,
    // Amount of times to repeat GIF
    repeat: 0,
    // GIF quality
    quality: 10,
    // Define the color which represents transparency in the GIF.
    transparent: "#FFFFFF",
    // Resize all frame to `largest` or `smallest`
    resizeTo: "largest",
    // Resize by `zoom` or `crop`
    resizeType: "zoom",
    // Options for sharp.resize()
    resizeOptions: {},
    // Background option for sharp.extend()
    extendBackground: { r: 0, g: 0, b: 0, alpha: 0 },
  });
  gif.addFrame(sharp("./1.png"));
  gif.addFrame(sharp("./2.png"));
  const image = await gif.toSharp();
  image.toFile("./frames.gif");

  // Trace encoding progress
  const image = await GIF
    .createGif()
    .addFrame(
      fs.readdirSync("./frames")
        .map((file) => sharp(`./frames/${file}`))
    )
    .toSharp(({ total, encoded }) => {
      console.log(`${encoded}/${total}`);
    });
  image.toFile("./frames.gif");

  // You can even concat animated GIFs
  const image = await GIF
    .createGif({ transparent: "#FFFFFF", })
    .addFrame([
      sharp("./1.gif", { animated: true }),
      sharp("./2.gif", { animated: true }),
    ])
    .toSharp();
  image.toFile("./concat.gif");
})();

Processing GIF frames

const sharp = require("sharp");
const GIF = require("sharp-gif");

(async () => {
  const reader = GIF.readGif(sharp("./2.gif", { animated: true }));
  const frames = await reader.toFrames();
  frames.forEach((frame, index) => {
    // You can process each frame here

    // Or just simple output frame
    frame.toFile(`./output/${("000" + index).substr(-4)}.png`);
  });

  const gif = await reader.toGif({ transparent: "#FFFFFF", });
  const image = await gif.toSharp();
  image.toFile("./output/remake.gif");
})();

API

GIF.createGif(options?: Object): Gif

  • options Object (optional)
    • gifEncoderOptions Object (optional) - GifEncoder constructor options.
      • highWaterMark Number - Number, in bytes, to store in internal buffer. Defaults to 64kB.
    • sharpOptions Object (optional) - Sharp constructor options.
    • width Number (optional) - Width, in pixels, of the GIF to output.
    • height Number (optional) - Height, in pixels, of the GIF to output.
    • delay Number (optional) - Amount of milliseconds to delay between frames.
    • repeat Number (optional) - Amount of times to repeat GIF. Default by 0, loop indefinitely.
    • quality Number (optional) - GIF quality. 1 is best colors and worst performance, 20 is suggested maximum but there is no limit. Default by 10.
    • transparent String (optional) - Define the color which represents transparency in the GIF.
    • resizeTo ("largest" | "smallest") (optional) - Resize all frame to the largest frame or smallest frame size. Default by largest.
    • resizeType ("zoom" | "crop") (optional) - zoom use sharp.resize(), crop use sharp.extend() and sharp.extract().
    • resizeOptions sharp.ResizeOptions (optional) - Options for sharp.resize().
    • extendBackground sharp.Color (optional) - Background option for sharp.extend().

Returns Gif - Return a instance of Gif Contains the following methods:

gif.addFrame(frame: Sharp | Sharp[]): Gif

  • frame (Sharp | Sharp[]) - An instance of Sharp, or an array of instance of Sharp.

Returns Gif - Return the Gif instance for chaining.

gif.toSharp(progress?: Function, encoder?: GifEncoder): Promise<Sharp>

Encode all frames and resolve with an animated Sharp instance.

  • progress (info: Object) => void (optional) - Frames encoding progress.
    • info Object - Note that the frames count contains GIF header end footer (as 2 frames).
      • total Number - Total frames count.
      • encoded Number - Encoded frames count.
  • encoder GifEncoder (optional) - Custom GifEncoder.

Returns Promise<Sharp> - Resolve with an instance of Sharp.

gif.toBuffer(progress?: Function, encoder?: GifEncoder): Promise<Buffer>

Encode all frames and resolve with an animated GIF buffer.

gif.getEncoder(width: Number, height: Number, options?: Object): GIFEncoder

Return a new instance of GIFEncoder. See new GifEncoder.

GIF.readGif(image: Sharp): GifReader

  • image Sharp - An instance of Sharp

Returns GifReader - Return a instance of GifReader Contains the following methods:

reader.toFrames(): Promise<Sharp[]>

Cut GIF frames.

Returns Promise<Sharp[]> - Resolve with cutted frames (an array of instance of Sharp).

reader.toGif(options?: Object): Promise<Gif>

Create Gif from cutted frames.

  • options Object (optional) - Options for createGif(). See createGif.

Returns Promise<Gif> - Resolve with an instance of Gif.

A shortcut to create a Gif with the cutted frames, equal to:

GIF.createGif(options).addFrame(reader.frames || (await reader.toFrames()));

Change Log

0.1.3

  • Feature: Add GifReader for cutting frames.

0.1.5

  • Fix: Resize bug.