This repository has been archived by the owner on Dec 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fresh.config.ts
101 lines (89 loc) · 2.69 KB
/
fresh.config.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
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { defineConfig } from "$fresh/server.ts";
import { ensureDir } from "$std/fs/ensure_dir.ts";
import ImagesPlugin, {
extendKeyMap,
getParam,
transform,
} from "fresh_images/mod.ts";
import { crop, resize, rotate } from "fresh_images/transformer.ts";
import { decode, GIF, Image } from "imagescript/mod.ts";
import caption from "./transformers/canvasExample.ts";
/**
* Custom transformer example.
* Rotate an image hue by a random number of degrees.\
* Optionally accept a query parameter to invert the hue. (Requires extending the key map.)
*/
const myTransformer = (img: Image | GIF, req: Request) => {
const randomDegrees = Math.floor(Math.random() * 360);
const invert = getParam(req, "invert", extendKeyMap({ invert: "i" }));
if (invert) {
return transform(img, (img) => Promise.resolve((img as Image).invertHue()));
}
return transform(
img,
(img) => Promise.resolve((img as Image).hueShift(randomDegrees)),
);
};
/**
* Pre-optimize images before serving them.
*/
const myBuildFunction = async () => {
const files = Deno.readDir("./static/image");
await ensureDir("./static/placeholders");
for await (const file of files) {
if (!file.isFile) {
continue;
}
const input = await Deno.readFile(`./static/image/${file.name}`);
const output = await transform(
await decode(input),
(img) => Promise.resolve((img as Image).resize(Image.RESIZE_AUTO, 100)),
);
if (output instanceof GIF) {
await Deno.writeFile(
`./static/placeholders/${file.name}`,
await output.encode(30),
);
continue;
}
await Deno.writeFile(
`./static/placeholders/${file.name}`,
await output.encodeJPEG(1),
);
}
};
export default defineConfig({
plugins: [
ImagesPlugin({
// This creates a route, "/img", that will serve images from the "./static/image" directory.
route: "/img",
// Pass the transformers to "install"
transformers: {
resize,
rotate,
crop,
// Custom transformers
caption,
cool: myTransformer,
withRoute: {
path: "/desaturated",
handler: (img: Image | GIF) =>
transform(
img,
(img) => Promise.resolve((img as Image).saturation(0.25, true)),
),
},
},
build: myBuildFunction,
}),
ImagesPlugin({
// Create a different route for the placeholder images. (Nested directory routes are currently not supported.)
route: "/img/placeholder",
realPath: "./static/placeholders",
// Only specified transformers will be available on this route.
transformers: {
cool: myTransformer,
},
}),
],
});