Perform Image Transformations in Vue.js with ImageKit
James Sinkala
Posted on May 2, 2021
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.
<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 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 and create a free account.
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.
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.
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:
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.
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.
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, 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:
<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:
<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
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).
<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.
<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
<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 widthw
of 300px, heighth
of 200px, the pad resize crop modecm
and a backgroundbg
hex value of#F3F3F3
<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
Applying max-size c: 'at_max'
cropping on it in vue
<template>
<div>
<IKImage
:path="'/portrait-3_8qJ14KyQ0sczC.jpg'"
:transformation="[
{w: 600, h: 400, c: 'at_max'}
]",
:urlEndpoint="galleryEndpoint"
/>
</div>
<template>
Applying min-size cropping on it, c: 'at_min'
<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
-
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
Maintain ratio crop in Vue
<template> <div> <IKImage :path="'/landscape-5_xTbBtNVK7.jpg'" :transformation="[ {w: 200, h: 200, c: 'maintain_ratio'} ]", :urlEndpoint="galleryEndpoint" /> </div> <template>
-
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'
<template> <div> <IKImage :path="'/landscape-5_xTbBtNVK7.jpg'" :transformation="[ {w: 200, h: 200, cm: 'extract'} ]", :urlEndpoint="galleryEndpoint" /> </div> <template>
- 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
<template> <div> <IKImage :path="'/landscape-5_xTbBtNVK7.jpg'" :transformation="[ {w: 2000, h: 600, cm: 'pad_extract', bg: 'ABC1E4'} ]", :urlEndpoint="galleryEndpoint" /> </div> <template>
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 focusfo
parameter and giving it the face
value in combination with maintain ratio to an image as follows
Original image
<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:
More on the focus transformation can be found here
Quality: We can specify the quality of the image to be displayed by passing the qualityq
paramater and assigning it a number from 1 - 99 .
Image with quality set to 10:
<template>
<div>
<IKImage
:path="'/20210204_204010__oBWM2H9Pfr5l.jpg'"
:transformation="[
{h: 300, q: 10}
]",
:urlEndpoint="galleryEndpoint"
/>
</div>
<template>
Setting the image quality to 100 on the same image:
<template>
<div>
<IKImage
:path="'/20210204_204010__oBWM2H9Pfr5l.jpg'"
:transformation="[
{h: 300, q: 100}
]",
:urlEndpoint="galleryEndpoint"
/>
</div>
<template>
Format: formatf
is used to specify the format of the image being fetched, it can be set to auto
,jpeg
,png
,avif
,webp
and jpg
.
Blur: blurbl
is used to set the gaussian blur to be set on an image with values between 1 and 100.
Applying an image with blurbl
value set to 5:
<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
Lazy loading images: To lazy load images pass the loading
parameter to the IKImage prop assigning it the String lazy
.
<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.
<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:
<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
.
<template>
<div>
<IKImage
:path="'/20210204_204010__oBWM2H9Pfr5l.jpg'"
:transformation="[
{h: 400, w: 400},
{r: 30},
{rotate: 180}
]",
:urlEndpoint="galleryEndpoint"
/>
</div>
<template>
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.
Posted on May 2, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.