• Stars
    star
    120
  • Rank 286,638 (Top 6 %)
  • Language
    JavaScript
  • License
    BSD 2-Clause "Sim...
  • Created almost 9 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A JavaScript client library for generating image URLs with imgix

imgix logo

@imgix/js-core is a JavaScript library for generating image URLs with imgix that can be used in browser or server-side settings.

NPM Version Build Status Monthly Downloads Minified Size License FOSSA Status


Installing

@imgix/js-core can be installed via npm:

npm install @imgix/js-core

Usage

Depending on your module system, using @imgix/js-core is done a few different ways. The most common entry point will be the ImgixClient class. Whenever you provide data to ImgixClient, make sure it is not already URL-encoded, as the library handles proper encoding internally.

CommonJS

const ImgixClient = require('@imgix/js-core');

const client = new ImgixClient({
  domain: 'testing.imgix.net',
  secureURLToken: '<SECURE TOKEN>',
});

const url = client.buildURL('/path/to/image.png', {
  w: 400,
  h: 300,
});

console.log(url); // => "https://testing.imgix.net/users/1.png?w=400&h=300&s=โ€ฆ"

ES6 Modules

import ImgixClient from '@imgix/js-core';

const client = new ImgixClient({
  domain: 'testing.imgix.net',
  secureURLToken: '<SECURE TOKEN>',
});

const url = client.buildURL('/path/to/image.png', { w: 400, h: 300 });
console.log(url); // => 'https://testing.imgix.net/users/1.png?w=400&h=300&s=โ€ฆ'

In-browser

var client = new ImgixClient({
  domain: 'testing.imgix.net',
  // Do not use signed URLs with `secureURLToken` on the client side,
  // as this would leak your token to the world. Signed URLs should
  // be generated on the server.
});

var url = client.buildURL('/path/to/image.png', { w: 400, h: 300 });
console.log(url); // => "https://testing.imgix.net/users/1.png?w=400&h=300"

Configuration

The following options can be used when creating an instance of ImgixClient:

  • domain: String, required. The imgix domain that will be used when constructing URLs. Defaults to null.
  • useHTTPS: Boolean. Specifies whether constructed URLs should use the HTTPS protocol. Defaults to true.
  • includeLibraryParam: Boolean. Specifies whether the constructed URLs will include an ixlib parameter. Defaults to true.
  • secureURLToken: String. When specified, this token will be used to sign images. Read more about securing images on the imgix Docs site. Defaults to null.
    • โš ๏ธ The secureURLToken option should only be used in server-side applications to prevent exposing your secure token. โš ๏ธ

API

ImgixClient.buildURL(path, params, options)

  • path: String, required. A full, unencoded path to the image. This includes any additional directory information required to locate the image within a source.
  • params: Object. Any number of imgix rendering API parameters.
  • options: Object. Any number of modifiers, described below:
    • disablePathEncoding: Boolean. Disables encoding logic applied to the image path.
    • encoder: Function. Applies custom logic to encode the image path and query parameters.

Construct a single image URL by passing in the image path and any rendering API parameters.

const client = new ImgixClient({
  domain: 'testing.imgix.net',
});

const url = client.buildURL('folder/image.jpg', {
  w: 1000,
});

Returns: an image URL as a string.

https://testing.imgix.net/folder/image.jpg?w=1000&ixlib=js-...

ImgixClient.buildSrcSet(path, params, options)

The @imgix/js-core module allows for generation of custom srcset attributes, which can be invoked through buildSrcSet(). By default, the srcset generated will allow for responsive size switching by building a list of image-width mappings.

const client = new ImgixClient({
  domain: 'testing.imgix.net',
  secureURLToken: 'my-token',
});

const srcset = client.buildSrcSet('image.jpg');

console.log(srcset);

Returns: A srcset attribute value as a string.

https://testing.imgix.net/image.jpg?w=100&s=e2e581a39c917bdee50b2f8689c30893 100w,
https://testing.imgix.net/image.jpg?w=116&s=836e0bc15da2ad74af8130d93a0ebda6 116w,
https://testing.imgix.net/image.jpg?w=134&s=688416d933381acda1f57068709aab79 134w,
                                            ...
