Perform Image Transformations in Vue.js with ImageKit
Tags: vue, javascript, webdev, productivity
Published: 2021-05-02 15:17:23

---
title: Perform Image Transformations in Vue.js with ImageKit
published: true
description: A brief read on how to perform image transformations for images hosted on ImageKit by using custom ImageKit Vue components.
tags: vue, javascript, webdev, productivity
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/25jdke3recphu1mwbfwo.png
canonical_url: https://jamesinkala.com/blog/perform-image-transformations-in-vuejs-with-imagekit/
---

Image transformation is the visual manipulation of an image file into acquiring an intended output, this can be modifying the image's color, dimensions, aspect ratio, borders, quality, size and more.

There are many ways to go about transforming images in web development, one way to do that is after an image has been loaded into the html page where it is modified by using CSS style sheets and Javascript. For example we are rotating the image by 45 degrees in the example below by using CSS. 
```html
<head>

    <style>
      img{
        transform: rotate(45deg);
      }
    </style>

</head>
<body>

    <img src="https://ik.imagekit.io/demo/medium_cafe_B1iTdD0C.jpg">

</body>
```

Another way is transformation of images done on the fly, this means transforming images by making a request with prescribed parameters that return the desired image from the content delivery network storing the image.

The later is more desirable as it helps implement best asset management and utilization practices in front-end projects, ImageKit does this and we are going to learn how we can use it to create transformations within the Vue environment.

### Creating an ImageKit account ###
ImageKit let's you [register for a free account](https://imagekit.io/registration?planType=free) that comes with support for all paid features to the service which lets you take the service for a test run before choosing to commit to it's paid plans, that said ImageKit paid plans are on the modest side of the pricing range compared to other image CDNs catering the same needs.

