Skip to content

Commit

Permalink
refactor(resize): ♻️ add resize and fit in sharp
Browse files Browse the repository at this point in the history
  • Loading branch information
mcnaveen committed Jan 10, 2023
1 parent d13655d commit 9ce4106
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
10 changes: 6 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,36 @@ import sharp from 'sharp';

export interface IOutput {
encoded: string;
decoded: Uint8ClampedArray;
width: number;
height: number;
}

export const blurhashFromURL = async (url: string) => {
export const blurhashFromURL = async (url: string, { size = 32 }: { size?: number } = {}) => {

const response = await fetch(url);
const arrayBuffer = await response.arrayBuffer();
const returnedBuffer = Buffer.from(arrayBuffer);

const { data, info } = await sharp(returnedBuffer)
.resize(size, size, {
fit: "inside",
})
.ensureAlpha()
.raw()
.toBuffer({
resolveWithObject: true,
});

const encoded = encode(
new Uint8ClampedArray(data),
info.width,
info.height,
4,
4
);
const decoded = decode(encoded, info.width, info.height);

const output: IOutput = {
encoded: encoded,
decoded: decoded,
width: info.width,
height: info.height,
};
Expand Down
4 changes: 3 additions & 1 deletion test/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
const { blurhashFromURL } = require("../dist/index.js");

async function getBlurhash() {
const output = await blurhashFromURL("https://i.imgur.com/NhfEdg2.png");
const output = await blurhashFromURL("https://i.imgur.com/NhfEdg2.png", {
size: 32,
});
console.log(output);
}

Expand Down

0 comments on commit 9ce4106

Please sign in to comment.