https://testing.imgix.net/image.jpg?w=7400&s=91779d82a0e1ac16db04c522fa4017e5 7400w,
https://testing.imgix.net/image.jpg?w=8192&s=59eb881b618fed314fe30cf9e3ec7b00 8192w

Fixed Image Rendering

Specifying either a w or a h parameter to buildSrcSet() will create a DPR-based srcset. This DPR-based srcset allows for the fixed-sized image to be served at different resolutions (i.e. at different pixel densities).

const client = new ImgixClient({
  domain: 'testing.imgix.net',
  secureURLToken: 'my-token',
});

const srcset = client.buildSrcSet('image.jpg', {
  h: 800,
  ar: '3:2',
  fit: 'crop',
});

console.log(srcset);

Will produce the following attribute value:

https://testing.imgix.net/image.jpg?h=800&ar=3%3A2&fit=crop&dpr=1&s=3d754a157458402fd3e26977107ade74 1x,
https://testing.imgix.net/image.jpg?h=800&ar=3%3A2&fit=crop&dpr=2&s=a984ad1a81d24d9dd7d18195d5262c82 2x,
https://testing.imgix.net/image.jpg?h=800&ar=3%3A2&fit=crop&dpr=3&s=8b93ab83d3f1ede4887e6826112d60d1 3x,
https://testing.imgix.net/image.jpg?h=800&ar=3%3A2&fit=crop&dpr=4&s=df7b67aa0439588edbfc1c249b3965d6 4x,
https://testing.imgix.net/image.jpg?h=800&ar=3%3A2&fit=crop&dpr=5&s=7c4b8adb733db37d00240da4ca65d410 5x

By default, this library generates a srcset with pixel density values of 1 through 5. These target ratios can be controlled by using the devicePixelRatios parameters.

const client = new ImgixClient({
  domain: 'testing.imgix.net',
  secureURLToken: 'my-token',
});

const srcset = client.buildSrcSet(
  'image.jpg',
  {
    h: 800,
    ar: '3:2',
    fit: 'crop',
  },
  {
    devicePixelRatios: [1, 2],
  },
);

console.log(srcset);

Will result in a smaller srcset.

https://testing.imgix.net/image.jpg?h=800&ar=3%3A2&fit=crop&dpr=1&s=3d754a157458402fd3e26977107ade74
1x,
https://testing.imgix.net/image.jpg?h=800&ar=3%3A2&fit=crop&dpr=2&s=a984ad1a81d24d9dd7d18195d5262c82
2x

For more information to better understand srcset, we highly recommend Eric Portis' "Srcset and sizes" article which goes into depth about the subject.

Custom Widths

In situations where specific widths are desired when generating srcset pairs, a user can specify them by passing an array of positive integers as widths to the third options object:

const client = new ImgixClient({
  domain: 'testing.imgix.net',
});

const srcset = client.buildSrcSet(
  'image.jpg',
  {},
  { widths: [100, 500, 1000, 1800] },
);

console.log(srcset);

Will generate the following srcset of width pairs:

https://testing.imgix.net/image.jpg?w=100 100w,
https://testing.imgix.net/image.jpg?w=500 500w,
https://testing.imgix.net/image.jpg?w=1000 1000w,
https://testing.imgix.net/image.jpg?w=1800 1800w

Note: that in situations where a srcset is being rendered as a fixed image, any custom widths passed in will be ignored. Additionally, if both widths and a widthTolerance are passed to the buildSrcSet method, the custom widths list will take precedence.

Width Tolerance

The srcset width tolerance dictates the maximum tolerated size difference between an image's downloaded size and its rendered size. For example: setting this value to 0.1 means that an image will not render more than 10% larger or smaller than its native size. In practice, the image URLs generated for a width-based srcset attribute will grow by twice this rate. A lower tolerance means images will render closer to their native size (thereby increasing perceived image quality), but a large srcset list will be generated and consequently users may experience lower rates of cache-hit for pre-rendered images on your site.

