Created
September 12, 2024 19:07
-
-
Save arron21/d927c808820845df12eca46f3a75f812 to your computer and use it in GitHub Desktop.
Deno script for creating optimized images for the web and and their metadata
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Image } from "https://deno.land/x/imagescript@1.2.15/mod.ts"; | |
import { join } from "https://deno.land/std@0.220.0/path/mod.ts"; | |
const inputDir = join(Deno.cwd(), "src", "assets", "img", "gallery"); | |
const outputDir = join(Deno.cwd(), "src", "assets", "img", "gallery-opt"); | |
const imagesObjsArr = []; | |
/** | |
* Optimizes the images in the inputDir directory and saves them to the outputDir directory | |
* writes the optimized images metadata to a images.ts file in the outputDir directory | |
* | |
*/ | |
async function optimizeImages() { | |
const files = []; | |
for await (const dirEntry of Deno.readDir(inputDir)) { | |
if (dirEntry.isFile) { | |
files.push(dirEntry.name); | |
} | |
} | |
const images = files.filter(file => /\.(jpg|jpeg|png|webp|gif)$/i.test(file)); | |
for(let img of images) { | |
const imgData = await optimizeImgForWeb(`${inputDir}/${img}`, `${outputDir}/${img}`, 70, img) | |
imagesObjsArr.push(imgData) | |
} | |
const content = `export const images = ${JSON.stringify(imagesObjsArr)}`; | |
await Deno.writeTextFile(outputDir+'/images.ts', content); | |
} | |
/** | |
* Optimizes an image for the web in jpg format | |
* @param {*} inputPath | |
* @param {*} outputPath | |
* @param {*} quality | |
* @param {*} fileName | |
* @returns JSON object with image metadata | |
*/ | |
async function optimizeImgForWeb(inputPath, outputPath, quality = 70, fileName) { | |
try { | |
// Read the input file | |
const inputBuffer = await Deno.readFile(inputPath); | |
// Decode the image | |
const image = await Image.decode(inputBuffer); | |
image.resize(1000, Image.RESIZE_AUTO); | |
const outputImg = await image.encodeJPEG(quality); | |
await Deno.writeFile(outputPath, outputImg); | |
const obj = { | |
name: fileName, | |
width: image.width, | |
height: image.height | |
} | |
return obj; | |
} catch (error) { | |
console.error(`Error converting ${inputPath} to Optimized file:`, error); | |
} | |
} | |
if (import.meta.main) { | |
console.log(`Optimizing images please wait...`); | |
const t0 = performance.now(); | |
await optimizeImages(); | |
const t1 = performance.now(); | |
console.log(`Optimized ${imagesObjsArr.length} images in ${t1 - t0} milliseconds.`); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment