Skip to content

Commit

Permalink
Add image library to optimize performance
Browse files Browse the repository at this point in the history
  • Loading branch information
jordisala1991 committed Jun 3, 2024
1 parent a411338 commit ae51d38
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 11 deletions.
23 changes: 23 additions & 0 deletions plugin-src/ImageLibrary.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { ImageColor } from '@ui/lib/types/utils/imageColor';

class ImageLibrary {
private images: Record<string, ImageColor> = {};

public register(hash: string, image: ImageColor) {
this.images[hash] = image;
}

public get(hash: string): ImageColor | undefined {
return this.images[hash];
}

public all(): Record<string, ImageColor> {
return this.images;
}

public init(images: Record<string, ImageColor>): void {
this.images = images;
}
}

export const imagesLibrary = new ImageLibrary();
31 changes: 20 additions & 11 deletions plugin-src/translators/fills/translateImageFill.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { imagesLibrary } from '@plugin/ImageLibrary';
import { detectMimeType } from '@plugin/utils';

import { Fill } from '@ui/lib/types/utils/fill';
Expand All @@ -9,28 +10,36 @@ export const translateImageFill = async (fill: ImagePaint): Promise<Fill | undef

return {
fillOpacity: !fill.visible ? 0 : fill.opacity,
fillImage: fillImage
fillImage
};
};

const translateImage = async (imageHash: string | null): Promise<ImageColor | undefined> => {
if (!imageHash) return;

const libraryImage = imagesLibrary.get(imageHash);

if (libraryImage) return libraryImage;

const image = figma.getImageByHash(imageHash);

if (!image) return;

const bytes = await image.getBytesAsync();
const size = await image.getSizeAsync();
const b64 = figma.base64Encode(bytes);
const mimeType = detectMimeType(b64);
const dataUri = `data:${mimeType};base64,${b64}`;
const { width, height } = await image.getSizeAsync();
const b64 = figma.base64Encode(await image.getBytesAsync());
const mtype = detectMimeType(b64);
const dataUri = `data:${mtype};base64,${b64}`;

return {
width: size.width,
height: size.height,
mtype: mimeType,
const imageColor = {
width,
height,
mtype,
dataUri,
keepAspectRatio: true,
dataUri: dataUri,
id: '00000000-0000-0000-0000-000000000000'
};

imagesLibrary.register(imageHash, imageColor);

return imageColor;
};

0 comments on commit ae51d38

Please sign in to comment.