How to use image-size - 10 common examples

To help you get started, we’ve selected a few image-size 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 brave / ethereum-remote-client / test / screens / new-ui.js View on Github external
async function generateGif(){
  // calculate screenshot size
  const screenshot = await driver.takeScreenshot()
  const pngBuffer = Buffer.from(screenshot, 'base64')
  const size = sizeOfPng.calculate(pngBuffer)

  // read only the english pngs into gif
  const encoder = new GIFEncoder(size.width, size.height)
  const stream = pngFileStream('./test-artifacts/screens/* (en).png')
    .pipe(encoder.createWriteStream({ repeat: 0, delay: 1000, quality: 10 }))
    .pipe(fs.createWriteStream('./test-artifacts/screens/walkthrough (en).gif'))

  // wait for end
  await pify(endOfStream)(stream)
}
github opencollective / opencollective-website / server / src / controllers / banner.js View on Github external
.then(responses => {
      const images = [];
      for (let i=0;i 0 && posX + avatarWidth + margin > imageWidth) {
          posY += (avatarHeight + margin);
          posX = margin;
        }
        const image = `<img xlink:href="data:${contentType};base64,${base64data}" height="${avatarHeight}" width="${avatarWidth}" y="${posY}" x="${posX}">`;
        const imageLink = `<a id="${user.username}" xlink:href="${website.replace(/&amp;/g,'&amp;')}">${image}</a>`;
        images.push(imageLink);
        posX += avatarWidth + margin;
      }
github ditojs / dito / packages / server / src / storage / ImageSizeTransform.js View on Github external
_transform(chunk, encoding, callback) {
    this.length += chunk.length
    if (!this.done) {
      if (this.limit && this.length >= this.limit) {
        this.error = new Error('Unable do determine image size: Limit reached')
        this.done = true
      } else {
        this.buffer = this.buffer
          ? Buffer.concat([this.buffer, chunk])
          : chunk
        try {
          const size = imageSize(this.buffer)
          this.error = null
          this.done = true
          this.emit('size', size)
        } catch (err) {
          // Do not emit the error right away. Instead keep trying when new
          // data is received until either the image size can be determined,
          // or the end of the stream is reached and `_flush()` is called.
          this.error = err
        }
      }
    }
    callback(null, chunk)
  }
github webhintio / hint / packages / hint-manifest-icons / src / hint.ts View on Github external
/**
             * sizes can be the string 'any' OR
             * space seperated list of
             * two non-negative integers without leading 0s and separated by 'x' like 144x144
             */
            if (iconSizes === 'any') {
                return false;
            }

            // Working on local environment so no access to the real image for further checking
            if (!iconRawData) {
                return true;
            }

            const specifiedSizes = iconSizes.split(' ');
            const realImage = getImageData(iconRawData);

            /**
             * Do not report if one of the specified size match real icon size
             */
            const sizesMatch = specifiedSizes.some((specifiedSize) => {
                const [widthString, heightString] = specifiedSize.split('x');
                const specifiedWidth = parseInt(widthString);
                const specifiedHeight = parseInt(heightString);

                return specifiedWidth === realImage.width && specifiedHeight === realImage.height;
            });

            if (!sizesMatch && realImage.width && realImage.height) {
                const message = getMessage('realImageSizeNotMatch', context.language, [realImage.width.toString(), realImage.height.toString(), specifiedSizes.toString()]);

                context.report(
github opencollective / opencollective-frontend / src / server / lib / image-generator.js View on Github external
if (!responses[i]) continue;
        const { headers } = responses[i][0];
        const rawData = responses[i][1];
        const user = users[i];
        if (!user) continue;

        const contentType = headers['content-type'];
        const website =
          options.linkToProfile || !user.website
            ? `${WEBSITE_URL}/${user.slug}`
            : user.website;
        const base64data = Buffer.from(rawData).toString('base64');
        let avatarWidth = avatarHeight;
        try {
          // We make sure the image loaded properly
          const dimensions = sizeOf(rawData);
          avatarWidth = Math.round(
            (dimensions.width / dimensions.height) * avatarHeight,
          );
        } catch (e) {
          // Otherwise, we skip it
          logger.warn(
            'Cannot get the dimensions of the avatar of %s.',
            user.slug,
            { image: user.image },
          );
          continue;
        }

        if (imageWidth > 0 && posX + avatarWidth + margin > imageWidth) {
          posY += avatarHeight + margin;
          posX = margin;
github triplecanopy / b-ber / packages / b-ber-tasks / src / cover / index.js View on Github external
generateCoverXHTML() {
        // get the image dimensions, and pass them to the coverSVG template
        const { width, height } = sizeOf(this.coverImagePath)
        const href = `images/${encodeURIComponent(this.coverEntry)}`
        const svg = Xhtml.cover({ width, height, href })

        // set the content string to be written once resolved
        this.coverXHTMLContent = Template.render(svg, Xhtml.body())
        log.info('cover build [cover.xhtml]')
    }
github jmerle / png-to-box2d / src / commands / generate.ts View on Github external
'0',
      '--output',
      tracedPath,
      thresholdedAlphaPath,
    );

    // Parse the traced PostScript file and convert it to a JSON file containing all shapes
    const shapesPath = this.getTempPath(inputPath, 'shapes.json');
    this.info(`Converting ${tracedPath} to shape paths`);
    const shapes = await postScriptToShapes(tracedPath, shapesPath, tolerance);

    // Convert the shape data into triangle data
    this.info(`Converting shape paths to triangulated shapes`);
    const triangles = await shapesToTriangulatedShapes(shapes);

    const inputDimensions = await imageSize(inputPath);

    const data: any = {
      width: inputDimensions.width,
      height: inputDimensions.height,
      shapes: triangles,
    };

    if (this.flags.path) {
      const paths: Point[][] = [];

      for (const shape of shapes) {
        const currentPath: Point[] = [];

        if (shape.mainPath !== null) {
          for (const point of shape.mainPath) {
            currentPath.push({
github webhintio / hint / packages / hint-image-optimization-cloudinary / src / hint.ts View on Github external
const analyzeImage = (fetchEnd: FetchEnd) => {
            if (!configured) {
                return;
            }

            const { response } = fetchEnd;

            try {
                // TODO: Find a better way than doing this to detect if it's an image
                getImageData(response.body.rawContent);

                uploads.push(processImage(fetchEnd));
            } catch (e) {
                if (e instanceof TypeError) {
                    // Not an image, ignoring
                }
            }
        };
github HuasoFoundries / systemjs-less-plugin / imagesize.js View on Github external
typeMap = {};


// load all available handlers

handlers.bmp = require('image-size/lib/types/bmp');
handlers.gif = require('image-size/lib/types/gif');
handlers.jpg = require('image-size/lib/types/jpg');
handlers.png = require('image-size/lib/types/png');
handlers.psd = require('image-size/lib/types/psd');
handlers.svg = require('image-size/lib/types/svg');
handlers.tiff = require('image-size/lib/types/tiff');
handlers.webp = require('image-size/lib/types/webp');

// load all available handlers
types.forEach(function (type) {
    typeMap[type] = handlers[type].detect;
});

var detector = function (buffer, filepath) {
    var type, result;
    for (type in typeMap) {
        result = typeMap[type](buffer, filepath);
        if (result) {
            return type;
        }
    }
};


// Maximum buffer size, with a default of 128 kilobytes.
// TO-DO: make this adaptive based on the initial signature of the image
github opencollective / opencollective-website / server / src / controllers / banner.js View on Github external
request({url: imageUrl, encoding: null}, (err, r, data) =&gt; {
        if (err) {
          return res.status(500).send(`Unable to fetch ${imageUrl}`);
        }
        const contentType = r.headers['content-type'];

        const imageHeight = Math.round(maxHeight / 2);
        let imageWidth = 64;
        if (tier.match(/sponsor/)) {
          try {
            const dimensions = sizeOf(data);
            imageWidth = Math.round(dimensions.width / dimensions.height * imageHeight);
          } catch (e) {
            console.error("Unable to get image dimensions for ", imageUrl);
            return res.status(500).send(`Unable to fetch ${imageUrl}`);
          }
        }

        const base64data = new Buffer(data).toString('base64');
        const svg = `<svg height="${imageHeight}" width="${imageWidth}" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg">
          <image xlink:href="data:${contentType};base64,${base64data}" height="${imageHeight}" width="${imageWidth}"></image>
        </svg>`;
        res.setHeader('Cache-Control', 'public, max-age=300');
        res.setHeader('content-type','image/svg+xml;charset=utf-8');
        return res.send(svg);
      });
    } else {

image-size

get dimensions of any image file

MIT
Latest version published 11 months ago

Package Health Score

76 / 100
Full package analysis