How to use sharp - 10 common examples

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 gymnastjs / gymnast / test / screenshot / commands / compareScreenshot.js View on Github external
/* eslint-disable no-console, prefer-arrow-callback, prefer-rest-params */
const { existsSync } = require('fs')
const { resolve } = require('path')
const { moveSync } = require('fs-extra')
const sharp = require('sharp')
const { noop } = require('lodash')
const { getBrowserData } = require('../shared')

sharp.concurrency(1)

function isValid(
  assert,
  screenshot,
  filename,
  baseline,
  sessionId,
  browserName,
  callback = noop
) {
  if (screenshot.status !== 0) {
    console.log('Error saving screenshot...', screenshot)
    callback(false)
  }
  assert.compareScreenshot(filename, baseline, browserName, result => {
    callback(!!result)
github vseventer / sharp-cli / test / mocks / sharp.js View on Github external
// Strict mode.
'use strict'

// Package modules.
const sharp = require('sharp')
const sinon = require('sinon')

// Configure.
const methods = Object.getOwnPropertyNames(sharp.prototype)

// Patch methods, add reset and restore handlers.
methods.forEach((name) => sinon.spy(sharp.prototype, name))
sharp.prototype.reset = () => {
  methods.forEach((name) => sharp.prototype[name].resetHistory())
}
sharp.prototype.restore = () => {
  methods.forEach((name) => sharp.prototype[name].restore())
}

// Exports.
module.exports = sharp
github vseventer / sharp-cli / test / mocks / sharp.js View on Github external
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

// Strict mode.
'use strict'

// Package modules.
const sharp = require('sharp')
const sinon = require('sinon')

// Configure.
const methods = Object.getOwnPropertyNames(sharp.prototype)

// Patch methods, add reset and restore handlers.
methods.forEach((name) => sinon.spy(sharp.prototype, name))
sharp.prototype.reset = () => {
  methods.forEach((name) => sharp.prototype[name].resetHistory())
}
sharp.prototype.restore = () => {
  methods.forEach((name) => sharp.prototype[name].restore())
}

// Exports.
module.exports = sharp
github vseventer / sharp-cli / test / mocks / sharp.js View on Github external
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

// Strict mode.
'use strict'

// Package modules.
const sharp = require('sharp')
const sinon = require('sinon')

// Configure.
const methods = Object.getOwnPropertyNames(sharp.prototype)

// Patch methods, add reset and restore handlers.
methods.forEach((name) => sinon.spy(sharp.prototype, name))
sharp.prototype.reset = () => {
  methods.forEach((name) => sharp.prototype[name].resetHistory())
}
sharp.prototype.restore = () => {
  methods.forEach((name) => sharp.prototype[name].restore())
}

// Exports.
module.exports = sharp
github chromakode / time / src / renderGIF.js View on Github external
const gl = createGLContext(WIDTH_S, HEIGHT_S)
  if (!gl) {
    console.error('Unable to create GL context')
    process.exit(1)
  }

  const blendData = JSON.parse(result.result[0])
  const timePiece = time(blendData, gl)

  const gif = new GifEncoder(WIDTH, HEIGHT, {highWaterMark: 1024 * 1024})
  gif.pipe(fs.createWriteStream(outPath))
  gif.setRepeat(0)
  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,
github MarcusCemes / responsive-image-builder / lib / worker.js View on Github external
const sharp   = require('sharp');
const path    = require('path');
const fs      = require('fs-extra');
const Export  = require(path.join(__dirname, 'export.js'));
const imagemin = require('imagemin');
const pngquant = require('imagemin-pngquant');
const mozjpeg = require('imagemin-mozjpeg');
const cluster = require('cluster');
let debug; try { debug = require('debug')('RIBworker:' + cluster.worker.id) } catch (err) { debug = () => {} };

let config;
let uncompressed_bytes = 0;
let compressed_bytes = 0;
let raw_bytes = 0;
sharp.concurrency(1);  // Only permit one thread

process.on('message', async function (packet) {
  if (packet.code === 'EXIT') {
    // Send worker stats and exit
    process.send({code: 'SUM', data: {uncompressed_bytes: uncompressed_bytes, compressed_bytes: compressed_bytes, raw_bytes: raw_bytes}});
    process.exit(0);

  } else if (packet.code === 'SETUP') {

    config = packet.data;

  } else if (packet.code === 'ACCEL') {
    sharp.concurrency(config.max_threads);  // Speed up the end, as there are fewer cores

  } else if (packet.code === 'TASK') {
    let result;
github MarcusCemes / responsive-image-builder / lib / worker.js View on Github external
process.on('message', async function (packet) {
  if (packet.code === 'EXIT') {
    // Send worker stats and exit
    process.send({code: 'SUM', data: {uncompressed_bytes: uncompressed_bytes, compressed_bytes: compressed_bytes, raw_bytes: raw_bytes}});
    process.exit(0);

  } else if (packet.code === 'SETUP') {

    config = packet.data;

  } else if (packet.code === 'ACCEL') {
    sharp.concurrency(config.max_threads);  // Speed up the end, as there are fewer cores

  } else if (packet.code === 'TASK') {
    let result;

    if (!config) {
      result = {code: 'NOPT', data: packet.data};
    } else {

      try {

        exp = await process_image(packet.data, config);

        result = { code: 'OK', data: exp };
      } catch (err) {
        if (err instanceof Error) err = new_error(err);
        result = {code: 'ERROR', data: packet.data, error: err};
github g-wilson / wrender / src / middleware / handleRecipe.js View on Github external
const image = sharp();

    source.on('error', err => next(err));
    image.on('error', err => source.emit('error', err));
    image.on('finish', () => fs.unlink(req.tempfile, () => {})); // eslint-disable-line no-empty-function

    // Convert to JPEG? GIFs become still-frames
    const convertToJPEG = (
      (config.convertGIF && type.mime === 'image/gif') ||
      (config.convertPNG && type.mime === 'image/png')
    );
    if (mimetype !== 'image/jpeg' && convertToJPEG) {
      mimetype = 'image/jpeg';
      image.background({ r: 0, g: 0, b: 0, alpha: 0 });
      image.flatten();
      image.toFormat(sharp.format.jpeg);
    }

    // Respect EXIF orientation headers
    if (mimetype === 'image/jpeg') {
      image.rotate();
    }

    // Apply recipe
    recipe.process(image, Object.freeze(Object.assign({}, req.params, {
      query: req.query,
      path: req.path,
      originalUrl: req.originalUrl,
    })));

    // Always apply compression at the end
    if (mimetype === 'image/jpeg') {
github RocketChat / Rocket.Chat / packages / rocketchat-file-upload / server / lib / FileUpload.js View on Github external
s.metadata(Meteor.bindEnvironment((err, metadata) => {
			if (!metadata) {
				metadata = {};
			}

			s.toFormat(sharp.format.jpeg)
				.resize(Math.min(height || 0, metadata.width || Infinity), Math.min(height || 0, metadata.height || Infinity))
				.pipe(sharp()
					.resize(height, height)
					.background('#FFFFFF')
					.embed()
				)
				// Use buffer to get the result in memory then replace the existing file
				// There is no option to override a file using this library
				.toBuffer()
				.then(Meteor.bindEnvironment((outputBuffer) => {
					fs.writeFile(tempFilePath, outputBuffer, Meteor.bindEnvironment((err) => {
						if (err != null) {
							console.error(err);
						}
						const { size } = fs.lstatSync(tempFilePath);
						this.getCollection().direct.update({ _id: file._id }, { $set: { size } });
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

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 3 months ago

Package Health Score

94 / 100
Full package analysis