Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to load images from base64-encoded strings. #29

Merged
merged 3 commits into from
Nov 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion builders/gen_entry.js
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,7 @@ function addTextAction(id, name) {
function addImageAction(id, name, withTx = true) {
let descript = "Dynamic Icons: " +
`Generate or layer an image. ${layerInfoText('image')} ` +
"File paths are relative to this plugin's \"Default Image Files Path\" setting, or use absolute paths.\n";
"File paths are relative to this plugin's \"Default Image Files Path\" setting, or use absolute paths. Base64-encoded images can be loaded by using a \"data:\" prefix before the string data.\n";
let [format, data] = makeIconLayerCommonData(id);
let i = data.length;
format += `Image\nFile {${i++}}Resize\nFit {${i++}}`;
Expand Down
29 changes: 21 additions & 8 deletions src/modules/ImageCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,15 @@ export class ImageCache
return src + ',' + size.width + ',' + size.height + ',' + (resizeOptions.fit || ImageCache.cacheOptions.resizeOptions.fit);
}

private resolveSource(src: string) {
const isData = src.startsWith("data:");
if (isData)
src = src.substring(5);
else if (PluginSettings.imageFilesBasePath && !isAbsPath(src))
src = pjoin(PluginSettings.imageFilesBasePath, src);
return { src: src, isB64Data: isData };
}

private async trimCache()
{
await this.mutex.runExclusive(async() =>
Expand Down Expand Up @@ -103,7 +112,7 @@ export class ImageCache
rec = { image: image, iconNames: [] }
this.cache.set(key, rec);
}
if (meta && meta.iconName && !rec.iconNames.includes(meta.iconName))
if (meta?.iconName && !rec.iconNames.includes(meta.iconName))
rec.iconNames.push(meta.iconName);

// Check for cache overflow; schedule trim if needed.
Expand All @@ -129,20 +138,18 @@ export class ImageCache
*/
public async getOrLoadImage(src: string, size: SizeType, resizeOptions:any = {}, meta?: any): Promise<ImageDataType>
{
if (PluginSettings.imageFilesBasePath && !isAbsPath(src))
src = pjoin(PluginSettings.imageFilesBasePath, src);
if (ImageCache.cacheOptions.maxCachedImages <= 0)
return this.loadImage(src, size, resizeOptions); // short-circuit for disabled cache

let img:ImageDataType = null;
const key:string = this.makeKey(src, size, resizeOptions);
let img: ImageDataType = null;
const key: string = this.makeKey(src, size, resizeOptions);
await this.mutex.runExclusive(async() => {
img = this.getImage_impl(key);
if (!img) {
img = await this.loadImage(src, size, resizeOptions);
if (img)
this.saveImage_impl(key, img, meta);
this.log.debug("Image cache miss for %s; Returned: %O", src, img);
this.log.debug("[%s] Image cache miss for '%s%s'; Returned: %O", meta?.iconName, (src.length > 50 ? "..." : ""), src.slice(-50), img);
}
});
return img;
Expand Down Expand Up @@ -178,7 +185,12 @@ export class ImageCache
*/
public async loadImage(src: string, size: SizeType, resizeOptions:any = {}): Promise<ImageDataType> {
try {
const image = sharp(src, ImageCache.cacheOptions.sourceLoadOptions);
const srcInfo = this.resolveSource(src);
let image: sharp.Sharp;
if (srcInfo.isB64Data)
image = sharp(Buffer.from(srcInfo.src, 'base64'), ImageCache.cacheOptions.sourceLoadOptions);
else
image = sharp(srcInfo.src, ImageCache.cacheOptions.sourceLoadOptions);
if (image) {
resizeOptions = { ...ImageCache.cacheOptions.resizeOptions, ...resizeOptions };
if ((size.width || size.height) && resizeOptions.fit !== "none") {
Expand Down Expand Up @@ -221,7 +233,8 @@ export class ImageCache
for (const [k, v] of this.cache.entries()) {
if (v.iconNames.includes(name)) {
this.cache.delete(k);
this.log.info(`Removed cached image ${k.split(',')[0]} for icon '${name}'.`);
const src = k.split(',')[0];
this.log.info("Removed cached image '%s%s' for icon '%s'.", (src.length > 60 ? "..." : ""), src.slice(-60), name);
}
}
});
Expand Down
2 changes: 1 addition & 1 deletion src/modules/elements/DynamicImage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export default class DynamicImage implements ILayerElement, IRenderable, IValued
setValue(value: string) {
// Fixup \ in Windows paths to \\, otherwise they're treated as escapes in the following eval.
// Ignore any value that contains a / to preserve code (eg. regex), since that's not a legal Windows path character anyway.
if (process.platform == "win32" && value.indexOf('/') < 0)
if (process.platform == "win32" && !value.startsWith("data:") && value.indexOf('/') < 0)
value = value.replace(/\\/g, "\\\\");
this.source = evaluateStringValue(value.trim());
}
Expand Down