Convert JPG/PNG Image to Pixelated & Blurred Image Using Node.js ImageMagick Express.js

npm init -y
npm i express
npm i multer

Just make a uploads directory where all the input image files will be stored

index.js

const express = require('express')

const multer = require('multer')

const {exec} = require('child_process')

const path = require('path')

const app = express()

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, 'uploads')
    },
    filename: function (req, file, cb) {
      cb(null, Date.now() + path.extname(file.originalname)) //Appending extension
    }
  })
  
var upload = multer({ storage: storage }).single('file')

app.post('/pixelatedimage',(req,res) => {
    let output = Date.now() + "output.jpg"
    upload(req,res,(err) => {
        if(err){
            console.log("Error in uploading file")
        }else{
            console.log(req.file.path)

            exec(`magick convert -scale 10% -scale 1000% ${req.file.path} ${output}`,(err,stdout,stderr) => {
                if(err){
                    console.log("Error takes place in processing image")
                }else{
                    res.download(output,(err) => {
                        
                    })
                }
            })
        }
    })
})

app.get('/',(req,res) => {
    res.sendFile(__dirname + "/index.html")
})

app.listen(5000,() => {
    console.log("App is listening on port 5000")
})

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image to Pixelated Image</title>
</head>
<body>
    <form action="/pixelatedimage" method="post" enctype="multipart/form-data">
        <input type="file" name="file" id="" required>
        <button>Download Pixelated Image</button>
    </form>
</body>
</html>

Run the Project

node index.js

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.