By default this rate is set to 8 percent, which we consider to be the ideal rate for maximizing cache hits without sacrificing visual quality. Users can specify their own width tolerance by providing a positive scalar value as widthTolerance to the third options object:

const client = new ImgixClient({
  domain: 'testing.imgix.net',
});

const srcset = client.buildSrcSet('image.jpg', {}, { widthTolerance: 0.2 });

console.log(srcset);

In this case, the width_tolerance is set to 20 percent, which will be reflected in the difference between subsequent widths in a srcset pair:

https://testing.imgix.net/image.jpg?w=100 100w,
https://testing.imgix.net/image.jpg?w=140 140w,
https://testing.imgix.net/image.jpg?w=196 196w,
          ...
https://testing.imgix.net/image.jpg?w=8192 8192w

Minimum and Maximum Width Ranges

In certain circumstances, you may want to limit the minimum or maximum value of the non-fixed srcset generated by the buildSrcSet() method. To do this, you can pass in an options object as a third argument, providing positive integers as minWidth and/or maxWidth attributes:

const client = new ImgixClient({
  domain: 'testing.imgix.net',
});

const srcset = client.buildSrcSet(
  'image.jpg',
  {},
  { minWidth: 500, maxWidth: 2000 },
);

console.log(srcset);

Will result in a smaller, more tailored srcset.

https://testing.imgix.net/image.jpg?w=500 500w,
https://testing.imgix.net/image.jpg?w=580 580w,
https://testing.imgix.net/image.jpg?w=672 672w,
https://testing.imgix.net/image.jpg?w=780 780w,
https://testing.imgix.net/image.jpg?w=906 906w,
https://testing.imgix.net/image.jpg?w=1050 1050w,
https://testing.imgix.net/image.jpg?w=1218 1218w,
https://testing.imgix.net/image.jpg?w=1414 1414w,
https://testing.imgix.net/image.jpg?w=1640 1640w,
https://testing.imgix.net/image.jpg?w=1902 1902w,
https://testing.imgix.net/image.jpg?w=2000 2000w

Remember that browsers will apply a device pixel ratio as a multiplier when selecting which image to download from a srcset. For example, even if you know your image will render no larger than 1000px, specifying options: { max_srcset: 1000 } will give your users with DPR higher than 1 no choice but to download and render a low-resolution version of the image. Therefore, it is vital to factor in any potential differences when choosing a minimum or maximum range.

Note: that according to the imgix API, the maximum renderable image width is 8192 pixels.

Variable Qualities

This library will automatically append a variable q parameter mapped to each dpr parameter when generating a fixed-image srcset. This technique is commonly used to compensate for the increased filesize of high-DPR images. Since high-DPR images are displayed at a higher pixel density on devices, image quality can be lowered to reduce overall filesize without sacrificing perceived visual quality. For more information and examples of this technique in action, see this blog post.

This behavior will respect any overriding q value passed in as a parameter. Additionally, it can be disabled altogether by passing { disableVariableQuality: true } to the third argument of buildSrcSet().

This behavior specifically occurs when a fixed-size image is rendered, for example:

const client = new ImgixClient({
  domain: 'testing.imgix.net',
});

const srcset = client.buildSrcSet('image.jpg', { w: 100 });

console.log(srcset);

Will generate a srcset with the following q to dpr mapping:

https://testing.imgix.net/image.jpg?w=100&dpr=1&q=75 1x,
https://testing.imgix.net/image.jpg?w=100&dpr=2&q=50 2x,
https://testing.imgix.net/image.jpg?w=100&dpr=3&q=35 3x,
https://testing.imgix.net/image.jpg?w=100&dpr=4&q=23 4x,
https://testing.imgix.net/image.jpg?w=100&dpr=5&q=20 5x

Quality parameters is overridable for each dpr by passing variableQualities parameters.

const client = new ImgixClient({
  domain: 'testing.imgix.net',
});

