1
1
import fetch from "node-fetch" ;
2
- import { encode , decode } from "blurhash" ;
2
+ import fs from "fs" ;
3
+ import { encode } from "blurhash" ;
3
4
import sharp from 'sharp' ;
4
5
import sizeOf from "image-size" ;
5
6
6
7
export interface IOptions {
7
8
size ?: number ;
9
+ offline ?: boolean ;
8
10
}
9
11
10
- export interface IInput {
11
- url : string ;
12
- options ?: IOptions ;
13
- }
14
12
export interface IOutput {
15
13
encoded : string ;
16
14
width : number ;
17
15
height : number ;
18
16
}
19
17
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 ;
22
43
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 ) ;
26
53
27
- const { width, height, } = sizeOf ( returnedBuffer ) ;
54
+ const { width : remoteWidth , height : remoteHeight } = sizeOf ( returnedBuffer ) ;
55
+ width = remoteWidth ;
56
+ height = remoteHeight ;
57
+ }
28
58
29
59
const { info, data } = await sharp ( returnedBuffer )
30
60
. resize ( size , size , {
@@ -36,7 +66,6 @@ export const blurhashFromURL = async (url: string, options: IOptions = {}) => {
36
66
resolveWithObject : true ,
37
67
} ) ;
38
68
39
-
40
69
const encoded = encode (
41
70
new Uint8ClampedArray ( data ) ,
42
71
info . width ,
0 commit comments