Manga-Reader icon indicating copy to clipboard operation
Manga-Reader copied to clipboard

一个简单暴力获取缩略图的工具函数

Open wing-kai opened this issue 9 years ago • 0 comments

只适用于像electron框架这种node与webkit结合的环境使用

const fs = require('fs');
const canvas = document.createElement('canvas');
const image = new Image();

const scale = image => {
    return 600 / (image.width > image.height ? image.width : image.height)
}

image.onload = event => {
    const tempCanvas = document.createElement('canvas');
    const context = tempCanvas.getContext('2d');

    canvas.width = Math.trunc(image.width * scale(image));
    canvas.height = Math.trunc(image.height * scale(image));
    tempCanvas.width = image.width * 0.5;
    tempCanvas.height = image.height * 0.5;

    context.drawImage(image, 0, 0, tempCanvas.width, tempCanvas.height);
    context.drawImage(tempCanvas, 0, 0, tempCanvas.width * 0.5, tempCanvas.height * 0.5);
    canvas.getContext('2d').drawImage(
        tempCanvas,
        0, 0,
        tempCanvas.width * 0.5,
        tempCanvas.height * 0.5,
        0, 0,
        Math.trunc(image.width * scale(image)),
        Math.trunc(image.height * scale(image))
    );

    fs.writeFile(
        './thumbnail.png',
        canvas.toDataURL("image/png").replace(/^data:image\/png;base64,/,""),
        'base64',
        err => {
            if (err)
                console.error(err);
        }
    )

    // 附加预览用
    document.body.appendChild(canvas);
};

image.src = "./example.png";

wing-kai avatar Feb 12 '16 17:02 wing-kai