-
Notifications
You must be signed in to change notification settings - Fork 6
/
image.ts
29 lines (23 loc) · 1.17 KB
/
image.ts
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
import { mime } from "https://cdn.deno.land/mimetypes/versions/v1.0.0/raw/mod.ts"
import { urlParse } from 'https://cdn.deno.land/url_parse/versions/1.0.0/raw/mod.ts';
import { basename } from "https://deno.land/std@0.92.0/path/mod.ts";
export async function readImageFromURL(url: string): Promise<{ bytes: Uint8Array; name: string; }> {
const response = await fetch(url); // fetch an image
const mimeType = response.headers.get('content-type');
const imageBytes = new Uint8Array(await response.arrayBuffer());
const extension = mime.getExtension(mimeType as string);
const defaultName = basename(urlParse(url).pathname)
let defaultImageName = defaultName
// if image name does NOT include an extension
if (mime.getType(defaultName) === undefined) {
defaultImageName = `${defaultName.split('.')[0]}.${extension}`
}
return { bytes: imageBytes, name: defaultImageName }
}
export async function readImageFromFile(path: string): Promise<Uint8Array> {
const bytes = await Deno.readFile(path) // local file
return bytes
}
export async function writeImage(imageBytes: Uint8Array, path: string) {
await Deno.writeFile(path, imageBytes);
}