11import fetch from "node-fetch" ;
2- import { encode , decode } from "blurhash" ;
2+ import fs from "fs" ;
3+ import { encode } from "blurhash" ;
34import sharp from 'sharp' ;
45import sizeOf from "image-size" ;
56
67export interface IOptions {
78 size ?: number ;
9+ offline ?: boolean ;
810}
911
10- export interface IInput {
11- url : string ;
12- options ?: IOptions ;
13- }
1412export interface IOutput {
1513 encoded : string ;
1614 width : number ;
1715 height : number ;
1816}
1917
20- export const blurhashFromURL = async ( url : string , options : IOptions = { } ) => {
21- const { size = 32 } = options ;
18+ /**
19+ * Generate a Blurhash string from a given image URL or local path.
20+ *
21+ * @param {string } source - The image URL or local path to the image file.
22+ * @param {IOptions } [options] - The optional configuration options.
23+ * @param {number } [options.size=32] - The desired size of the image for encoding the Blurhash.
24+ * @param {boolean } [options.offline=false] - Set to `true` if the image source is a local path, `false` if it's a URL.
25+ * @returns {Promise<IOutput> } The Promise that resolves to the encoded Blurhash string, along with the image width and height.
26+ * @default size 32
27+ * @default offline false
28+ * @example
29+ * ```js
30+ * import { blurhashFromURL } from "blurhash-from-url";
31+ *
32+ * const output = await blurhashFromURL("https://i.imgur.com/NhfEdg2.png", {
33+ * size: 32,
34+ * });
35+ *
36+ * console.log(output);
37+ * ```
38+ */
39+ export const blurhashFromURL = async ( source : string , options : IOptions = { } ) : Promise < IOutput > => {
40+ const { size = 32 , offline = false } = options ;
41+
42+ let width , height , returnedBuffer ;
2243
23- const response = await fetch ( url ) ;
24- const arrayBuffer = await response . arrayBuffer ( ) ;
25- const returnedBuffer = Buffer . from ( arrayBuffer ) ;
44+ if ( offline ) {
45+ const { width : localWidth , height : localHeight } = sizeOf ( source ) ;
46+ width = localWidth ;
47+ height = localHeight ;
48+ returnedBuffer = await sharp ( fs . readFileSync ( source ) ) . toBuffer ( ) ;
49+ } else {
50+ const response = await fetch ( source ) ;
51+ const arrayBuffer = await response . arrayBuffer ( ) ;
52+ returnedBuffer = Buffer . from ( arrayBuffer ) ;
2653
27- const { width, height, } = sizeOf ( returnedBuffer ) ;
54+ const { width : remoteWidth , height : remoteHeight } = sizeOf ( returnedBuffer ) ;
55+ width = remoteWidth ;
56+ height = remoteHeight ;
57+ }
2858
2959 const { info, data } = await sharp ( returnedBuffer )
3060 . resize ( size , size , {
@@ -36,7 +66,6 @@ export const blurhashFromURL = async (url: string, options: IOptions = {}) => {
3666 resolveWithObject : true ,
3767 } ) ;
3868
39-
4069 const encoded = encode (
4170 new Uint8ClampedArray ( data ) ,
4271 info . width ,
0 commit comments