Skip to content

Build your personal knowledge base with Trilium Notes

feat(canvas): store inserted images as attachments

Elian Doranc9462ac972f2
diff --git a/apps/client/src/services/image_upload.spec.ts b/apps/client/src/services/image_upload.spec.ts
new file mode 100644
index 0000000000..29050d4b55
--- /dev/null
+++ b/apps/client/src/services/image_upload.spec.ts
@@ -0,0 +1,66 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { dataUrlToImageFile, parseImageDataUrl, uploadImageAttachment } from "./image_upload";
+import server from "./server";
+
+vi.mock("./server", () => ({ default: { upload: vi.fn() } }));
+
+const serverUpload = vi.mocked(server.upload);
+
+describe("parseImageDataUrl", () => {
+ it("splits a base64 data URL into its mime, raw base64 and extension", () => {
+ expect(parseImageDataUrl("data:image/png;base64,AAAA")).toEqual({ mime: "image/png", base64: "AAAA", ext: "png" });
+ expect(parseImageDataUrl("data:image/jpeg;base64,BBBB")?.ext).toBe("jpeg");
+ });
+
+ it("maps svg+xml to a clean 'svg' extension", () => {
+ expect(parseImageDataUrl("data:image/svg+xml;base64,Q0M=")?.ext).toBe("svg");
+ });
+
+ it("returns null for non-base64 data URLs and plain URLs", () => {
+ expect(parseImageDataUrl("api/attachments/x/image/x.png")).toBeNull();
+ expect(parseImageDataUrl("data:image/png,notbase64")).toBeNull();
+ });
+});
+
+describe("dataUrlToImageFile", () => {
+ it("decodes the base64 payload into a File with the parsed mime and extension", async () => {
+ const file = dataUrlToImageFile("data:image/png;base64,QUJD"); // "ABC"
+ expect(file).not.toBeNull();
+ expect(file?.type).toBe("image/png");
+ expect(file?.name).toBe("image.png");
+ expect(await file?.text()).toBe("ABC");
+ });
+
+ it("returns null when the input is not a base64 data URL", () => {
+ expect(dataUrlToImageFile("https://example.com/a.png")).toBeNull();
+ });
+});
+
+describe("uploadImageAttachment", () => {
+ afterEach(() => vi.clearAllMocks());
+
+ it("uploads the decoded image and returns the attachment URL on success", async () => {
+ serverUpload.mockResolvedValue({ uploaded: true, url: "api/attachments/new1/image/image.png" });
+
+ const url = await uploadImageAttachment("note1", "data:image/png;base64,QUJD");
+
+ expect(url).toBe("api/attachments/new1/image/image.png");
+ expect(serverUpload).toHaveBeenCalledWith("notes/note1/attachments/upload", expect.any(File), undefined, "POST");
+ });
+
+ it("returns null when the server reports the upload did not succeed", async () => {
+ serverUpload.mockResolvedValue({ uploaded: false });
+ expect(await uploadImageAttachment("note1", "data:image/png;base64,QUJD")).toBeNull();
+ });
+
+ it("returns null without uploading when the data URL cannot be parsed", async () => {
+ expect(await uploadImageAttachment("note1", "not-a-data-url")).toBeNull();
+ expect(serverUpload).not.toHaveBeenCalled();
+ });
+
+ it("returns null when the upload throws", async () => {
+ serverUpload.mockRejectedValue(new Error("network"));
+ expect(await uploadImageAttachment("note1", "data:image/png;base64,QUJD")).toBeNull();
+ });
+});
diff --git a/apps/client/src/services/image_upload.ts b/apps/client/src/services/image_upload.ts
new file mode 100644
index 0000000000..8bf20b332a
--- /dev/null
+++ b/apps/client/src/services/image_upload.ts
@@ -0,0 +1,54 @@
+import server from "./server.js";
+
+/**
+ * Uploads a base64 `data:` image to a note as an attachment via the standard attachment-upload
+ * endpoint (the server assigns the id, compresses the image, and returns the reference URL).
+ * Resolves to the `api/attachments/...` URL, or `null` on failure (caller decides how to fall back,
+ * e.g. keep the image inline as base64 so it still persists/renders).
+ *
+ * Format-agnostic: used by any rich note type that needs to offload inline base64 images to
+ * attachments (e.g. the spreadsheet drawing layer).
+ */
+export async function uploadImageAttachment(noteId: string, dataUrl: string): Promise<string | null> {
+ const file = dataUrlToImageFile(dataUrl);
+ if (!file) return null;
+
+ try {
+ const response = await server.upload(`notes/${noteId}/attachments/upload`, file, undefined, "POST") as { uploaded?: boolean; url?: string };
+ return response?.uploaded && response.url ? response.url : null;
+ } catch (e) {
+ console.error("Failed to upload image attachment", e);
+ return null;
+ }
+}
+
+/** Decodes a `data:<mime>;base64,<data>` URL into a {@link File} suitable for upload. */
+export function dataUrlToImageFile(dataUrl: string): File | null {
+ const parsed = parseImageDataUrl(dataUrl);
+ if (!parsed) return null;
+
+ const binary = atob(parsed.base64);
+ const bytes = new Uint8Array(binary.length);
+ for (let i = 0; i < binary.length; i++) {
+ bytes[i] = binary.charCodeAt(i);
+ }
+ return new File([ bytes ], `image.${parsed.ext}`, { type: parsed.mime });
+}
+
+export interface ParsedImageDataUrl {
+ mime: string;
+ base64: string;
+ ext: string;
+}
+
+/** Splits a `data:<mime>;base64,<data>` URL into its mime, raw base64 and a file extension. */
+export function parseImageDataUrl(dataUrl: string): ParsedImageDataUrl | null {
+ const match = /^data:([^;,]+);base64,(.*)$/.exec(dataUrl);
+ if (!match) return null;
+
+ const mime = match[1];
+ const base64 = match[2];
+ const subtype = mime.split("/")[1] ?? "png";
+ const ext = subtype === "svg+xml" ? "svg" : (subtype.replace(/[^a-z0-9]/gi, "") || "png");
+ return { mime, base64, ext };
+}
diff --git a/apps/client/src/widgets/type_widgets/canvas/image_attachments.spec.ts b/apps/client/src/widgets/type_widgets/canvas/image_attachments.spec.ts
new file mode 100644
index 0000000000..912a86ed04
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/canvas/image_attachments.spec.ts
@@ -0,0 +1,118 @@
+import { BinaryFileData } from "@excalidraw/excalidraw/types";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type FNote from "../../../entities/fnote";
+import { buildNewImageAttachments, findOrphanImageAttachments, loadImageAttachments } from "./image_attachments";
+
+function file(dataURL: string, mimeType = "image/png"): BinaryFileData {
+ return { id: "x", dataURL, mimeType, created: 0 } as BinaryFileData;
+}
+
+describe("buildNewImageAttachments", () => {
+ it("emits a base64 image attachment titled with the fileId for each new image", () => {
+ const activeFiles = {
+ a: file("data:image/png;base64,AAAA"),
+ b: file("data:image/jpeg;base64,BBBB", "image/jpeg")
+ };
+
+ const attachments = buildNewImageAttachments(activeFiles, new Set());
+
+ expect(attachments).toEqual([
+ { role: "image", title: "a", mime: "image/png", content: "AAAA", position: 10, encoding: "base64" },
+ { role: "image", title: "b", mime: "image/jpeg", content: "BBBB", position: 20, encoding: "base64" }
+ ]);
+ });
+
+ it("skips files already persisted (loaded at start or uploaded earlier this session)", () => {
+ const activeFiles = {
+ old: file("data:image/png;base64,AAAA"),
+ new: file("data:image/png;base64,CCCC")
+ };
+
+ const attachments = buildNewImageAttachments(activeFiles, new Set([ "old" ]));
+
+ expect(attachments).toEqual([
+ { role: "image", title: "new", mime: "image/png", content: "CCCC", position: 10, encoding: "base64" }
+ ]);
+ });
+
+ it("skips files whose source is not an inline data URL (nothing to upload)", () => {
+ const activeFiles = { a: file("api/attachments/x/image/x.png") };
+ expect(buildNewImageAttachments(activeFiles, new Set())).toEqual([]);
+ });
+
+ it("migrates a legacy note's inline base64 images to attachments, preserving the exact bytes", () => {
+ // A legacy note loads its images inline (content.files) into memory, so on the first save
+ // every active file is unseen (empty persisted set) and must be written out verbatim — the
+ // stored content is the original base64, not a recompressed copy.
+ const activeFiles = { legacy: file("data:image/png;base64,iVBORw0KGgoAAAA=") };
+
+ const attachments = buildNewImageAttachments(activeFiles, new Set());
+
+ expect(attachments).toEqual([
+ { role: "image", title: "legacy", mime: "image/png", content: "iVBORw0KGgoAAAA=", position: 10, encoding: "base64" }
+ ]);
+ });
+});
+
+describe("findOrphanImageAttachments", () => {
+ it("splits loaded attachments into removed (orphan) and still-referenced (remaining)", () => {
+ const loaded = [
+ { fileId: "a", attachmentId: "att-a" },
+ { fileId: "b", attachmentId: "att-b" },
+ { fileId: "c", attachmentId: "att-c" }
+ ];
+
+ const { orphans, remaining } = findOrphanImageAttachments(loaded, new Set([ "a", "c" ]));
+
+ expect(orphans).toEqual([ { fileId: "b", attachmentId: "att-b" } ]);
+ expect(remaining).toEqual([
+ { fileId: "a", attachmentId: "att-a" },
+ { fileId: "c", attachmentId: "att-c" }
+ ]);
+ });
+
+ it("returns no orphans when every loaded image is still on the canvas", () => {
+ const loaded = [ { fileId: "a", attachmentId: "att-a" } ];
+ const { orphans, remaining } = findOrphanImageAttachments(loaded, new Set([ "a" ]));
+
+ expect(orphans).toEqual([]);
+ expect(remaining).toEqual(loaded);
+ });
+});
+
+describe("loadImageAttachments", () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ function noteWithAttachments(attachments: { attachmentId: string; title: string }[]) {
+ return { getAttachmentsByRole: vi.fn(async () => attachments) } as unknown as FNote;
+ }
+
+ it("fetches each image attachment, rebuilds its data URL and maps it to its fileId, ignoring the SVG export", async () => {
+ const note = noteWithAttachments([
+ { attachmentId: "att-export", title: "canvas-export.svg" },
+ { attachmentId: "att-1", title: "fileId-1" }
+ ]);
+ const fetchMock = vi.fn(async () => ({ ok: true, blob: async () => new Blob([ "ABC" ], { type: "image/png" }) }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const { files, metadata } = await loadImageAttachments(note);
+
+ // Only the image is fetched (the export is filtered out by title), via the attachment image endpoint.
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(fetchMock).toHaveBeenCalledWith("api/attachments/att-1/image/fileId-1");
+ // "ABC" base64-encodes to "QUJD" — the bytes survive the round-trip unchanged.
+ expect(files).toEqual([ { id: "fileId-1", dataURL: "data:image/png;base64,QUJD", mimeType: "image/png", created: expect.any(Number) } ]);
+ expect(metadata).toEqual([ { fileId: "fileId-1", attachmentId: "att-1" } ]);
+ });
+
+ it("skips attachments whose fetch fails without rejecting", async () => {
+ const note = noteWithAttachments([ { attachmentId: "att-1", title: "fileId-1" } ]);
+ vi.stubGlobal("fetch", vi.fn(async () => ({ ok: false, blob: async () => new Blob() })));
+
+ const { files, metadata } = await loadImageAttachments(note);
+
+ expect(files).toEqual([]);
+ expect(metadata).toEqual([]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/canvas/image_attachments.ts b/apps/client/src/widgets/type_widgets/canvas/image_attachments.ts
new file mode 100644
index 0000000000..dd56c298f6
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/canvas/image_attachments.ts
@@ -0,0 +1,108 @@
+import type { BinaryFileData } from "@excalidraw/excalidraw/types";
+
+import type FNote from "../../../entities/fnote";
+import { parseImageDataUrl } from "../../../services/image_upload";
+import type { SavedData } from "../../react/hooks";
+
+/** Maps a canvas image's Excalidraw `fileId` to the attachment it is stored in. */
+export interface ImageAttachmentMetadata {
+ fileId: string;
+ attachmentId: string;
+}
+
+/**
+ * Attachment role under which both the SVG export and the canvas images are stored. Images are
+ * served back via the `api/attachments/:id/image/...` endpoint, which only accepts the `image`
+ * role — so they must share it with the export and are told apart by title (see below).
+ */
+export const IMAGE_ROLE = "image";
+/** Fixed title of the SVG export attachment; canvas images are titled with their `fileId` instead. */
+export const CANVAS_EXPORT_TITLE = "canvas-export.svg";
+
+/**
+ * Loads the note's image attachments (every `image`-role attachment except the SVG export) and
+ * rebuilds them into Excalidraw {@link BinaryFileData}, keyed by the `fileId` stored as the
+ * attachment title. The bytes are fetched from the attachment image endpoint and re-encoded as a
+ * data URL, since Excalidraw renders only from inline data URLs (it has no external-URL provider).
+ */
+export async function loadImageAttachments(note: FNote): Promise<{ files: BinaryFileData[]; metadata: ImageAttachmentMetadata[] }> {
+ const attachments = (await note.getAttachmentsByRole(IMAGE_ROLE)).filter((attachment) => attachment.title !== CANVAS_EXPORT_TITLE);
+
+ const files: BinaryFileData[] = [];
+ const metadata: ImageAttachmentMetadata[] = [];
+
+ await Promise.all(attachments.map(async (attachment) => {
+ try {
+ const response = await fetch(`api/attachments/${attachment.attachmentId}/image/${encodeURIComponent(attachment.title)}`);
+ if (!response.ok) return;
+
+ const blob = await response.blob();
+ const dataURL = await blobToDataURL(blob);
+ files.push({
+ id: attachment.title,
+ dataURL,
+ mimeType: blob.type || "image/png",
+ created: Date.now()
+ } as BinaryFileData);
+ metadata.push({ fileId: attachment.title, attachmentId: attachment.attachmentId });
+ } catch (e) {
+ console.error(`Failed to load canvas image attachment '${attachment.attachmentId}'`, e);
+ }
+ }));
+
+ return { files, metadata };
+}
+
+/**
+ * Builds attachment payloads for canvas images not yet persisted. Each is titled with its `fileId`
+ * so the server matches and updates it in place across saves (rather than duplicating). The bytes
+ * are stored as exact base64 (no compression), preserving PNG transparency.
+ */
+export function buildNewImageAttachments(activeFiles: Record<string, BinaryFileData>, persistedFileIds: ReadonlySet<string>): NonNullable<SavedData["attachments"]> {
+ const attachments: NonNullable<SavedData["attachments"]> = [];
+ let position = 10;
+
+ for (const [ fileId, file ] of Object.entries(activeFiles)) {
+ if (!file || persistedFileIds.has(fileId)) continue;
+
+ const parsed = parseImageDataUrl(file.dataURL);
+ if (!parsed) continue; // not an inline data URL — nothing to upload
+
+ attachments.push({
+ role: IMAGE_ROLE,
+ title: fileId,
+ mime: file.mimeType,
+ content: parsed.base64,
+ position,
+ encoding: "base64"
+ });
+ position += 10;
+ }
+
+ return attachments;
+}
+
+/**
+ * Partitions previously-loaded image attachments into those whose image is gone from the canvas
+ * (`orphans`, to be deleted) and those still referenced (`remaining`).
+ */
+export function findOrphanImageAttachments(loaded: readonly ImageAttachmentMetadata[], activeFileIds: ReadonlySet<string>) {
+ const orphans: ImageAttachmentMetadata[] = [];
+ const remaining: ImageAttachmentMetadata[] = [];
+
+ for (const entry of loaded) {
+ (activeFileIds.has(entry.fileId) ? remaining : orphans).push(entry);
+ }
+
+ return { orphans, remaining };
+}
+
+/** Reads a blob as a base64 `data:` URL. */
+function blobToDataURL(blob: Blob): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(reader.result as string);
+ reader.onerror = () => reject(reader.error);
+ reader.readAsDataURL(blob);
+ });
+}
diff --git a/apps/client/src/widgets/type_widgets/canvas/persistence.ts b/apps/client/src/widgets/type_widgets/canvas/persistence.ts
index 4b31d826b6..22b21c6064 100644
--- a/apps/client/src/widgets/type_widgets/canvas/persistence.ts
+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.ts
@@ -8,6 +8,7 @@ import NoteContext from "../../../components/note_context";
import FNote from "../../../entities/fnote";
import server from "../../../services/server";
import { SavedData, useEditorSpacedUpdate } from "../../react/hooks";
+import { buildNewImageAttachments, CANVAS_EXPORT_TITLE, findOrphanImageAttachments, IMAGE_ROLE, ImageAttachmentMetadata, loadImageAttachments } from "./image_attachments";
interface AttachmentMetadata {
title: string;
@@ -40,6 +41,13 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConte
const libraryCache = useRef<LibraryItem[]>([]);
const attachmentMetadata = useRef<AttachmentMetadata[]>([]);
+ // Image attachments present at load (fileId -> attachmentId), used to delete attachments whose
+ // image was removed from the canvas this session (mirrors the library-item cleanup above).
+ const loadedImageAttachments = useRef<ImageAttachmentMetadata[]>([]);
+ // fileIds already persisted as attachments (loaded at start + uploaded this session), so each
+ // image is written once rather than re-encoded into every save.
+ const persistedImageFileIds = useRef<Set<string>>(new Set());
+
const appStateToCompare = useRef<Partial<ImportantAppState>>({});
const spacedUpdate = useEditorSpacedUpdate({
@@ -52,6 +60,8 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConte
libraryCache.current = [];
attachmentMetadata.current = [];
+ loadedImageAttachments.current = [];
+ persistedImageFileIds.current = new Set();
// load saved content into excalidraw canvas
let content: CanvasContent = {
@@ -69,6 +79,17 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConte
loadData(api, content, theme);
+ // Images live as attachments (titled with their fileId); fetch them, rebuild their
+ // data URLs and inject them so elements referencing those fileIds render. Legacy notes
+ // that still carry inline images in `content.files` were already loaded by loadData().
+ loadImageAttachments(note).then(({ files, metadata }) => {
+ if (files.length > 0) {
+ api.addFiles(files);
+ }
+ loadedImageAttachments.current = metadata;
+ persistedImageFileIds.current = new Set(metadata.map((m) => m.fileId));
+ });
+
// Initialize tracking state after loading to prevent redundant updates from initial onChange events
currentSceneVersion.current = getSceneVersion(api.getSceneElements());
@@ -85,8 +106,23 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConte
async getData() {
const api = apiRef.current;
if (!api) return;
- const { content, svg } = await getData(api, appStateToCompare);
- const attachments: SavedData["attachments"] = [{ role: "image", title: "canvas-export.svg", mime: "image/svg+xml", content: svg, position: 0 }];
+ const { content, svg, activeFiles } = await getData(api, appStateToCompare);
+ const attachments: SavedData["attachments"] = [{ role: IMAGE_ROLE, title: CANVAS_EXPORT_TITLE, mime: "image/svg+xml", content: svg, position: 0 }];
+
+ // Persist newly inserted images as attachments and drop the ones whose image was removed.
+ // `content` carries only the fileId references (see getData), so the bytes live here.
+ const activeFileIds = new Set(Object.keys(activeFiles));
+ for (const attachment of buildNewImageAttachments(activeFiles, persistedImageFileIds.current)) {
+ attachments.push(attachment);
+ persistedImageFileIds.current.add(attachment.title);
+ }
+
+ const { orphans, remaining } = findOrphanImageAttachments(loadedImageAttachments.current, activeFileIds);
+ for (const { attachmentId, fileId } of orphans) {
+ await server.remove(`attachments/${attachmentId}`);
+ persistedImageFileIds.current.delete(fileId);
+ }
+ loadedImageAttachments.current = remaining;
// libraryChanged is unset in dataSaved()
if (libraryChanged.current) {
@@ -231,7 +267,10 @@ async function getData(api: ExcalidrawImperativeAPI, appStateToCompare: RefObjec
type: "excalidraw",
version: 2,
elements,
- files: activeFiles,
+ // Images are persisted as attachments (keyed by fileId), not inline, so the content stays
+ // small. Elements keep their `fileId`; the bytes are reattached on load. Kept as an empty
+ // object for shape compatibility with loadData() and legacy content.
+ files: {} as Record<string, BinaryFileData>,
appState: {
scrollX: appState.scrollX,
scrollY: appState.scrollY,
@@ -242,7 +281,8 @@ async function getData(api: ExcalidrawImperativeAPI, appStateToCompare: RefObjec
return {
content,
- svg: svgString
+ svg: svgString,
+ activeFiles
};
}
@@ -254,14 +294,11 @@ function loadData(api: ExcalidrawImperativeAPI, content: CanvasContent, theme: A
// files are expected in an array when loading. they are stored as a key-index object
// see example for loading here:
// https://github.com/excalidraw/excalidraw/blob/c5a7723185f6ca05e0ceb0b0d45c4e3fbcb81b2a/src/packages/excalidraw/example/App.js#L68
+ // Only legacy notes still carry inline images here; new saves persist images as attachments
+ // (loaded separately via loadImageAttachments) and leave `content.files` empty.
const fileArray: BinaryFileData[] = [];
for (const fileId in files) {
- const file = files[fileId];
- // TODO: dataURL is replaceable with a trilium image url
- // maybe we can save normal images (pasted) with base64 data url, and trilium images
- // with their respective url! nice
- // file.dataURL = "http://localhost:8080/api/images/ltjOiU8nwoZx/start.png";
- fileArray.push(file);
+ fileArray.push(files[fileId]);
}
// Update the scene
diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/persistence.tsx b/apps/client/src/widgets/type_widgets/spreadsheet/persistence.tsx
index 8f39efabc4..a4940724f1 100644
--- a/apps/client/src/widgets/type_widgets/spreadsheet/persistence.tsx
+++ b/apps/client/src/widgets/type_widgets/spreadsheet/persistence.tsx
@@ -3,7 +3,7 @@ import { MutableRef, useEffect, useRef } from "preact/hooks";
import NoteContext from "../../../components/note_context";
import FNote from "../../../entities/fnote";
-import server from "../../../services/server";
+import { uploadImageAttachment } from "../../../services/image_upload";
import { randomString } from "../../../services/utils";
import { SavedData, useEditorSpacedUpdate } from "../../react/hooks";
@@ -202,7 +202,7 @@ export default function usePersistence(note: FNote, noteContext: NoteContext | n
slimmed,
preexistingImageSources.current,
uploadedImageUrls.current,
- (source) => uploadDrawingImage(note.noteId, source)
+ (source) => uploadImageAttachment(note.noteId, source)
);
const content = {
@@ -353,37 +353,6 @@ export async function uploadNewDrawingImages(
}
}
-/**
- * Uploads a base64 image to the note as an attachment via the standard attachment-upload endpoint
- * (the server assigns the id and returns the reference URL). Resolves to the URL, or `null` on
- * failure.
- */
-async function uploadDrawingImage(noteId: string, source: string): Promise<string | null> {
- const file = dataUrlToImageFile(source);
- if (!file) return null;
-
- try {
- const response = await server.upload(`notes/${noteId}/attachments/upload`, file, undefined, "POST") as { uploaded?: boolean; url?: string };
- return response?.uploaded && response.url ? response.url : null;
- } catch (e) {
- console.error("Failed to upload spreadsheet image", e);
- return null;
- }
-}
-
-/** Decodes a `data:<mime>;base64,<data>` URL into a {@link File} for upload. */
-function dataUrlToImageFile(dataUrl: string): File | null {
- const parsed = parseImageDataUrl(dataUrl);
- if (!parsed) return null;
-
- const binary = atob(parsed.base64);
- const bytes = new Uint8Array(binary.length);
- for (let i = 0; i < binary.length; i++) {
- bytes[i] = binary.charCodeAt(i);
- }
- return new File([ bytes ], `image.${parsed.ext}`, { type: parsed.mime });
-}
-
/** Collects the base64 image sources currently present in a workbook's drawing resource. */
export function collectBase64DrawingSources(workbookData: Partial<IWorkbookData>): Set<string> {
const sources = new Set<string>();
@@ -436,21 +405,3 @@ function forEachBase64DrawingImage(
return { resource, drawingData };
}
-
-interface ParsedImageDataUrl {
- mime: string;
- base64: string;
- ext: string;
-}
-
-/** Splits a `data:<mime>;base64,<data>` URL into its mime, raw base64 and a file extension. */
-function parseImageDataUrl(dataUrl: string): ParsedImageDataUrl | null {
- const match = /^data:([^;,]+);base64,(.*)$/.exec(dataUrl);
- if (!match) return null;
-
- const mime = match[1];
- const base64 = match[2];
- const subtype = mime.split("/")[1] ?? "png";
- const ext = subtype === "svg+xml" ? "svg" : (subtype.replace(/[^a-z0-9]/gi, "") || "png");
- return { mime, base64, ext };
-}