Skip to content

Instantly share code, notes, and snippets.

@dominictarr dominictarr/thumbnails.js
Last active Jan 1, 2018

Embed
What would you like to do?
test script for generating thumbnails in an electron app
//updated to save thumbnails!
var h = require('hyperscript')
var fs = require('fs')
var pull = require('pull-stream')
var paramap = require('pull-paramap')
var path = require('path')
//XXX note, I added `module.exports = downsample` to the bottom of this file, TODO: make PR
var downsample = require('downscale/src/downsample')
var dir = process.argv[2], pool = []
fs.readdir(dir, function (err, ls) {
var canvas = document.createElement('canvas')
var canvas2 = document.createElement('canvas')
canvas.width = 50
canvas.height = 50
var ctx = canvas.getContext('2d')
var start = Date.now()
document.head.appendChild(h('style', {textContent: 'body { margin: 0px; line-height: 0px; }'}))
var content = h('div')
var perf = h('h1'), size = 0, size2 = 0
document.body.appendChild(h('div', perf, content))
try {
fs.mkdirSync(path.join(dir, '.thumbnails'))
} catch (_) {}
pull(
pull.values(ls),
paramap(function (file, cb) {
var base = path.basename(file)
var thumbnail = path.join(dir,'.thumbnails', file)
fs.stat(thumbnail, function (err, stat) {
if(err) return cb(null, file)
else return cb(null, thumbnail)
})
}),
paramap(function (file, cb) {
if(/.thumbnail/.test(file)) return cb(null, h('img', {src: file}))
var img = pool.length ? pool.shift() : h('img')
img.src = path.resolve(dir, file)
img.onload = function (ev) {
var size = Math.min(img.width, img.height)
size2 += img.width * img.height
if(true) {
ctx.drawImage(img, (img.width - size)/2, (img.height - size)/2, size, size, 0, 0, canvas.width, canvas.height)
} else {
//
canvas2.width = size
canvas2.height = size
var ctx2 = canvas2.getContext('2d')
ctx2.drawImage(img, (img.width - size)/2, (img.height - size)/2, size, size, 0, 0, size, size)
ctx.putImageData(downsample(ctx2.getImageData(0,0,size,size), canvas.width, canvas.height, 0, 0, size, size), 0, 0)
}
img.onerror = img.onload = null
pool.push(img)
var data = canvas.toDataURL('image/jpg')
data = data.substring(data.indexOf(',')+1)
var thumbnail = path.join(dir, '.thumbnails', file)
fs.writeFile(thumbnail, new Buffer(data, 'base64'), function (err) {
cb(null, h('img', {src: thumbnail}))
})
}
img.onerror = function (ev) {
cb(null)
}
}, 32, false),
pull.filter(),
pull.drain(function (img) {
content.appendChild(img)
var count = content.children.length
var time = (Date.now()-start)/1000
size += (Math.round(img.src.length/1000))/1000
perf.textContent = [count, size.toString().substring(0, 5), ((Math.round(size2/1000))/1000).toString().substring(0, 5), time, count/time].join(', ')
}, function (err) {
if(err) throw err
})
)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.