const srcset = client.buildSrcSet(
  'image.jpg',
  { w: 100 },
  { variableQualities: { 1: 45, 2: 30, 3: 20, 4: 15, 5: 10 } },
);

console.log(srcset);

Will generate the following custom q to dpr mapping:

https://testing.imgix.net/image.jpg?w=100&dpr=1&q=45 1x,
https://testing.imgix.net/image.jpg?w=100&dpr=2&q=30 2x,
https://testing.imgix.net/image.jpg?w=100&dpr=3&q=20 3x,
https://testing.imgix.net/image.jpg?w=100&dpr=4&q=15 4x,
https://testing.imgix.net/image.jpg?w=100&dpr=5&q=10 5x

Disable Path Encoding

This library will encode by default all paths passed to both buildURL and buildSrcSet methods. To disable path encoding, pass { disablePathEncoding: true } to the third argument options of buildURL() or buildSrcSet().

const client = new ImgixClient({
  domain: 'testing.imgix.net',
});

const src = client.buildURL(
  'file+with%20some+crazy?things.jpg',
  {},
  { disablePathEncoding: true },
);
console.log(src);

const srcset = client.buildSrcSet(
  'file+with%20some+crazy?things.jpg',
  {},
  { disablePathEncoding: true },
);
console.log(srcset);

Normally this would output a src of https://testing.imgix.net/file%2Bwith%2520some%2Bcrazy%3Fthings.jpg, but since path encoding is disabled, it will output a src of https://testing.imgix.net/file+with%20some+crazy?things.jpg.

Custom URL encoding

This library will encode by default using encodeURI(), encodeURIComponent(), or a combination of the two depending on the image path and parameters. You can define a custom encoding function in buildURL's options` object if you wish to override this behavior. Note that encoding your own URL can result in a URL that is not recognized by the imgix rendering API.

const ImgixClient = require("@imgix/js-core");
const client = new ImgixClient({
  domain: 'test.imgix.com',
  secureURLToken: 'xxxxxxxx',
});

client.buildURL(
  "https://proxy.imgix.net/image.jpg",
  {
    "txt": "test!(')*"
  },
  {
    encoder: (path) => encodeURI(path).replace("'", "%27")
  }
)

/*
  output:
  https://proxy.imgix.net/image.jpg?txt=test!(%27)
*/

The custom encoder also accepts a second optional parameter key which allows users to modify how query parameters are encoded. This parameter does not affect the custom encoding logic of the image path.

const ImgixClient = require("@imgix/js-core");
const client = new ImgixClient({
  domain: 'test.imgix.com',
  secureURLToken: 'xxxxxxxx',
});

client.buildURL(
  "https://proxy.imgix.net/image.jpg",
  {
    "txt": "test!(')*"
  },
  {
    encoder: (value, key) => key?.substr(-2) === '64' ? Base64.encodeURI(value) : value.replace(' ', "+")
  }
)

Web Proxy Sources

If you are using a Web Proxy Source, all you need to do is pass the full image URL you would like to proxy to @imgix/js-core as the path, and include a secureURLToken when creating the client. @imgix/js-core will then encode this full URL into a format that imgix will understand, thus creating a proxy URL for you.

import ImgixClient from '@imgix/js-core';

const client = new ImgixClient({
  domain: 'my-proxy-domain.imgix.net',
  secureURLToken: '<token>',
});

client.buildURL('https://example.com/image-to-proxy.jpg', {});
client.buildSrcSet('https://example.com/image-to-proxy.jpg', {});

What is the Ixlib Param on Every Request?

For security and diagnostic purposes, we sign all requests with the language and version of library used to generate the URL.

This can be disabled by passing a falsy value for the includeLibraryParam option to new ImgixClient:

new ImgixClient({
  domain: 'my-source.imgix.net',
  includeLibraryParam: false,
});

Support for Management API

Users looking for client library support for the imgix management API should use the imgix-management-js library. These two projects may be merged at a future date.

Testing

@imgix/js-core uses mocha for testing. Hereโ€™s how to run those tests:

npm test

License

FOSSA Status

