File size: 1,565 Bytes
0bf0c48
 
83defd6
 
6215321
 
 
 
 
83defd6
6215321
 
 
 
 
83defd6
 
 
 
 
6215321
0bf0c48
6215321
 
 
 
 
 
 
 
 
3d4392e
83defd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
53
54
55
56
57
import { aitubeApiUrl } from "../../core/config"

// return an image
// note that this function can work either on the server-side or the client-side
export async function generateImage({
  prompt,
  width,
  height,
  token,
  mode = "data-uri"
}: {
  prompt: string
  width: number
  height: number
  token: string

  // data-uri are good for small files as they contain all the data, they can be sent over the network,
  // object-uri are good for large files but can't be sent over the network (they are just a ID)
  // this also means that object-uri cannot be used on the server-side
  mode?: "data-uri" | "object-uri"
}): Promise<string> {
  const requestUri = `${aitubeApiUrl}/api/resolvers/image?t=${
    token
  }&w=${
    width
  }&h=${
    height

  }&p=${
    encodeURIComponent(prompt)
  }`
  const res = await fetch(requestUri)

  // will only work on the server-side
  if (mode === "object-uri") {
    const blob = await res.blob()

    return URL.createObjectURL(blob)
  } else {
    if (typeof window !== "undefined") {
      const blob = await res.blob()

      // on browser-side
      const dataURL = await new Promise<string>((resolve, reject) => {
        var a = new FileReader()
        a.onload = function(e) { resolve(`${e.target?.result || ""}`) }
        a.readAsDataURL(blob)
      })
      return dataURL 
    } else {
      // NodeJS side
      const buffer = await (res as any).buffer()
      const contentType = res.headers.get("Content-Type")
      return "data:" + contentType + ';base64,' + buffer.toString('base64')
    }
  }
}