Last active
November 22, 2023 12:33
-
-
Save ChaseIngebritson/61596510c80479247366bcc87e3e0ef5 to your computer and use it in GitHub Desktop.
Convert a .webp image to be readable by Jimp
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
// This is a temporary fix until Jimp implements support for webp | |
// https://github.com/oliver-moran/jimp/issues/144 | |
// const img = await webpToJimp('https://test.com/img.webp', './tmp') | |
import fs from 'fs' | |
import axios from 'axios' | |
import jimp from 'jimp' | |
import webp from 'webp-converter' | |
export default async function webpToJimp (url, tempDir) { | |
// Verify that the img is a webp | |
if (!url.match(/(\.webp)/gi)) return jimp.read(url) | |
// Get the webp image | |
const response = await axios.get(url, { | |
responseType: 'stream' | |
}) | |
// Create the temporary directory if it doesn't exist | |
await fs.promises.mkdir(tempDir, { recursive: true }) | |
// Create a stream at the temporary directory and load the data into it | |
const file = fs.createWriteStream(`${tempDir}/tmp.webp`) | |
await response.data.pipe(file) | |
// Convert the webp image to a readable format | |
await webp.dwebp(`${tempDir}/tmp.webp`, `${tempDir}/tmp.png`, '-o') | |
// Read the newly created image | |
const img = await jimp.read(`${tempDir}/tmp.png`) | |
// Delete the temporary files | |
fs.unlink(`${tempDir}/tmp.webp`, () => {}) | |
fs.unlink(`${tempDir}/tmp.png`, () => {}) | |
return img | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That script made my day, thanks!