Browse Source

save blob to indexeddb instead of base64 image string

lloydzhou 1 year ago
parent
commit
a1117cd4ee
2 changed files with 20 additions and 2 deletions
  1. 7 2
      app/store/sd.ts
  2. 13 0
      app/utils/file.tsx

+ 7 - 2
app/store/sd.ts

@@ -3,7 +3,7 @@ import { showToast } from "@/app/components/ui-lib";
 import { getHeaders } from "@/app/client/api";
 import { createPersistStore } from "@/app/utils/store";
 import { nanoid } from "nanoid";
-import { saveFileData } from "@/app/utils/file";
+import { saveFileData, base64Image2Blob } from "@/app/utils/file";
 
 export const useSdStore = createPersistStore<
   {
@@ -72,7 +72,12 @@ export const useSdStore = createPersistStore<
               this.updateDraw({
                 ...data,
                 status: "success",
-                img_data: saveFileData(db, data.id, resData.image),
+                // save blob to indexeddb instead of base64 image string
+                img_data: saveFileData(
+                  db,
+                  data.id,
+                  base64Image2Blob(resData.image, "image/png"),
+                ),
               });
             } else {
               this.updateDraw({

+ 13 - 0
app/utils/file.tsx

@@ -32,6 +32,16 @@ export function useFileDB() {
   return useIndexedDB(StoreKey.File);
 }
 
+export function base64Image2Blob(base64Data: string, contentType: string) {
+  const byteCharacters = atob(base64Data);
+  const byteNumbers = new Array(byteCharacters.length);
+  for (let i = 0; i < byteCharacters.length; i++) {
+    byteNumbers[i] = byteCharacters.charCodeAt(i);
+  }
+  const byteArray = new Uint8Array(byteNumbers);
+  return new Blob([byteArray], { type: contentType });
+}
+
 export function saveFileData(db, fileId, data) {
   // save file content and return url start with `indexeddb://`
   db.add({ id: fileId, data });
@@ -40,6 +50,9 @@ export function saveFileData(db, fileId, data) {
 
 export async function getFileData(db, fileId, contentType = "image/png") {
   const { data } = await db.getByID(fileId);
+  if (typeof data == "object") {
+    return URL.createObjectURL(data);
+  }
   return `data:${contentType};base64,${data}`;
 }