Creating Animated Fade Away gifs from Image

Eugene Musebe

This Mediajam showcases how to transform an image to gif as a fadeout using cloudinary API's in combination with typescript Nextjs

Codesandbox

The final project can be viewed on Codesandbox.

You can find the full source code on my Github repository.

Project initialization and setup

Initiatilization of next js with typescript project

First, we initialize an empty next js project.

Using the commands below. The command will prompt you to name your project.

1npx create-next-app@latest --typescript
2
3# or
4
5yarn create next-app --typescript

Once initialization is complete you can confirm that the initial setup is complete by running.

1yarn dev
2
3# OR
4
5npm run dev

After running the above command visit localhost port 3000

Dependencies definitions and additions

  1. html2canvas

  2. cloudinary

  3. gifshot

  4. styled-components

1yarn add html2canvas
2
3yarn add gifshot
4
5yarn add cloudinary
6
7yarn add styled-components

Additional setup for gifshot

Add the following line of code in the ./pages/api/decs.d.ts file

To enable the import and export of the module within the project

1declare module "gifshot";

Development steps

  • Setup demonstration image in the public folder.

  • link the image to an image tag in the App class renderer

  • Retrieve the html image tag and convert the element to the canvas using the html2canvas library

  • Generate 6 other canvases (Due to storage constraints) while fading out the pixels in each canvas.

  • Take the generated list of canvases to convert them into data urls array

  • Combine the images to gif using gifshot library

  • Upload the generated video/gif to cloudinary for storage.

  • Display the generated fadeout/disintegration gif

link the image to an image tag in the App class renderer

1<Main>
2
3<div className="inner">
4
5{loading ? (
6
7<div>Processing ... </div>
8
9) : (
10
11<Image
12
13id="world"
14
15src={gif_image ? gif_image : `/goat.jpg`}
16
17alt=""
18
19/>
20
21)}
22
23<br />
24
25{url ? <div>{url}</div> : ""}
26
27{!loading && <button onClick={this.snap.bind(this)}>Snap</button>}
28
29</div>
30
31</Main>

Retrieve the html image tag and convert the element to the canvas using the html2canvas library

1// convert img tag to canvas
2
3const canvas = await html2canvas(img as HTMLElement);
4
5const ctx = canvas.getContext("2d");
6
7if (!ctx) return;
8
9// Getting image data from the canvas for pixel manipulation
10
11const image_data = ctx.getImageData(0, 0, canvas.width, canvas.height);
12
13if (!image_data) return;
14
15const pixel_arr = image_data.data;

Generate 6 other canvases while fading out the pixels in each canvas

1const image_data_array = this.createBlankImageArray(image_data);
2
3//put pixel info to imageDataArray (Weighted Distributed)
4
5for (let i = 0; i < pixel_arr.length; i++) {
6
7const p = Math.floor((i / pixel_arr.length) * CANVAS_COUNT);
8
9
10
11const dist = Math.round(Math.random() * (CANVAS_COUNT - 1));
12
13
14
15const a = image_data_array[dist];
16
17a[i] = pixel_arr[i];
18
19a[i + 1] = pixel_arr[i + 1];
20
21a[i + 2] = pixel_arr[i + 2];
22
23a[i + 3] = pixel_arr[i + 3];
24
25}

Take the generated list of canvases to convert them into data urls array

1// fadeout image list generation and mapping
2
3const images = new Array(CANVAS_COUNT)
4
5.fill(0)
6
7.map((_, i) =>
8
9this.createCanvasFromImageData(
10
11image_data_array[i],
12
13canvas.width,
14
15canvas.height
16
17).toDataURL()
18
19);

Combine the images into gifs using the gifshot library

1gifshot.createGIF(
2
3{
4
5images,
6
7gifWidth: canvas.width,
8
9gifHeight: canvas.height,
10
11numFrames: CANVAS_COUNT
12
13},
14
15(obj: any) => {
16
17if (obj.error) {
18
19console.log(obj.error);
20
21return;
22
23}
24
25console.log(obj.image);
26
27this.uploadVideoCloudinary(obj.image);
28
29this.setState({ gif_image: obj.image, loading: false });
30
31}
32
33);

Upload the generated video/gif to cloudinary for storage

This article will use cloudinary for media upload and storage. Use this link to access the cloudinary website and sign up or log in to receive your environment variables(Cloud name, API Key, and API Secret). The mentioned variables will be found in your dashboard which should look like the below:

.

Create a file named .env at the root of your project. The file is where we store our environment variables. Paste the following code into the file

1CLOUDINARY_NAME = ""
2
3
4
5CLOUDINARY_API_KEY = ""
6
7
8
9CLOUDINARY_API_SECRET= ""

Ensure to fill in the blanks with your respective environment variables then restart the project server for the project to update its env.

Head to the ./pages/api directory and create a file named upload.tsx. In the file, we will access the cloudinary API to upload our files and receive the cloudinary file URL.

Start by including the necessary imports

1import type { NextApiRequest, NextApiResponse } from 'next'
2
3var cloudinary = require('cloudinary').v2

Integrate your environment variables with the API backend like below:

1cloudinary.config({
2
3cloud_name: process.env.CLOUDINARY_NAME,
4
5api_key: process.env.CLOUDINARY_API_KEY,
6
7api_secret: process.env.CLOUDINARY_API_SECRET,
8
9});

Since we are using typescript, we will include a type system to represent the type of value that will be used in our backend. In our case, the value will be a string.

1type Data = {
2
3name: string
4
5}

We can then introduce a handler function that receives a post request and processes response feedback for our front end.

1// https://rv7py.sse.codesandbox.io/
2
3export default async function handler(
4
5req: NextApiRequest,
6
7res: NextApiResponse<Data>
8
9) {
10
11if (req.method === "POST") {
12
13let fileStr: string = req.body.data;
14
15let uploadResponse: any;
16
17
18
19try {
20
21uploadResponse = await cloudinary.uploader.upload_large(fileStr, {
22
23resource_type: "auto",
24
25chunk_size: 6000000,
26
27timeout: 60000
28
29});
30
31console.log(uploadResponse);
32
33} catch (err) {
34
35console.log(err);
36
37}
38
39res.status(200).json({ name: "" + uploadResponse.secure_url });
40
41}
42
43}

The code above receives the request body and uploads it to cloudinary. It then captures the sent file's cloudinary URL and sends it back to the front end as a response.

That's it! we've completed our project backend.

Eugene Musebe

Software Developer

I’m a full-stack software developer, content creator, and tech community builder based in Nairobi, Kenya. I am addicted to learning new technologies and loves working with like-minded people.