0

Create Image

by
Published Apr 8, 2025
Script buttondown Verified

The script

Submitted by hugo697 Bun
Verified 428 days ago
1
//native
2
type Buttondown = {
3
  token: string;
4
};
5
type Base64 = string;
6
/**
7
 * Create Image
8
 *
9
 */
10
export async function main(
11
  auth: Buttondown,
12
  body: {
13
    image: {
14
      base64: Base64;
15
      type:
16
        | "image/png"
17
        | "image/jpeg"
18
        | "image/gif"
19
        | "application/pdf"
20
        | "appication/json"
21
        | "text/csv"
22
        | "text/plain"
23
        | "audio/mpeg"
24
        | "audio/wav"
25
        | "video/mp4";
26
      name: string;
27
    };
28
  },
29
) {
30
  const url = new URL(`https://api.buttondown.com/v1/images`);
31

32
  const formData = new FormData();
33
  for (const [k, v] of Object.entries(body)) {
34
    if (v !== undefined) {
35
      if (["image"].includes(k)) {
36
        const { base64, type, name } = v as {
37
          base64: Base64;
38
          type: string;
39
          name: string;
40
        };
41
        formData.append(
42
          k,
43
          new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
44
            type,
45
          }),
46
          name,
47
        );
48
      } else {
49
        formData.append(k, String(v));
50
      }
51
    }
52
  }
53
  const response = await fetch(url, {
54
    method: "POST",
55
    headers: {
56
      Authorization: "Token " + auth.token,
57
    },
58
    body: formData,
59
  });
60
  if (!response.ok) {
61
    const text = await response.text();
62
    throw new Error(`${response.status} ${text}`);
63
  }
64
  return await response.json();
65
}
66