Created
October 10, 2024 08:10
-
-
Save abel533/68abae6a8311286532759f17279fe3b2 to your computer and use it in GitHub Desktop.
Hexo插件,将图片转换为webp格式
This file contains hidden or 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 path = require('path'); | |
const sharp = require('sharp'); | |
var fs = require('hexo-fs'); | |
//检测文章内的图片,将不是webp格式的图片转换为webp格式 | |
hexo.extend.filter.register('before_post_render', function(data){ | |
var log = this.log; | |
const title = data.title; | |
log.i("WebP Convert Filter: " + title); | |
const convertImages = new Set(); | |
// detect ![]() pattern and convert path | |
let raw = data.raw.replace(/!\[([^\[\]]*)\]\((.*?)\s?(?:".*")?\)/g, | |
function(match_str, label, imagePath){ | |
if(!imagePath) return match_str; | |
const imageExt = path.extname(imagePath); | |
if (imageExt !== '.webp') { | |
let imageFullPath; | |
if(imagePath.startsWith('/')) { | |
imageFullPath = path.join(data.full_source.substring(0, | |
data.full_source.lastIndexOf('source' + path.sep) + ('source' + path.sep).length), imagePath); | |
} else { | |
imageFullPath = path.resolve(data.full_source.substring(0, data.full_source.lastIndexOf(path.sep)), imagePath); | |
} | |
imageFullPath = decodeURIComponent(imageFullPath); | |
if (!fs.existsSync(imageFullPath)) { | |
log.i("Image file does not exist: " + imageFullPath); | |
return match_str; | |
} | |
if (!convertImages.has(imageFullPath)) { | |
convertImages.add(imageFullPath); | |
log.i("Markdown Image Path: " + imageFullPath); | |
sharp(imageFullPath) | |
.toFormat('webp') | |
.toFile(imageFullPath.replace(imageExt, '.webp')) | |
.then(() => { | |
fs.unlink(imageFullPath, (err) => { | |
if (err) { | |
log.e(`Error deleting original image: ${err}`); | |
} else { | |
log.i(`Original image deleted: ${imagePath}`); | |
} | |
}); | |
}) | |
.catch((err) => { | |
console.error(`Error converting [${title}] image [${imageFullPath}] to webp: ${err}`); | |
}); | |
} else { | |
log.i("Already converted: " + imageFullPath); | |
} | |
return match_str.replace(imageExt, '.webp'); | |
} | |
return match_str; | |
}); | |
if (raw !== data.raw) { | |
data.raw = raw; | |
fs.writeFile(data.full_source, raw, (err) => { | |
if (err) { | |
log.e(`Error writing raw to file: ${err}`); | |
} else { | |
log.i(`raw written to file: ${data.full_source}`); | |
} | |
}); | |
} | |
return data; | |
}, 9); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment