Created
April 22, 2020 08:22
-
-
Save fvisticot/f0634c0aab3d157d1ff9b4610e76516b to your computer and use it in GitHub Desktop.
BlurHash test
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
const blurhash = require('blurhash'); | |
const { createCanvas, loadImage, Image } = require('canvas') | |
const getImageData = (image) => { | |
const canvas = createCanvas(image.width, image.height) | |
const context = canvas.getContext('2d') | |
context.drawImage(image, 0, 0) | |
return context.getImageData(0, 0, image.width, image.height) | |
} | |
const encodeImageToBlurhash = async image => { | |
const imageData = getImageData(image); | |
console.log(`${imageData.width} ${imageData.height}`); | |
const hash= blurhash.encode(imageData.data, imageData.width, imageData.height, 4, 4); | |
return hash; | |
}; | |
async function decodeBlurhash(imagehash, width, height, filename) { | |
const pixels = blurhash.decode(imagehash, width, height); | |
const canvas = createCanvas(width, height); | |
const context = canvas.getContext('2d') | |
const imageData = context.createImageData(width, height); | |
imageData.data.set(pixels); | |
context.putImageData(imageData, 0, 0); | |
var fs = require('fs') | |
, out = fs.createWriteStream(__dirname + '/' + filename) | |
, stream = canvas.pngStream(); | |
stream.on('data', function(chunk){ | |
out.write(chunk); | |
}); | |
stream.on('end', function(){ | |
console.log('saved png'); | |
}); | |
} | |
async function testImage(imageUrl) { | |
const image = await loadImage(imageUrl); | |
const imageHash= await encodeImageToBlurhash(image); | |
await decodeBlurhash(imageHash, image.width, image.height, 'test3.png'); | |
} | |
testImage('https://www.echosdunet.net/sites/default/files/styles/article/public/test-ping.png?itok=dQ_Mhhq9'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment