1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| 'use strict';
const node_fetch = require("node-fetch"); const logger = require('hexo-log').default(); const fs = require('hexo-fs'); const frontMatter = require('hexo-front-matter');
hexo.extend.filter.register('before_post_render', async function (Posts) { const config = hexo.config.imageColor || hexo.theme.config.imageColor
if (!Posts.cover || Posts.main_color || !config.enable) return;
try { const color_API = config.api_url; const imageUrl = Posts.cover; const dominantColor = color_API + imageUrl; let adjustedColor;
await node_fetch(dominantColor) .then(response => { if (!response.ok) return;
return response.json(); }) .then(data => { const ImgColorHex = colorHex(data.RGB); adjustedColor = ImgColorHex;
if (!config.log == true) { logger.info(`文章《${Posts.title}》的主色调:${adjustedColor}`); }
Posts.main_color = adjustedColor;
if (/\.md$/.test(Posts.source)) { const parsedPost = frontMatter.parse(Posts.raw);
parsedPost.main_color = adjustedColor;
const processedPostStr = frontMatter.stringify(parsedPost); const updatedContent = '---\n' + processedPostStr;
fs.writeFile(Posts.full_source, updatedContent, 'utf-8'); } }) .catch(error => { logger.error(`提取文章《${Posts.title}》封面图像的主题颜色时出错: ${error}`); }); } catch (error) { logger.error(`提取文章《${Posts.title}》封面图像的主题颜色时出错: ${error}`); }
return Posts; });
const colorHex = str => { const hexRegex = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
if (/^(rgb|RGB)/.test(str)) { const aColor = str.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(","); return aColor.reduce((acc, val) => { const hex = Number(val).toString(16).padStart(2, "0"); return acc + hex; }, "#"); }
if (hexRegex.test(str)) { if (str.length === 4) { return Array.from(str.slice(1)).reduce((acc, val) => acc + val + val, "#"); } return str; }
return str; };
|