How to use the sharp function in sharp

To help you get started, we’ve selected a few sharp examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github chromakode / time / src / renderGIF.js View on Github external
gif.writeHeader()

  sharp.cache(false)  // Reduce memory usage

  const totalFrames = 2 * FRAMES - 1
  for (let i = 0; i < totalFrames; i++) {
    // Render frame
    const y = i < FRAMES ? i / FRAMES : 2 - i / FRAMES
    timePiece.renderFrame(.5, y)

    // Get frame data
    let pixels = new Uint8Array(WIDTH_S * HEIGHT_S * 4)
    gl.readPixels(0, 0, WIDTH_S, HEIGHT_S, gl.RGBA, gl.UNSIGNED_BYTE, pixels)

    // Resize and flip (otherwise gifs come out upside-down!?)
    let framePixels = await sharp(Buffer.from(pixels.buffer), {
        raw: {
          width: WIDTH_S,
          height: HEIGHT_S,
          channels: 4,
        }
    })
      .resize(WIDTH, HEIGHT)
      .flip()
      .toBuffer()

    // Add to GIF (slow!)
    gif.setDelay(i === 0 ? PAUSE : DURATION / FRAMES)
    gif.addFrame(framePixels)

    // This seems to help keep memory usage down.
    pixels = null
github UnicornTranscoder / UnicornLoadBalancer / src / core / images.js View on Github external
format: false, // png / jpg / webp

                // Force upscale
                upscale: false,

                // User parameters
                ...parameters
            }

            if (!params.width || !params.height)
                return reject('Size not provided');

            // Load sharp
            let s = false;
            try {
                s = sharp().on('error', err => { return reject(err); });
            }
            catch (e) {
                return reject(e)
            }
            if (!s)
                return reject(e)

            // Resize parameters
            const opt = {
                ...((params.upscale) ? { withoutEnlargement: !!params.upscale } : {})
            }

            // Resize based on width
            try {
                if (params.minSize === 1)
                    s.resize(params.width, null, opt);
github dosyago / supreme-architect / zombie-lord / screenShots.js View on Github external
export async function forExport({frame, connection}) {
  let {img} = frame;
  // FIXME : CPU issues
  img = Buffer.from(img, 'base64');
  if ( ! connection.isSafari ) {
    img = await sharp(img).webp(WEBP_OPTS).toBuffer();
  }
  img = img.toString('base64');
  frame.img = img;
  return frame;
}
github reactioncommerce / reaction / imports / plugins / core / files / server / no-meteor / setUpFileCollections.js View on Github external
async transformWrite(fileRecord) {
        if (!transform) return null;

        const { size, mod, format, type } = transform;

        // Need to update the content type and extension of the file info, too.
        // The new size gets set correctly automatically by FileCollections package.
        fileRecord.type(type, { store: name });
        fileRecord.extension(format, { store: name });

        // resizing image, adding mod, setting output format
        return sharp().resize(size, size)[mod]().toFormat(format);
      }
    })
github artsmia / lume / image-tiler / iiif / info.js View on Github external
let url = `https://s3.amazonaws.com/${organizationId}/${imageId}/original`

    if (process.env.FILE_STORAGE === "offline") {
      url = `http://localhost:5000/static/${imageId}/original.jpeg`
    }

    const response = await fetch(
      url, {
      method: 'GET'
    })


    const buffer = await response.buffer()

    let meta = await sharp(buffer).metadata()


    const info = {
      "@context": "http://iiif.io/api/image/2/context.json",
      "@id": `http://localhost:3000/iiif/${imageId}`,
      "protocal": "http://iiif.io/api/image",
      width: meta.width,
      height: meta.height,
      profile: [ "http://iiif.io/api/image/2/level2.json" ]
    }
    res.send(info)

  } catch (ex) {
    console.error(ex)
  }
}
github cncf / landscapeapp / tools / generateMosaic.js View on Github external
}
    })
    const tile = tiles[tileIdx]
    tiles = tiles.filter((_, idx) => idx !== tileIdx)
    for (let i = 0; i < tileHeight; i++) {
      for (let j = 0; j < tileWidth; j++) {
        const rightIdx = (tileWidth * i + j) * 3
        const leftIdx = (width * (y * tileHeight + i) + x * tileWidth + j) * 3 ;
        newPngData[leftIdx] = tile.buffer[rightIdx]
        newPngData[leftIdx + 1] = tile.buffer[rightIdx + 1]
        newPngData[leftIdx + 2] = tile.buffer[rightIdx + 2]
      }
    }
  })

  await sharp(Buffer.from(newPngData), { raw: { width, height, channels: 3 }})
          .toFile(path.resolve(projectPath, 'dist', `${mosaic.split('.')[0]}-mosaic.png`))
}
github luizbatanero / gostack-meetapp / api / src / app / controllers / AvatarController.js View on Github external
async store(req, res) {
    const { originalname: name, filename, path } = req.file;

    const buffer = await sharp(path)
      .resize(350, 350)
      .toBuffer();

    fs.writeFile(path, buffer, err => {
      if (err) throw err;
    });

    const file = await File.create({
      name,
      path: filename,
    });

    return res.json(file);
  }
}
github Tibus / TouchScreen-For-NanoDLP / src / plugins / nextion / nextionService.js View on Github external
async displayBlackWhiteImage(buffer, positionX, positionY, width){
    //debug(url);
    const image = sharp(buffer);
    
    image.metadata()
      .then((metadata) => {        
        image
          .rotate((metadata.width>=metadata.height)?0:90)
          .resize(width)
          .extractChannel(1)
          //.toFile(__dirname+"/../1.min.png");
          .raw()
          .toBuffer(async (err, data, info)=> {
            debug(err);
            debug(data.length);
            debug(data);
            debug(info);

            //debug("fill", info.width, info.height, "0");
github ionic-team / cordova-res / src / image.ts View on Github external
export async function readSourceImage(platform: Platform, type: ResourceType, src: string, errstream?: NodeJS.WritableStream): Promise {
  const image = sharp(await readFile(src));
  const metadata = await RASTER_RESOURCE_VALIDATORS[type](src, image);

  debug('Source image for %s: %O', type, metadata);

  return {
    platform,
    resource: type,
    type: SourceType.RASTER,
    src,
    image: { src, pipeline: image, metadata },
  };
}
github staylor / graphql-wordpress / packages / draft / src / server / uploads / types / Image.js View on Github external
async save(file: FileUpload, cb: Callback) {
    await this.setFileProps(file);

    const finalPath = path.join(this.destination, this.fileName);
    const original = { fileName: this.fileName, width: 0, height: 0, fileSize: 0 };
    const imageMeta = sharp().on('info', info => {
      original.width = info.width;
      original.height = info.height;
      original.fileSize = info.size;
    });

    const outStream = fs.createWriteStream(finalPath);
    outStream.on('error', cb);
    outStream.on('finish', async () => {
      const sizes = this.settings.crops.map(({ width, height }) => {
        if (width < original.width && height > original.height) {
          return [width];
        } else if (height < original.height && width > original.width) {
          return [null, height];
        }
        return [width, height];
      });

sharp

High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images

Apache-2.0
Latest version published 1 month ago

Package Health Score

94 / 100
Full package analysis