More Repositories

1

drift

Easily add "zoom on hover" functionality to your site's images. Lightweight, no-dependency JavaScript.
JavaScript
1,527
star
2

imgix.js

Responsive images in the browser, simplified
JavaScript
965
star
3

luminous

A simple, lightweight, no-dependencies JavaScript lightbox
JavaScript
771
star
4

react-imgix

React component to display imgix images
JavaScript
353
star
5

prometheus-am-executor

Execute command based on Prometheus alerts
Go
232
star
6

imgix-php

A PHP client library for generating URLs with imgix
PHP
111
star
7

imgix-rails

A gem for integrating imgix into Rails projects
Ruby
110
star
8

imgix-rb

A Ruby gem for generating image URLs with imgix
Ruby
76
star
9

jekyll-imgix

A plugin for integrating imgix into Jekyll sites
Ruby
51
star
10

motif

A simple Rails app to create responsive social images
HTML
41
star
11

imgix-url-params

Organized, machine-friendly documentation of imgix's URL parameters
38
star
12

imgix-python

A Python client library for generating URLs with imgix
Python
36
star
13

vue

A simple yet powerful integration between Vue and imgix
TypeScript
35
star
14

gatsby

A simple yet powerful integration between Gatsby and imgix
TypeScript
30
star
15

imgix-objc

Official imgix Objective-C client.
Objective-C
29
star
16

ember-cli-imgix

Easily add imgix functionality to your Ember application
JavaScript
26
star
17

imgix-swift

A Swift client library for generating URLs with imgix
Swift
25
star
18

magento

Browse, search, and insert image assets into your storefront quickly and easily via the imgix Image Manager.
JavaScript
22
star
19

imgix-emacs

An emacs major-mode for editing images via imgix.
Emacs Lisp
20
star
20

imgix-java

A Java client library for generating URLs with imgix
Java
19
star
21

django-imgix

Django module to provide imgix template tags and functions
Python
19
star
22

imgix-blueprint

Documentation for creating imgix libraries in different languages
18
star
23

imgix-statamic

An add-on for integrating imgix into Statamic sites
PHP
17
star
24

paperclip-imgix

Paperclip plugin to integrate with Imgix
Ruby
15
star
25

imgix-csharp

A C# client library for generating image URLs with imgix
C#
14
star
26

imgix-go

A Go client library for generating image URLs with imgix
Go
12
star
27

contentful

Browse, search, and add assets into your content quickly and easily via the imgix Asset Manager.
TypeScript
10
star
28

imgix-management-js

A Javascript library that wraps the imgix management API
JavaScript
7
star
29

eddy

High-performance, maintenence-light, caching library and tools.
C
5
star
30

ix-video

An imgix video custom element that works anywhere
TypeScript
4
star
31

angular

A library for integrating imgix into Angular applications
TypeScript
4
star
32

fontmanager

Command line font manager for OS X
Objective-C
3
star
33

web-components

SDK web components shared across Frontend Frameworks - WIP
TypeScript
3
star
34

typescript-imgix-url-params

TypeScript definitions of imgix's URL parameters
TypeScript
3
star
35

go-httpstring

fast http header string parser
Go
2
star
36

go-jobmanager

run subproc pools, on-demand grow and shrink, communicate with length-prefixed response, monitor RSS
Go
2
star
37

renovate-config

A shareable Renovate bot configuration for all SDK repos
1
star
38

web-tools

Tools and configurations common to all imgix web projects
JavaScript
1
star
39

imgix-webfolder-router

A simple node.js router to allow multiple Base URLs for imgix Web Folders
JavaScript
1
star
40

nyt-example-app

Demos the imgix srcset API
HTML
1
star
41

sf-commerce-cloud

Use this integration to insert images from imgix's Image Manager into your Salesforce Commerce Cloud websites.
JavaScript
1
star
42

react-native-expo-example-app

Example Expo React Native application using @imgix/js-core to render a responsive image
JavaScript
1
star
43

shopify-integration-guide

Guide for integrating Shopify with imgix
1
star