File size: 1,168 Bytes
3d4392e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
export function addBase64Header(
  image?: string,
  format?:
  | "jpeg" | "jpg" | "png" | "webp" | "heic"
  | "mp3" | "wav"
  | "mp4" | "webm"
  | string
) {

  if (!image || typeof image !== "string" || image.length < 60) {
    return ""
  }

  const ext = (`${format || ""}`.split(".").pop() || "").toLowerCase().trim()

  let mime = ""
  if (
    ext === "jpeg" ||
    ext === "jpg") {
    mime = "image/jpeg"
  } else if (
    ext === "webp"
  ) {
    mime = "image/webp"
  } else if (
    ext === "png") {
    mime = "image/png"
  } else if (ext === "heic") {
    mime = "image/heic"
  } else if (ext === "mp3") {
    mime = "audio/mp3"
  } else if (ext === "mp4") {
    mime = "video/mp4"
  } else if (ext === "webm") {
    mime = "video/webm"
  } else if (ext === "wav") {
    mime = "audio/wav"
  } else {
    throw new Error(`addBase64Header failed (unsupported format: ${format})`)
  }


  if (image.startsWith('data:')) {
    if (image.startsWith(`data:${mime};base64,`)) {
      return image
    } else {
      throw new Error(`addBase64Header failed (input string is NOT a ${mime} image)`)
    }
  } else {
    return `data:${mime};base64,${image}`
  }
}