hexo-bitiful-toolkit 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +82 -0
- package/dist/index.js +1 -0
- package/package.json +18 -0
package/README.md
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# Bitiful_toolkit
|
|
2
|
+
|
|
3
|
+
## Intro
|
|
4
|
+
|
|
5
|
+
> [!NOTE]
|
|
6
|
+
>
|
|
7
|
+
> A very compact representation of an image placeholder. Store it inline with your data and show it while the real image is loading for a smoother loading experience. It's similar to BlurHash but with the following advantages:
|
|
8
|
+
>
|
|
9
|
+
> - Encodes more detail in the same space
|
|
10
|
+
> - Also encodes the aspect ratio
|
|
11
|
+
> - Gives more accurate colors
|
|
12
|
+
> - Supports images with alpha
|
|
13
|
+
> - Despite doing all of these additional things, the code for ThumbHash is still similar in complexity to the code for BlurHash. One potential drawback compared to BlurHash is that the parameters of the algorithm are not configurable (everything is automatically configured).
|
|
14
|
+
>
|
|
15
|
+
> The code for this is available at https://github.com/evanw/thumbhash and contains implementations for JavaScript, Rust, Swift, and Java. You can use npm install thumbhash to install the JavaScript package and cargo add thumbhash to install the Rust package.
|
|
16
|
+
>
|
|
17
|
+
> <img width="1760" height="640" alt="1756906220972" src="https://github.com/user-attachments/assets/74f6a198-9ed7-4374-9522-c2efc7fac852" />
|
|
18
|
+
|
|
19
|
+
progressive_image 会请求 bitiful server,拿到 thumbhash base64 text,多次运行可能会浪费请求次数,bitiful 计费参考[计费概述 - 缤纷云文档](https://docs.bitiful.com/prices/basic#%E5%85%8D%E8%B4%B9%E9%A2%9D%E5%BA%A6)
|
|
20
|
+
因此本地测试环境设置不启用;如需开启,设置`$env.CI = true`,CI/CD Pipeline 同理;
|
|
21
|
+
|
|
22
|
+
```js
|
|
23
|
+
if (
|
|
24
|
+
!hexo.config.bitiful_toolkit ||
|
|
25
|
+
!hexo.config.bitiful_toolkit.enable ||
|
|
26
|
+
process.env.CI !== "true"
|
|
27
|
+
) {
|
|
28
|
+
//
|
|
29
|
+
log.info("[BITIFUL] Skip Image Processing...");
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
本次测试时,可以直接运行`bun run test`,在浏览器打开`/test/output/index.html`查看效果。效果如图所示
|
|
35
|
+
|
|
36
|
+
[README.webm](https://github.com/user-attachments/assets/90dc98bd-37e0-4f44-b761-1772bcd63343)
|
|
37
|
+
|
|
38
|
+
## TODO-List
|
|
39
|
+
|
|
40
|
+
- [x] config.yaml 中 bitiful_toolkit 新增 env_name 选项,可自定义环境变量名
|
|
41
|
+
- [x] 缓存 img_url: data-url 键值对到本地文件(`.thumbcache.json`)
|
|
42
|
+
- 每次 build 前,从 hexo 根目录加载缓存文件到内存。
|
|
43
|
+
- 在获取 img url 对应的 data-url 前,先检查本地缓存是否存在 img_url 对应的 data-url
|
|
44
|
+
- 如果存在,直接使用 data-url
|
|
45
|
+
- 否则,请求 bitiful 服务获取 thumbhash base64 text,并转换为 data-url 后存储到本地缓存
|
|
46
|
+
- build 完成后,将更新的缓存文件保存到 hexo 根目录,供下次使用
|
|
47
|
+
|
|
48
|
+
## Setup
|
|
49
|
+
|
|
50
|
+
`bun add git+https://github.com/Efterklang/Bitiful_Responsive_And_Progressive_Image`
|
|
51
|
+
|
|
52
|
+
```yaml config.yaml
|
|
53
|
+
bitiful_toolkit:
|
|
54
|
+
enable: true
|
|
55
|
+
env_name: "CI" # 如果存在环境变量CI的值为true,才进行图片处理
|
|
56
|
+
all: false
|
|
57
|
+
srcset_widths: [200, 400, 600, 800, 1200, 2000, 3000]
|
|
58
|
+
add_max_width: false
|
|
59
|
+
max_widths: "(max-width: 600px) 100vw, (max-width: 1200px) 50vw, 800px"
|
|
60
|
+
enable_lazy_loading: true
|
|
61
|
+
lazy_skip_first: 2
|
|
62
|
+
supported_domains: ["assets.vluv.space", "s3.bitiful.net", "bitiful.com"]
|
|
63
|
+
exclude_formats: ['svg', 'gif'],
|
|
64
|
+
inject_css: true
|
|
65
|
+
cache:
|
|
66
|
+
enable: true
|
|
67
|
+
cache_file: ".thumbcache.json" # 缓存文件名,存储在hexo根目录
|
|
68
|
+
cache_key: "img_src" # 缓存键名选择,可选: "img_src" 或 "img_filename"
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### 缓存功能说明
|
|
72
|
+
|
|
73
|
+
新增的缓存功能可以将图片 URL 到 data-url 的映射关系缓存到本地文件,避免重复请求 Bitiful 服务:
|
|
74
|
+
|
|
75
|
+
- 构建开始前:自动从 hexo 根目录加载缓存文件
|
|
76
|
+
- 图片处理时:优先检查缓存,命中则直接使用,未命中才请求 Bitiful API
|
|
77
|
+
- 构建结束后:将更新的缓存文件保存到 hexo 根目录
|
|
78
|
+
|
|
79
|
+
## Ref
|
|
80
|
+
|
|
81
|
+
- [ThumbHash: A very compact representation of an image placeholder](https://evanw.github.io/thumbhash/)
|
|
82
|
+
- [图像 BlurHash 与 ThumbHash 哈希占位技术: - 缤纷云文档](https://docs.bitiful.com/bitiful-s4/features/hash-placeholder)
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var Y=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var xe=Object.prototype.hasOwnProperty;var ye=(t,e)=>()=>(t&&(e=t(t=0)),e);var ae=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),be=(t,e)=>{for(var a in e)Y(t,a,{get:e[a],enumerable:!0})},Ie=(t,e,a,l)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of me(e))!xe.call(t,s)&&s!==a&&Y(t,s,{get:()=>e[s],enumerable:!(l=_e(e,s))||l.enumerable});return t};var Fe=t=>Ie(Y({},"__esModule",{value:!0}),t);var oe={};be(oe,{rgbaToDataURL:()=>ie,rgbaToThumbHash:()=>Le,thumbHashToApproximateAspectRatio:()=>le,thumbHashToAverageRGBA:()=>Te,thumbHashToDataURL:()=>$e,thumbHashToRGBA:()=>se});function Le(t,e,a){if(t>100||e>100)throw new Error(`${t}x${e} doesn't fit in 100x100`);let{PI:l,round:s,max:o,cos:n,abs:r}=Math,h=0,d=0,p=0,c=0;for(let m=0,_=0;m<t*e;m++,_+=4){let g=a[_+3]/255;h+=g/255*a[_],d+=g/255*a[_+1],p+=g/255*a[_+2],c+=g}c&&(h/=c,d/=c,p/=c);let f=c<t*e,K=f?5:7,E=o(1,s(K*t/o(t,e))),z=o(1,s(K*e/o(t,e))),k=[],U=[],M=[],N=[];for(let m=0,_=0;m<t*e;m++,_+=4){let g=a[_+3]/255,v=h*(1-g)+g/255*a[_],i=d*(1-g)+g/255*a[_+1],u=p*(1-g)+g/255*a[_+2];k[m]=(v+i+u)/3,U[m]=(v+i)/2-u,M[m]=v-i,N[m]=g}let D=(m,_,g)=>{let v=0,i=[],u=0,y=[];for(let x=0;x<g;x++)for(let A=0;A*g<_*(g-x);A++){let O=0;for(let $=0;$<t;$++)y[$]=n(l/t*A*($+.5));for(let $=0;$<e;$++)for(let Q=0,ge=n(l/e*x*($+.5));Q<t;Q++)O+=m[Q+$*t]*y[Q]*ge;O/=t*e,A||x?(i.push(O),u=o(u,r(O))):v=O}if(u)for(let x=0;x<i.length;x++)i[x]=.5+.5/u*i[x];return[v,i,u]},[G,w,V]=D(k,o(3,E),o(3,z)),[W,J,X]=D(U,3,3),[S,q,j]=D(M,3,3),[R,H,P]=f?D(N,5,5):[],B=t>e,b=s(63*G)|s(31.5+31.5*W)<<6|s(31.5+31.5*S)<<12|s(31*V)<<18|f<<23,C=(B?z:E)|s(63*X)<<3|s(63*j)<<9|B<<15,F=[b&255,b>>8&255,b>>16,C&255,C>>8],L=f?6:5,T=0;f&&F.push(s(15*R)|s(15*P)<<4);for(let m of f?[w,J,q,H]:[w,J,q])for(let _ of m)F[L+(T>>1)]|=s(15*_)<<((T++&1)<<2);return new Uint8Array(F)}function se(t){let{PI:e,min:a,max:l,cos:s,round:o}=Math,n=t[0]|t[1]<<8|t[2]<<16,r=t[3]|t[4]<<8,h=(n&63)/63,d=(n>>6&63)/31.5-1,p=(n>>12&63)/31.5-1,c=(n>>18&31)/31,f=n>>23,K=(r>>3&63)/63,E=(r>>9&63)/63,z=r>>15,k=l(3,z?f?5:7:r&7),U=l(3,z?r&7:f?5:7),M=f?(t[5]&15)/15:1,N=(t[5]>>4)/15,D=f?6:5,G=0,w=(B,b,C)=>{let F=[];for(let L=0;L<b;L++)for(let T=L?0:1;T*b<B*(b-L);T++)F.push(((t[D+(G>>1)]>>((G++&1)<<2)&15)/7.5-1)*C);return F},V=w(k,U,c),W=w(3,3,K*1.25),J=w(3,3,E*1.25),X=f&&w(5,5,N),S=le(t),q=o(S>1?32:32*S),j=o(S>1?32/S:32),R=new Uint8Array(q*j*4),H=[],P=[];for(let B=0,b=0;B<j;B++)for(let C=0;C<q;C++,b+=4){let F=h,L=d,T=p,m=M;for(let i=0,u=l(k,f?5:3);i<u;i++)H[i]=s(e/q*(C+.5)*i);for(let i=0,u=l(U,f?5:3);i<u;i++)P[i]=s(e/j*(B+.5)*i);for(let i=0,u=0;i<U;i++)for(let y=i?0:1,x=P[i]*2;y*U<k*(U-i);y++,u++)F+=V[u]*H[y]*x;for(let i=0,u=0;i<3;i++)for(let y=i?0:1,x=P[i]*2;y<3-i;y++,u++){let A=H[y]*x;L+=W[u]*A,T+=J[u]*A}if(f)for(let i=0,u=0;i<5;i++)for(let y=i?0:1,x=P[i]*2;y<5-i;y++,u++)m+=X[u]*H[y]*x;let _=F-2/3*L,g=(3*F-_+T)/2,v=g-T;R[b]=l(0,255*a(1,g)),R[b+1]=l(0,255*a(1,v)),R[b+2]=l(0,255*a(1,_)),R[b+3]=l(0,255*a(1,m))}return{w:q,h:j,rgba:R}}function Te(t){let{min:e,max:a}=Math,l=t[0]|t[1]<<8|t[2]<<16,s=(l&63)/63,o=(l>>6&63)/31.5-1,n=(l>>12&63)/31.5-1,h=l>>23?(t[5]&15)/15:1,d=s-2/3*o,p=(3*s-d+n)/2,c=p-n;return{r:a(0,e(1,p)),g:a(0,e(1,c)),b:a(0,e(1,d)),a:h}}function le(t){let e=t[3],a=t[2]&128,l=t[4]&128,s=l?a?5:7:e&7,o=l?e&7:a?5:7;return s/o}function ie(t,e,a){let l=t*4+1,s=6+e*(5+l),o=[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,t>>8,t&255,0,0,e>>8,e&255,8,6,0,0,0,0,0,0,0,s>>>24,s>>16&255,s>>8&255,s&255,73,68,65,84,120,1],n=[0,498536548,997073096,651767980,1994146192,1802195444,1303535960,1342533948,-306674912,-267414716,-690576408,-882789492,-1687895376,-2032938284,-1609899400,-1111625188],r=1,h=0;for(let d=0,p=0,c=l-1;d<e;d++,c+=l-1)for(o.push(d+1<e?0:1,l&255,l>>8,~l&255,l>>8^255,0),h=(h+r)%65521;p<c;p++){let f=a[p]&255;o.push(f),r=(r+f)%65521,h=(h+r)%65521}o.push(h>>8,h&255,r>>8,r&255,0,0,0,0,0,0,0,0,73,69,78,68,174,66,96,130);for(let[d,p]of[[12,29],[37,41+s]]){let c=-1;for(let f=d;f<p;f++)c^=o[f],c=c>>>4^n[c&15],c=c>>>4^n[c&15];c=~c,o[p++]=c>>>24,o[p++]=c>>16&255,o[p++]=c>>8&255,o[p++]=c&255}return"data:image/png;base64,"+btoa(String.fromCharCode(...o))}function $e(t){let e=se(t);return ie(e.w,e.h,e.rgba)}var ce=ye(()=>{});var te=ae((je,re)=>{var Z=require("fs/promises"),ne=require("path"),ee=class{constructor(e={}){this.config={enable:!1,cache_file:".thumbcache.json",hexo_root:process.cwd(),cache_key_type:"img_src",...e},this.cache={},this.isDirty=!1,this.cacheFilePath=ne.join(this.config.hexo_root,this.config.cache_file),this.stats={apiRequests:0,cacheHits:0}}generateCacheKey(e){if(this.config.cache_key_type==="img_filename"){let a=new URL(e);return ne.basename(a.pathname)}else return e}async loadCacheFromFile(){try{if(console.log("[BITIFUL] Loading cache from local file..."),await Z.access(this.cacheFilePath).then(()=>!0).catch(()=>!1)){let e=await Z.readFile(this.cacheFilePath,"utf8");this.cache=JSON.parse(e||"{}"),console.log(`[BITIFUL] Cache loaded from ${this.cacheFilePath}, ${Object.keys(this.cache).length} items`)}else console.log("[BITIFUL] Cache file not found, starting with empty cache"),this.cache={};return!0}catch(e){return console.warn("[BITIFUL] Failed to load cache from file:",e.message),this.cache={},!1}}async saveCacheToFile(){if(!this.config.enable||!this.isDirty)return console.log("[BITIFUL] Skipping cache save: disabled or no changes"),!1;try{console.log("[BITIFUL] Saving cache to local file...");let e=JSON.stringify(this.cache,null,2);return Z.writeFileSync(this.cacheFilePath,e,"utf8"),console.log(`[BITIFUL] Cache saved to ${this.cacheFilePath}, ${Object.keys(this.cache).length} items`),this.isDirty=!1,!0}catch(e){return console.warn("[BITIFUL] Failed to save cache to file:",e.message),!1}}getCachedDataURL(e){let a=this.generateCacheKey(e);return this.cache[a]?(this.stats.cacheHits++,this.cache[a]):(this.stats.apiRequests++,null)}setCachedDataURL(e,a){let l=this.generateCacheKey(e);a&&this.cache[l]!==a&&(this.cache[l]=a,this.isDirty=!0)}getStats(){let e=this.stats.apiRequests+this.stats.cacheHits;return{totalItems:Object.keys(this.cache).length,isDirty:this.isDirty,cacheEnabled:this.config.enable,...this.stats,totalRequests:e,cacheHitRate:e>0?(this.stats.cacheHits/e*100).toFixed(1):0}}};re.exports=ee});var ue=ae((Pe,fe)=>{var{thumbHashToDataURL:Ue}=(ce(),Fe(oe)),He=te();function Be(t){try{let e=t.replace(/\s/g,""),a=atob(e),l=new Uint8Array(a.length);for(let s=0;s<a.length;s++)l[s]=a.charCodeAt(s);return l}catch(e){throw new Error(`Base64 decode failed: ${e.message}`)}}async function Ce(t,e=null){file_name=t.split("/").pop().split("?")[0];try{if(e){let r=e.getCachedDataURL(t);if(r)return r}console.log(`[BITIFUL] \u274C ${file_name} \u7F13\u5B58\u672A\u547D\u4E2D\uFF0C\u6B63\u5728\u83B7\u53D6...`);let a=`${t.split("?")[0]}?fmt=thumbhash`,s=await(await fetch(a)).text(),o=Be(s.trim()),n=Ue(o);return e&&n&&(console.log(`[BITIFUL] \u5C06${t}\u53CA\u5176\u5BF9\u5E94\u7684dataUrl\u5199\u5165\u7F13\u5B58`),e.setCachedDataURL(t,n)),n}catch(a){return console.warn("Failed to generate thumbhash:",a.message),null}}function he(t,e,a){let l=e.some(n=>t.includes(n)),s=t.split(".").pop().split("?")[0].toLowerCase(),o=!a.includes(s);return l&&o}function ve(t,e,a,l,s){let o=a.srcset_widths.map(d=>`${e.includes("?")?`${e}&w=${d}`:`${e}?w=${d}`} ${d}w`).join(", "),n=t.replace(/<img\s+/,"").replace(/\s*\/?>$/,"").replace(/src="[^"]*"\s*/,""),r=`${[`<img src="${e}" srcset="${o}"`,a.add_max_width?`sizes="${a.max_widths}"`:"",l?'loading="lazy" decoding="async"':"",`onload="this.classList.add('loaded')"`,n].filter(Boolean).join(" ")}>`,h=`<img class="thumbhash-placeholder" src="${s}">`;return s?`<div class="progressive_img_container">${r}${h}</div>`:r}var we=async(t,e={})=>{let a={srcset_widths:[200,400,600,800,1200,2e3,3e3],add_max_width:!1,max_widths:"(max-width: 600px) 100vw, (max-width: 1200px) 50vw, 800px",enable_lazy_loading:!0,lazy_skip_first:2,supported_domains:["assets.vluv.space","s3.bitiful.net","bitiful.com"],exclude_formats:["svg","gif"],cache:{enable:!1,...e.cache},...e},l=global.bitifulCacheInstance,s=/<img[^>]+src="(.+?)"[^>]*>/gm,o=[...t.matchAll(s)],n=await Promise.all(o.map(([,h])=>he(h,a.supported_domains,a.exclude_formats)?Ce(h,l):null)),r=0;return t.replace(s,(h,d)=>{if(!he(d,a.supported_domains,a.exclude_formats))return h;let p=a.enable_lazy_loading&&++r>a.lazy_skip_first,c=n[r-1];return ve(h,d,a,p,c)})};fe.exports=we});var de=ue(),qe=te(),Re=require("fs").promises.readFile,{join:Ae}=require("path"),I=hexo.log,pe,ke=((pe=hexo.config.bitiful_toolkit)==null?void 0:pe.env_name)||"CI";function De(){var e;if(!hexo.config.bitiful_toolkit||!hexo.config.bitiful_toolkit.enable||process.env[ke]!=="true")return;let t=null;(e=hexo.config.bitiful_toolkit.cache)!=null&&e.enable&&(t=new qe({...hexo.config.bitiful_toolkit.cache,hexo_root:hexo.base_dir}),global.bitifulCacheInstance=t,hexo.extend.filter.register("before_generate",async()=>{I.info("[BITIFUL] Initializing thumbhash cache..."),await t.loadCacheFromFile();let a=t.getStats();I.info(`[BITIFUL] Cache initialized with ${a.totalItems} items`)},8),hexo.extend.filter.register("after_generate",async()=>{if(t){let a=t.getStats();I.info("[BITIFUL] \u56FE\u7247\u5904\u7406\u5B8C\u6210\u7EDF\u8BA1:"),I.info(`[BITIFUL] - \u603B\u8BF7\u6C42\u6570: ${a.totalRequests}`),I.info(`[BITIFUL] - \u5B9E\u9645API\u8BF7\u6C42\u6570: ${a.apiRequests}`),I.info(`[BITIFUL] - \u7F13\u5B58\u547D\u4E2D\u6570: ${a.cacheHits}`),I.info(`[BITIFUL] - \u7F13\u5B58\u547D\u4E2D\u7387: ${a.cacheHitRate}%`),I.info(`[BITIFUL] - \u7F13\u5B58\u603B\u6761\u76EE\u6570: ${a.totalItems}`),a.isDirty?(I.info("[BITIFUL] Saving updated cache to local file..."),await t.saveCacheToFile()):I.info("[BITIFUL] No cache updates, skipping save")}})),hexo.config.bitiful_toolkit.inject_css&&(hexo.extend.generator.register("bitiful_assets",async()=>{let a=await Re(Ae(__dirname,"style/progressive_image.css"),"utf-8");return[{path:"css/progressive_image.css",data:()=>a}]}),hexo.extend.injector.register("head_end",()=>`<link rel="stylesheet" href="${hexo.config.root}css/progressive_image.css">`)),hexo.config.bitiful_toolkit.all?(I.info("[BITIFUL] process all image"),hexo.extend.filter.register("after_render:html",async a=>(I.info("html: ",a),a=await de(a,hexo.config.bitiful_toolkit),a),15)):(I.info("[BITIFUL] process post images"),hexo.extend.filter.register("before_post_render",async a=>(a.content=await de(a.content,hexo.config.bitiful_toolkit),a),15))}De();
|
package/package.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "hexo-bitiful-toolkit",
|
|
3
|
+
"main": "dist/index.js",
|
|
4
|
+
"version": "0.1.3",
|
|
5
|
+
"files": [
|
|
6
|
+
"dist/index.js",
|
|
7
|
+
"README.md"
|
|
8
|
+
],
|
|
9
|
+
"scripts": {
|
|
10
|
+
"build": "node build.js",
|
|
11
|
+
"test": "node test/test_replace.js",
|
|
12
|
+
"test-cache": "node test/test_local_cache.js"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [ "hexo" ],
|
|
15
|
+
"devDependencies": {
|
|
16
|
+
"esbuild": "^0.27.2"
|
|
17
|
+
}
|
|
18
|
+
}
|