npm package: @siteone/img-microservice
Description: Image processing service
Latest version: 2.4.1

# @siteone/img

<a href="https://seal.beyondsecurity.com/vulnerability-scanner-verification/img.frontend.company"><img src="https://seal.beyondsecurity.com/verification-images/img.frontend.company/vulnerability-scanner-2.gif" alt="Website Security Test" border="0"></a>

> Microservice for fast and awesome image manipulation microservice.

- [@siteone/img](#siteoneimg)
  - [Install](#install)
    - [Npm](#npm)
  - [Configuration](#configuration)
    - [Developers](#developers)
    - [Cli / global installation](#cli--global-installation)
      - [Server parameters](#server-parameters)
      - [Caches](#caches)
        - [Output cache](#output-cache)
        - [Input cache](#input-cache)
      - [Cache configuration](#cache-configuration)
        - [_No cache_](#no-cache)
        - [_Filesystem caching_](#filesystem-caching)
        - [_Memory_](#memory)
      - [Domain whitelist](#domain-whitelist)
      - [Logger](#logger)
      - [Guess file type by extension](#guess-file-type-by-extension)
      - [Progressive images](#progressive-images)
      - [Errors](#errors)
      - [Compress](#compress)
  - [Usage](#usage)
  - [Blur](#blur)
    - [Example](#example)
  - [Extract](#extract)
    - [Example](#example-1)
  - [Flip](#flip)
      - [Example](#example-2)
        - [Flip x](#flip-x)
        - [Flip y](#flip-y)
  - [Output](#output)
    - [Example](#example-3)
      - [JPEG](#jpeg)
      - [WEBP](#webp)
  - [Progressive images](#progressive-images-1)
    - [Force progressive](#force-progressive)
    - [Force non progressive](#force-non-progressive)
  - [Resize](#resize)
    - [Resize methods](#resize-methods)
      - [Scale](#scale)
        - [Examples](#examples)
      - [Fit](#fit)
      - [Down fit](#down-fit)
      - [Up fit](#up-fit)
      - [Fill](#fill)
        - [Examples](#examples-1)
      - [Down fill](#down-fill)
        - [Examples](#examples-2)
      - [Embed](#embed)
    - [Sizes](#sizes)
      - [Pixel](#pixel)
      - [Percentage](#percentage)
      - [Mixed](#mixed)
    - [Gravity](#gravity)
    - [Colors](#colors)
  - [Rotate](#rotate)

---

## Install

Img microservice can be installed in different ways, through docker or with npm. Depending on your needs you find here your way.

### Npm

You can install img globally with

```bash
npm install -g @siteone/img
```

and then run it with

```bash
img
```

Pass `--help` to discover the available options

---

## Configuration

Img microservice try to meet the most common needs, so when you start it you already have a fully working system. Nonetheless Img microservice is highly customizable.

### Developers

If you are a developer or run Img microservice directly from the source, the default configuration file contains a lot of instructions. You can read it in <a href="https://git.siteone.cz/frontend/img/blob/master/config/default.js" target="_blank">`config/default.js`</a>.

### Cli / global installation

When you install img globally, the cli accepts various configuration parameters. You can read the inline help running `img --help`.
Here a deeper look to the parameter

#### Server parameters

Img microservice listen to port **8565** by default. You can change it to the value you prefer:

```bash
> img --port 1234
```

#### Caches

Img microservice has different cache levels and any can be disabled and configured indipendently from the others

##### Output cache

This cache store the resulting image. If you make a second request to get the same image with the same transformations, this cache will hit and the cached result will be returned. The image won't be processed again. By default this cache is set to `memory`.

##### Input cache

If you change your transformation the original image will be downloaded again unless you activate the input cache. If this cache is activated the original image will be stored and therefore it won't be downloaded again. The image will be just re-processed to evaluate the new transformations to apply.
This cache by default is disabled.

#### Cache configuration

Each cache can use a different method to save/retrieve cached resources. All of those methods applies to any kind of cache.

##### _No cache_

This special cache doesn't store anything. Each request will be re-processed by Img microservice.

- **Output cache:**

      	```bash
      	# enable
      	> img --cache none
      	```

- **Input cache:**
  `bash # enable > img --inputcache none`

##### _Filesystem caching_

The cached images will be stored on your local file system.

- **Output cache:**

      	```bash
      	# enable
      	# note: The processed images will be saved on the operating system default temporary folder.
      	> img --cache file
      	# change cache path path
      	> img --cache file --cache-filepath "path/to/cache/folder/"
      	```

- **Input cache:**
  `bash # enable # note: The processed images will be saved on the operating system default temporary folder. > img --inputcache file # change path > img --inputcache file --inputcache-filepath "path/to/cache/folder/"`

##### _Memory_

In this case the cache will be stored in memory. It will be delete when the service is restarted.

- **Output cache:**

      	```bash
      	# enable
      	# note: The processed images will be saved on the operating system default temporary folder.
      	> img --cache file
      	# change cache size limit (in MB)
      	> img --cache file --cache-limit 250
      	# disable cache size limit
      	> img --inputcache file --inputcache-limit false
      	```

- **Input cache:**
  `bash # enable # note: The processed images will be saved on the operating system default temporary folder. > img --inputcache file # change cache size limit (in MB) > img --inputcache file --inputcache-limit 250 # disable cache size limit > img --inputcache file --inputcache-limit false`

#### Domain whitelist

By default img transforms any image you feed him.
If your service is publicly exposed you may want to restrict the list of domains from where the images can be taken.
This can be a list of domains and it can contain wildcards.

```bash
> img --whitelist myapp.s3.amazon.com, *.myapp.com
```

#### Logger

Logger can be set to two levels.

```bash
## verbose logging
> img -v
## quiet
> img -q
```

Img microservice, by default, prints readable messages on stdout. You can, however, change output to JSON.

```bash
> img --json
```

#### Guess file type by extension

Img microservice reads the file metadata to retrieve information about the file type. It can be configured to use the file extensions instead.

```bash
> img --guess-type-by-extension
```

In case the file extension is missing, img will fallback to metadata. For some transformation, reading the metadata is mandatory.

#### Progressive images

For the image formats where this is applicable, Img microservice produces progressive images. This is the best choice on the web since the images
can start to render before being entirely downloaded.
This behavior can be disabled

```bash
> img --progressive false
```

#### Errors

Img microservice can report error in several format. By default the errors are reported in a `json` format to help machine parsing. The other accepted values are `plain`, for a simple text report, and `html` for a pretty formatted report.

```bash
> img --errors plain
```

#### Compress

Img microservice can compress the response through `deflate/gzip` if the requester (the browser usually), asks for it through `Accept-encoding` header. _By default this option is turned off._

```bash
img --compress
```

---

## Usage

**Demo instance:** `$MICROSERVICE_URL/$TRANSFORMS/$IMAGE_URL`

- `$MICROSERVICE_URL` - full URL of microservice (example instance runs on https://img.frontend.company)
- `$TRANSFORMS` - documented below
- `$IMAGE_URL` - full URL of image

**Example:** `https://img.frontend.company/rs_200x200/http://unsplash.it/2000/2000

---

## Blur

Blur the image.

**General syntax**: `blur_$VALUE`

- `$VALUE` can be `0.3` to `1000`

### Example

**Result**
![](https://img.frontend.company/blur_10/https://picsum.photos/800/600/?id=1)

**Example URL**: `https://img.frontend.company/blur_100/https://picsum.photos/800/600/`

---

## Extract

Extract let you select an arbitrary portion of the input image specifying the coordinates and the size of the extraction.

**General syntax**: `extract_$X_$Y_$W_$H`

- `$X` X coordinate
- `$Y` Y coordinate
- `$W` width
- `$H` height

**All values can be specified as pixel values or percentages.**

### Example

![](https://img.frontend.company/ex_95_35_0.5_100/https://picsum.photos/800/600/)

**Image URL:** `https://img.frontend.company/ex_95_35_0.5_100/https://picsum.photos/800/600/`

Produces image with crop start at X **95px** and Y **35px** with width of **50%** of original image and height **100px**.

---

## Flip

Fli the image horizontally or vertically.

**General syntax**: `flip_$AXIS`

- `$AXIS` can be either - `x` for horizontal flipping - `y` for vertical flipping

#### Example

##### Flip x

![](https://img.frontend.company/flip_x/https://picsum.photos/800/600)

**Image URL:** https://img.frontend.company/flip_x/https://picsum.photos/800/600

##### Flip y

![](https://img.frontend.company/flip_y/https://picsum.photos/800/600)

**Image URL:** https://img.frontend.company/flip_y/https://picsum.photos/800/600

---

## Output

Returns your image in another format. Supports transforming `jpeg`, `png` `webp` and `tiff` into `jpeg` or `webp` formats.

**General syntax**: `o_$FORMAT`

- `$FORMAT` output image format - `webp` for [WEBP](https://wikipedia.org/wiki/WebP) - `jpeg` for JPEG

### Example

#### JPEG

![](https://img.frontend.company/o_jpeg/https://picsum.photos/800/600/)

**Image URL:** `https://img.frontend.company/o_jpeg/https://picsum.photos/800/600/`

#### WEBP

![](https://img.frontend.company/o_webp/https://picsum.photos/800/600/)

**Image URL: **
`https://img.frontend.company/o_webp/https://picsum.photos/800/600/`

---

## Progressive images

Produce [progressive](https://en.wikipedia.org/wiki/Progressive_Graphics_File) images.

**General syntax**: `progressive_$VALUE`

- `$VALUE` progressive option - `true` for progressive output - `false` for non-progressive output

### Force progressive

![](https://img.frontend.company/progressive_true/https://picsum.photos/800/600/?image=1)

**Image URL:** `https://img.frontend.company/progressive_true/https://picsum.photos/800/600/`

### Force non progressive

![](https://img.frontend.company/progressive_false/https://picsum.photos/800/600/?image=1)

**Image URL:** `https://img.frontend.company/progressive_false/https://picsum.photos/800/600/`

---

## Resize

Resize can be a very complex task in Img microservice. There are plenty of ways of resizing, cropping and extract portion of your images.

**General syntax:** `rs_$SIZE_$MODE_$MODE_PARAMS`

- `$SIZE` - is the new size (it can be expressed in several ways as explaned [here](#sizes)).
- `$MODE` - define how to resize. Maybe you want to stretch the image, or take just a portion;
- `$MODE_PARAMS` - are the parameters accepted by the specific mode and can also be empty.

### Resize methods

#### Scale

In scale mode the image will have the dimension of the size you specified. The aspect ratio is kept unless you pass **iar** (ignore aspect ratio) as additional parameter.
Since `scale` is the default resize mode, you can avoid specifiying it.

##### Examples

**Scale the image to 200x300 px keeping the aspect ratio**

![](https://img.frontend.company/rs_200x300/https://picsum.photos/800/600/)

**Image URL:** `https://img.frontend.company/rs_200x300/https://picsum.photos/800/600/?image=1`

**Scale the image to 200 px width keeping the aspect ratio. The height is calculated automatically**

![](https://img.frontend.company/rs_200/https://picsum.photos/800/600/)

**Image URL:** `https://img.frontend.company/rs_200/https://picsum.photos/800/600/?image=1`

**Scale the image to 200x300 px width ignoring the aspect ratio.**

![](https://img.frontend.company/rs_200x300_scale_iar/https://picsum.photos/800/600/)

**Image URL:** `https://img.frontend.company/rs_200x300_scale_iar/https://picsum.photos/800/600/?image=1`

#### Fit

The image will take the maximum available space up to the specified size, keeping the aspect ratio.
For example this will resize the image up to 300x300 pixels and all the image will be visible.

![](https://img.frontend.company/rs_300x300_fit/https://picsum.photos/800/600/?image=1)

**NOTE**: both width and height must be passed. Nonetheless they can be expressed in percentage

#### Down fit

Like fit but only if the image is **larger** than the desired size (width _or_ height), otherwise it will be left untouched.

![](https://img.frontend.company/rs_300x300_downfit/https://picsum.photos/800/600/?image=1)

**NOTE**: both width and height must be passed. Nonetheless they can be expressed in percentage

#### Up fit

Like fit but only if the image is **smaller** than the desired size (**both** the width and height must be smaller), otherwise it will be left untouched.

![](https://img.frontend.company/rs_300x300_upfit/https://picsum.photos/800/600/?image=1)

**NOTE**: both width and height must be passed. Nonetheless they can be expressed in percentage

#### Fill

Produce a new image of specified width and height. The original image is then filled inside those dimensions. The excess part will be excluded.
You can specify a [gravity](#gravity) to decide which part of the original image should be excluded. If nothing is specified the default gravity is `center`.

`Fill` also accept a special gravity parameter: **`auto`**. This let you automatically select a meaningfull region of the image.

##### Examples

**Center gravity**

![](https://img.frontend.company/rs_300x300/https://picsum.photos/800/600/?image=1)

**North-east gravity**

![](https://img.frontend.company/rs_300x300_fill_ne/https://picsum.photos/800/600/?image=1)

**Gravity on center**

![](https://img.frontend.company/rs_200x300_fill_center/https://picsum.photos/800/600/?image=1)

**Gravity auto**

![](https://img.frontend.company/rs_200x300_fill_auto/https://picsum.photos/800/600/?image=1)

#### Down fill

Same as fill but only if the image is larger than the target size (width _and_ height).

##### Examples

**Center downfill**

![](https://img.frontend.company/rs_300x300_downfill/https://picsum.photos/800/600/?image=1)

**West downfill**

![](https://img.frontend.company/rs_300x300_downfill_west/https://picsum.photos/800/600/?image=1)

#### Embed

This embeds the image in the specified dimensions. The entire image is taken and aspect ratio is kept. If the image doesn't fit well in the dimension the output will be padded with a color of your choice (or black by default).

**Simple embedding**

![](https://img.frontend.company/rs_320x240_embed/https://picsum.photos/800/600/?image=1)

**RGB color**

![](https://img.frontend.company/rs_320x240_embed_b105072200/https://picsum.photos/800/600/?image=1)

**RGBA color**

![](https://img.frontend.company/rs_320x240_embed_b105072200.5/https://picsum.photos/800/300/?image=1)

**HEX color and optional alpha (6 digit + alpha)**

![](https://img.frontend.company/rs_320x240_embed_bFF5400.5/https://picsum.photos/800/300/?image=1)

**Gravity**

![](https://img.frontend.company/rs_320x240_embed_bFF5400_gnorth/https://picsum.photos/800/300/?image=1)

### Sizes

The size parameter can be specified in several format in each resize mode.

#### Pixel

`rs_200x300` is 200 x 300 px
`rs_200` is 200 px width, height auto
`rs_x300` is 200 px height, width auto

#### Percentage

You can specify the width and height as percentage value of the input image

`rs_0.2x0.3` is 20% of the width and 30% of the height
`rs_0.2` is 20% of the width
`rs_x0.3` is 30% of the height

#### Mixed

Pixel and percentage can be mixed.

`rs_200x0.3` is 200px of width and 30% of height

### Gravity

For those operations which support gravity, those value can be specified

`center`, `north`, `northeast`, `northwest`, `east`, `west`, `south`, `southeast`, `southwest`

and can be abbreviated in

`c`, `n`, `ne`, `nw`, `e`, `w`, `s`, `se`, `sw`.

Some operation, such as `fill` and `downfill` accept the `auto` gravity. This automatically focus on the most important region of the image.
Look [here](#auto) for an example

### Colors

The colors accepted by some operations can be expressed as:

RGB `120230007` in this case the rgb(120, 230, 7)

The three values of red, green and blue must be put together and each must be of three digits, so 7 becomes 007 and 45 becomes 045.

Hexadecimal `FF00AB` is in the hex format. The short notation (3 digits only) is not accepted yet and `#` at the beginning must be removed.

To specify the opacity you can add `.3` at the end. So to set an opacity of 0.4 the previouses become `120230007.4` and `FF00AB.4`
Omitting the opacity means it is 1, full opaque, while `.0` means full transparent.

---

## Rotate

This paramter let you rotate the image.
Any angle multiple of `90°` is accepted.

**Result**

![](https://img.frontend.company/rotate_270/https://picsum.photos/800/600/?image=1)