Head over to [ImageKit's registration page](https://imagekit.io/registration?planType=free) and create a free account.
![ImageKit registration page](https://ik.imagekit.io/rzynsbbdjrf/vue_image_tr_blog/imagekit-registration_UkwJA9de67GM.png)

After completing the registration process login into the account, you'll find yourself in the account's dashboard, here proceed with the account registration completion instructions to finish setting up your ImageKit account.
![ImageKit account registration completion steps](https://ik.imagekit.io/rzynsbbdjrf/vue_image_tr_blog/imagekit-account-completion--instructions_amI0a9WMN.png)

### Setting up ImageKit’s Vue SDK ###
If you have not installed Vue.js on your system yet proceed with the following steps.
First, install vue-cli into your system and start a new VueJs project.
```sh
npm install -g @vue/cli
# OR
yarn global add @vue/cli
```

After installation you'll have access to the Vue binary on the command-line and to test if the installation was successful run `vue` on the command-line which should present you with a help message listing all available commands.

Proceed to creating a new Vue project with the following command:
```sh
vue create imagekit-transformations
```

Choose the features that satisfy the needs of your project and let it set up all the initial files and dependencies, on completion switch into the new project's directory with `cd imagekit-transformations`.

Inside the project's directory install ImageKit's Vue plugin [imagekitio-vue]() with the following command.
```sh
npm install imagekitio-vue
# OR
yarn add imagekitio-vue
```

Initialize ImageKit's Vue SDK in the main.js file or the individual component that you are going to use ImageKit's components.
```js
import ImageKit from "imagekitio-vue"
Vue.use(ImageKit, {
  urlEndpoint: "your_url_endpoint",
  // publicKey: "your_public_api_key",
  // authenticationEndpoint: "https://www.your-server.com/auth"
})
```

This is a breakdown of the above properties: 
__urlEndpoint__ is a required parameter and is the base URL to all of the images found on your ImageKit media library, you can find it on your [ImageKit dashboard](https://imagekit.io/dashboard#url-endpoints), copy that value and place it here.
__publicKey__ and __authenticationEndpoint__ are optional parameters that are used when you want to implement front-end image uploading which is outside the scope of this article.
 
### Rendering images in Vue.js ###
ImageKit's VUe plugin comes with three different components __IKImage__, __IKContext__ and __IKUpload__.
The __IKImage__ component is used for image resizing giving an __img__ tag as it's output.
The __IKUpload__ is used for uploading files giving a  __file input__ tag as it's output and IKContext is used for defining ___urlEndpoint___, ___publicKey___ and ___authenticationEndpoint___ to its children elements.

Since we are dealing with image transformations we are going to work mainly with the __IKImage__ component.
All that is needed to render an image in the IKImage component is a minimum of a ___src___ or ___path___ prop.
The ___path___ property is a String variable holding the path at which an image exists in relation to the base URL(___urlEndpoint___) of your ImageKit account, for example - `/default-image.png`.
To render an image with the ___path___ prop do the following:
```vue
<ik-image path="/default-image.jpg"></ik-image>
```

The ___src___ property is a String variable holding the complete URL of an image already mapped to ImageKit, for example - `https://ik.imagekit.io/rzynsbbdfsd/default-image.jpg`
To render an image with the ___path___ prop do the following:
```vue
<ik-image :src="YOUR_IMAGEKIT_URL_ENDPOINT/default-image.jpg"></ik-image>
```

### Using ImageKit’s Vue components to transform images ###
After covering the bit about ImageKit URL tranformations and rendering images with the __IKImage__ component we are going to combine that knowledge to perform image transformations in Vue. All you need to know are a couple of other __IkImage__ component props that will assist you in accomplish this.
Extra IKImage component props:

Extra __IKImage__ component props to know:
__transformation__: This is an optional array variable holding the transformations to be applied in the URL as key value pair objects of the transformation names and value respsectively. [Here is a list of all the supported transformations](https://github.com/imagekit-developer/imagekit-vuejs#list-of-supported-transformations)
__lqip__: This is optional object parameter that's used to show low-quality placeholder images while the intended image is being loaded by specifying the ___blur___ and ___quality___ values. 
__queryParameters__: These are the other optional query parameters that you want to add to the final image URL, they can be any query parameters not necessarily related to ImageKit and are quite useful when you want to add some versioning to your URLs.
__loading__: This is an optional prop used to lazy load images.
When it comes to performing image transformations in Vue you'll be working mostly with the __transformation__ and maybe __lqip__ parameters.
 
Let's create some image transformations with the __IKImage__ component.

Starting with general image transformations, we choose a couple of parameters to demonstrate their application within the __IKImage__ component.
Let's first initiate a `galleryEndpoint` variable that will hold the firt part of the URLs to our image assets (___urlEndpoint___).
```jsx
<script>
export default {
  data(){
    return: {
      galleryEndpoint: process.env.VUE_APP_URL_ENDPOINT
    }
  }
} 
</script>
```

As you can notice above, it's good practice to place the environmental variables in a `.env` file, though we should never pass any secret keys in this format and ImageKit proposes another way to go about this when performing image uploads.

More transformations:
__Transformation of the height `h` and width__ `w`: We pass the height `h` and width `w` transformations as object properties within the transformations array as follows.
```jsx
  <template>
    <div>
      <IKImage
        :path="'/portrait-3_8qJ14KyQ0sczC.jpg'"
        :transformation="[
          {height: 300, width: 400}
        ]",
        :urlEndpoint="galleryEndpoint"
      />
    </div>
  <template>
```

__Aspect ratio:__ To modify the aspect ratio of an image pass the `ar` parameter and its value as an object in the transformations array as follows.
___aspect ratio:___ 3:1
```jsx
  <template>
    <div>
      <IKImage
        :path="'/portrait-3_8qJ14KyQ0sczC.jpg'"
        :transformation="[
          {ar: 3}
        ]",
        :urlEndpoint="galleryEndpoint"
      />
    </div>
  <template>
```
__Crop, crop-modes and focus:__
  - __Pad resize crop strategy:__ Let's demonstrate how we can apply this crop strategy using the __IKImage__ component.
  Examples:
  original image - `https://ik.imagekit.io/demo/img/plant.jpeg`, applying width `w` of 300px, height `h` of 200px, the pad resize crop mode `cm` and a background`bg`  hex value of `#F3F3F3`
  ```jsx
  <template>
    <div>
      <IKImage
        :path="'/portrait-3_8qJ14KyQ0sczC.jpg'"
        :transformation="[
          {w: 300, h: 200, cm: 'pad_resize', bg: 'F3F3F3'}
        ]",
        :urlEndpoint="galleryEndpoint"
      />
    </div>
  <template>
  ```
  - __max-size cropping__ or __min-size cropping strategy:__ In these two crop mode strategies, one or both of the dimensions are adjusted to preserve the aspect ratio without cropping the image.
  Examples:
  Original image - `URL_ENDPOINT/portrait-3_8qJ14KyQ0sczC.jpg`
  ![Original image](https://ik.imagekit.io/rzynsbbdjrf/portrait-3_8qJ14KyQ0sczC.jpg)

  Applying max-size `c: 'at_max'` cropping on it in vue
  ```jsx
  <template>
    <div>
      <IKImage
        :path="'/portrait-3_8qJ14KyQ0sczC.jpg'"
        :transformation="[
          {w: 600, h: 400, c: 'at_max'}
        ]",
        :urlEndpoint="galleryEndpoint"
      />
    </div>
  <template>
  ```

  We get the following output
  ![Pad resized image](https://ik.imagekit.io/rzynsbbdjrf/portrait-3_8qJ14KyQ0sczC.jpg?tr=w-600,h-400,c-at_max)

  Applying min-size cropping on it, c: 'at_min'
  ```jsx
  <template>
    <div>
      <IKImage
        :path="'/portrait-3_8qJ14KyQ0sczC.jpg'"
        :transformation="[
          {w: 200, h: 300, c: 'at_min'}
        ]",
        :urlEndpoint="galleryEndpoint"
      />
    </div>
  <template>
  ```

  Results to the following image
  ![pad resized image](https://ik.imagekit.io/rzynsbbdjrf/portrait-3_8qJ14KyQ0sczC.jpg?tr=w-200,h-300,c-at_min)

  - __maintain ratio crop or extract crop or pad extract crop strategy__: These crop stategies let us receive exact  same dimensions in the resulting images as requested but crop the image to preserve the aspect ratio or extract a portion from the original image
    - __Maintain ratio crop strategy__: This is the default crop strategy where the output image's dimensions are same as requested and the aspect ratio is preserved resulting in resizing of the original image and cropping of some of it's parts
    Original image
    ![random image](https://ik.imagekit.io/rzynsbbdjrf/landscape-5_xTbBtNVK7.jpg)

    Maintain ratio crop in Vue
    ```jsx
    <template>
      <div>
        <IKImage
          :path="'/landscape-5_xTbBtNVK7.jpg'"
          :transformation="[
            {w: 200, h: 200, c: 'maintain_ratio'}
          ]",
          :urlEndpoint="galleryEndpoint"
        />
      </div>
    <template>
      ```

    Resulting image
    ![pad resized image](https://ik.imagekit.io/rzynsbbdjrf/landscape-5_xTbBtNVK7.jpg?tr=w-200,h-200,c-maintain_ratio)
    - __Extract crop strategy__: This is the same as the ratio crop strategy but instead of resizing the image it extracts a region per the requested dimensions from the original image.
      Applying extract crop in Vue `cm: 'extract'`
      ```jsx
      <template>
        <div>
          <IKImage
            :path="'/landscape-5_xTbBtNVK7.jpg'"
            :transformation="[
              {w: 200, h: 200, cm: 'extract'}
            ]",
            :urlEndpoint="galleryEndpoint"
          />
        </div>
      <template>
      ```

      Resulting image
      ![pad resized image](https://ik.imagekit.io/rzynsbbdjrf/landscape-5_xTbBtNVK7.jpg?tr=w-200,h-200,cm-extract)
    - __Pad extract crop strategy__: This is the same as the extract crop strategy but applicable in an instance where the portion we are trying to extract from an image is larger than the image itself, thus padding is added around the image to match the exact size requested.
      Repeating the above example, we get
      ```jsx
          <template>
            <div>
              <IKImage
                :path="'/landscape-5_xTbBtNVK7.jpg'"
                :transformation="[
                  {w: 2000, h: 600, cm: 'pad_extract', bg: 'ABC1E4'}
                ]",
                :urlEndpoint="galleryEndpoint"
              />
            </div>
          <template>
      ```

      Resulting image
      ![pad resized image](https://ik.imagekit.io/rzynsbbdjrf/landscape-5_xTbBtNVK7.jpg?tr=w-2000,h-1000,cm-pad_extract,bg-ABC1E4)

__Focus__: This transformation can be used with the combination of __pad resize__, __maintain ratio__ and __extract crop__ to change the behavior of padding or cropping:
We can use focus to focus on features such as a face, passing the focus`fo` parameter and giving it the `face` value in combination with __maintain ratio__ to an image as follows
Original image
![portrait of a girl](https://ik.imagekit.io/rzynsbbdjrf/vue_image_tr_blog/portrait-2_D1mTiDtoT4sHW.jpg?tr=h-300)

```jsx
<template>
  <div>
    <IKImage
      :path="'/vue_image_tr_blog/landscape-5_xTbBtNVK7.jpg'"
      :transformation="[
        {w: 100, h: 100, cm: 'maintain_ratio', fo: 'face'}
      ]",
      :urlEndpoint="galleryEndpoint"
    />
  </div>
<template>
```
After applying focus on the face with some resizing in the code above, we have the following image output:
![image cropped and focus is placed on the face](https://ik.imagekit.io/rzynsbbdjrf/vue_image_tr_blog/portrait-2_D1mTiDtoT4sHW.jpg?tr=h-100,w-100,fo-face,cm-maintain_ratio)

[More on the focus transformation can be found here](https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#focus-fo)

__Quality__: We can specify the quality of the image to be displayed by passing the quality`q` paramater and assigning it a number from 1 - 99 .
Image with quality set to 10:
```jsx
<template>
  <div>
    <IKImage
      :path="'/20210204_204010__oBWM2H9Pfr5l.jpg'"
      :transformation="[
        {h: 300, q: 10}
      ]",
      :urlEndpoint="galleryEndpoint"
    />
  </div>
<template>
```

![Image with quality - 'q' set to 10](https://ik.imagekit.io/rzynsbbdjrf/20210204_204010__oBWM2H9Pfr5l.jpg?tr=h-300,q-10)

Setting the image quality to 100 on the same image:
```jsx
<template>
  <div>
    <IKImage
      :path="'/20210204_204010__oBWM2H9Pfr5l.jpg'"
      :transformation="[
        {h: 300, q: 100}
      ]",
      :urlEndpoint="galleryEndpoint"
    />
  </div>
<template>
```
![Image with quality - 'q' set to 100](https://ik.imagekit.io/rzynsbbdjrf/20210204_204010__oBWM2H9Pfr5l.jpg?tr=h-300,q-100)

__Format__: format`f` is used to specify the format of the image being fetched, it can be set to `auto`,`jpeg`,`png`,`avif`,`webp` and `jpg`.

__Blur__: blur`bl` is used to set the gaussian blur to be set on an image with values between 1 and 100.
Applying an image with blur`bl` value set to 5:
```jsx
<template>
  <div>
    <IKImage
      :path="'/20210204_204010__oBWM2H9Pfr5l.jpg'"
      :transformation="[
        {h: 300, bl: 5}
      ]",
      :urlEndpoint="galleryEndpoint"
    />
  </div>
<template>
```
Image with blur parameter `bl` set to 5
![Image with blur parameter 'bl' set to 5](https://ik.imagekit.io/rzynsbbdjrf/20210204_204010__oBWM2H9Pfr5l.jpg?tr=h-300,bl-5)

__Lazy loading images__: To lazy load images pass the `loading` parameter to the __IKImage__ prop assigning it the String `lazy`.
```jsx
<template>
  <div>
    <IKImage
      :path="'/20210204_204010__oBWM2H9Pfr5l.jpg'"
      loading="lazy"
      :urlEndpoint="galleryEndpoint"
    />
  </div>
<template>
```

__Low quality image placeholders__: We can set the `lqip` attribute to true to load low quality versions of images before the original image is loaded. When the higher quality version gets fully loaded it replaces the placeholder.
```jsx
<template>
  <div>
    <IKImage
      :path="'/20210204_204010__oBWM2H9Pfr5l.jpg'"
      :lqip="{active: true}"
      :urlEndpoint="galleryEndpoint"
    />
  </div>
<template>
```

You can go as far as modifying the blur and quality values of the placeholder image:
```jsx
<template>
  <div>
    <IKImage
      :path="'/20210204_204010__oBWM2H9Pfr5l.jpg'"
      :lqip="{active: true, quality: 25, blur: 15}"
      :urlEndpoint="galleryEndpoint"
    />
  </div>
<template>
```
#### Chained transformation ####
More than one object containing various key value pairs of the transformations can be passed on the ___transformations___ prop to perform a sequence of transformations one following the other.
For example in the following image we are resizing the image, we then a border radius to end at finally rotate it by 180 degrees. The only rotation angles allowed by ImageKit are `0`, `90`, `180`, `270` and `360`.
```jsx
<template>
  <div>
    <IKImage
      :path="'/20210204_204010__oBWM2H9Pfr5l.jpg'"
      :transformation="[
        {h: 400, w: 400},
        {r: 30},
        {rotate: 180}
      ]",
      :urlEndpoint="galleryEndpoint"
    />
  </div>
<template>
```
![image cropped and focus is placed on the face](https://ik.imagekit.io/rzynsbbdjrf/20210204_204010__oBWM2H9Pfr5l.jpg?tr=h-400,w-400,r-30,rt-180)

This is how we chain transformations in ImageKit.

## Image transformation best practices ##
Since image transformations are performed on 'images' then the best practices that we observe while serving images to our applications remain the same with a couple additions.
Here are a few:
- Reducing the file size of images being served to reduce loading times as this is used as a pageranking factor in some search engines and for use cases such as e-commerce websites, longer loadding times means loss of customers and hence revenues. This can also include the optimization of images such as thumbnails to make sure that you deliver small files otherwise they will slow down loading speeds.
- Add and optimize alt attributes on the `<img>` as this will act as an alternative to the image when it fails to load and they are used for web accessibility. Properly constructed alt attributes with relevant keywords also contribute to higher ranking in SEO scores.
- Serve responsive images where possible, this enhances the user experience, and when the dimensions of images delivered are just right for specific viewports it give websites a professional feel as otherwise images might break the responsiveness of whole web pages on mobile devices when not styled right.

## Summary ##
Here is a summary of what we have learnt.
So far we have learnt:
- What image tranformations are.
- We have learnt how to create an account on ImageKit.io, its Vue SDK and how to set it up.
- We have also learnt how to use the __IKImage__ component to perform various transformations of images hosted on ImageKit inside Vue.

Go ahead and transform the web.

&nbsp;
&nbsp;

<center><a href="https://www.buymeacoffee.com/Xinnks" target="_blank"><img src="https://res.cloudinary.com/djx5h4cjt/image/upload/c_scale,h_50/james-sinkala/bmc-button.png" alt="Buy Me A Coffee" style="height: 50px !important;width: auto !important;" ></a></center>