Skip to content

Commit afe0326

Browse files
committed
v0.0.1
1 parent 9b2b6d2 commit afe0326

File tree

5 files changed

+376
-10
lines changed

5 files changed

+376
-10
lines changed

README.md

Lines changed: 309 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,309 @@
1-
# image-size-api-netlify-edge-functions
1+
# image-api-netlify-edge-functions
2+
3+
[![Star on GitHub](https://img.shields.io/github/stars/samestrin/image-api-netlify-edge-function?style=social)](https://github.com/samestrin/image-api-netlify-edge-function/stargazers)[![Fork on GitHub](https://img.shields.io/github/forks/samestrin/image-api-netlify-edge-function?style=social)](https://github.com/samestrin/image-api-netlify-edge-function/network/members)[![Watch on GitHub](https://img.shields.io/github/watchers/samestrin/image-api-netlify-edge-function?style=social)](https://github.com/samestrin/image-api-netlify-edge-function/watchers)
4+
5+
![Version 0.0.1](https://img.shields.io/badge/Version-0.0.1-blue)[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)[![Built with Node.js](https://img.shields.io/badge/Built%20with-TypeScript-green)](https://www.typescriptlang.org/)
6+
7+
**image-size-api-netlify-edge-functions** is a collection of serverless functions designed to handle various image processing tasks, deployed on the Netlify Edge platform. This project leverages the power of ImageMagick, a robust image manipulation library, to perform operations such as analyzing, converting, cropping, resizing, and generating thumbnails for images. These functions are optimized for edge computing, ensuring low latency and high performance.
8+
9+
### **Netlify Edge Functions**
10+
11+
Edge functions have limits for their size and the amount of memory and execution time they can use:
12+
13+
- **Code size limit**: 20 MB after compression. This is the maximum edge function bundle size supported.
14+
- **Memory per set of deployed edge functions**: 512 MB
15+
- **CPU execution time per request**: _50 ms_. This tracks all time spent running your scripts. Execution time does not include time spent waiting for resources or responses.
16+
- **Response header timeout**: 40 s
17+
18+
While resource-limited, Netlify provides _1M/month requests_ to edge functions per site at the free tier. Pro members have _2M/month requests_.
19+
20+
### **Features**
21+
22+
- **Analyze Image**: Computes the brightness and histogram of an image.
23+
- **Convert Image**: Converts images to different formats.
24+
- **Crop Image**: Crops images based on specified dimensions.
25+
- **Edge Enhance**: Enhances the edges of an image.
26+
- **Generate Thumbnail**: Creates thumbnails from images with specified dimensions.
27+
- **Image Dimensions**: Extracts the dimensions of various image formats.
28+
- **Resize Image**: Resizes images while maintaining aspect ratio.
29+
30+
### **Dependencies**
31+
32+
- **Netlify**: For deploying serverless functions.
33+
- **ImageMagick**: For performing image manipulations.
34+
- **multiParser**: For parsing multipart form data.
35+
36+
### **Installation**
37+
38+
To set up the project locally, follow these steps:
39+
40+
1. **Clone the Repository**:
41+
42+
```bash
43+
git clone https://github.com/samestrin/image-size-api-netlify-edge-functions.git
44+
cd image-size-api-netlify-edge-functions
45+
```
46+
47+
2. **Install Dependencies**: Ensure you have the required dependencies installed. Use npm or yarn to install any necessary packages.
48+
49+
```bash
50+
npm install
51+
```
52+
53+
3. **Set Up Netlify CLI**: Install the Netlify CLI to deploy and test the functions locally.
54+
55+
```bash
56+
57+
npm install -g netlify-cli
58+
```
59+
60+
4. **Run the Functions Locally**: Use the Netlify CLI to run the edge functions locally.
61+
62+
```bash
63+
netlify dev
64+
```
65+
66+
### **Configuration**
67+
68+
The `**netlify.toml**` file contains the configuration for the edge functions. Each function is mapped to a specific endpoint:
69+
70+
```toml
71+
[build]
72+
publish = "public"
73+
functions = "netlify/functions"
74+
75+
[[edge_functions]]
76+
function = "image-dimensions"
77+
path = "/api/image-dimensions"
78+
79+
[[edge_functions]]
80+
function = "convert-image"
81+
path = "/api/convert-image"
82+
83+
[[edge_functions]]
84+
function = "generate-thumbnail"
85+
path = "/api/generate-thumbnail"
86+
87+
[[edge_functions]]
88+
function = "analyze-image"
89+
path = "/api/analyze-image"
90+
91+
[[edge_functions]]
92+
function = "crop-image"
93+
path = "/api/crop-image"
94+
95+
[[edge_functions]]
96+
function = "resize-image"
97+
path = "/api/resize-image"
98+
99+
[[edge_functions]]
100+
function = "edge-enhance"
101+
path = "/api/edge-enhance"
102+
```
103+
104+
Endpoints Documentation
105+
106+
## Endpoints
107+
108+
### Analyze Image
109+
110+
**Endpoint:** `/api/analyze-image`
111+
**Method:** POST
112+
113+
Analyzes an image to compute its brightness and histogram.
114+
115+
- `file`: The image file to be analyzed.
116+
117+
#### Example Usage
118+
119+
Use a tool like Postman or curl to make a request:
120+
121+
```bash
122+
curl -X POST \
123+
https://localhost/api/analyze-image \
124+
-F 'file=@/path/to/image.jpg'
125+
```
126+
127+
The server responds with:
128+
129+
{
130+
"brightness": 123.45,
131+
"histogram": {
132+
"255,255,255": 100,
133+
"0,0,0": 50,
134+
...
135+
}
136+
}
137+
138+
### Convert Image
139+
140+
**Endpoint:** `/api/convert-image`
141+
**Method:** POST
142+
143+
Converts an image to a specified format.
144+
145+
- `file`: The image file to be converted.
146+
- `targetFormat`: The desired target format (e.g., `png`, `jpeg`).
147+
148+
#### Example Usage
149+
150+
Use a tool like Postman or curl to make a request:
151+
152+
```bash
153+
curl -X POST \
154+
https://localhost/api/convert-image \
155+
-F 'file=@/path/to/image.jpg' \
156+
-F 'targetFormat=png'
157+
```
158+
159+
The server responds with the converted image file.
160+
161+
### Crop Image
162+
163+
**Endpoint:** `/api/crop-image`
164+
**Method:** POST
165+
166+
Crops an image based on the specified dimensions.
167+
168+
- `file`: The image file to be cropped.
169+
- `x`: The x-coordinate of the top-left corner.
170+
- `y`: The y-coordinate of the top-left corner.
171+
- `width`: The width of the cropped area.
172+
- `height`: The height of the cropped area.
173+
174+
#### Example Usage
175+
176+
Use a tool like Postman or curl to make a request:
177+
178+
```bash
179+
curl -X POST \
180+
https://localhost/api/crop-image \
181+
-F 'file=@/path/to/image.jpg' \
182+
-F 'x=10' \
183+
-F 'y=10' \
184+
-F 'width=100' \
185+
-F 'height=100'
186+
```
187+
188+
The server responds with the cropped image file.
189+
190+
### Edge Enhance
191+
192+
**Endpoint:** `/api/edge-enhance`
193+
**Method:** POST
194+
195+
Enhances the edges of an image.
196+
197+
- `file`: The image file to be processed.
198+
199+
#### Example Usage
200+
201+
Use a tool like Postman or curl to make a request:
202+
203+
```bash
204+
curl -X POST \
205+
https://localhost/api/edge-enhance \
206+
-F 'file=@/path/to/image.jpg'
207+
```
208+
209+
The server responds with the edge-enhanced image file.
210+
211+
### Generate Thumbnail
212+
213+
**Endpoint:** `/api/generate-thumbnail`
214+
**Method:** POST
215+
216+
Generates a thumbnail from an image with specified dimensions.
217+
218+
- `file`: The image file to be used for generating the thumbnail.
219+
- `width`: The width of the thumbnail.
220+
- `height`: The height of the thumbnail.
221+
222+
#### Example Usage
223+
224+
Use a tool like Postman or curl to make a request:
225+
226+
```bash
227+
curl -X POST \
228+
https://localhost/api/generate-thumbnail \
229+
-F 'file=@/path/to/image.jpg' \
230+
-F 'width=100' \
231+
-F 'height=100'
232+
```
233+
234+
The server responds with the generated thumbnail image.
235+
236+
### Image Dimensions
237+
238+
**Endpoint:** `/api/image-dimensions`
239+
**Method:** POST
240+
241+
Extracts the dimensions of an image.
242+
243+
- `file`: The image file to be analyzed.
244+
245+
#### Example Usage
246+
247+
Use a tool like Postman or curl to make a request:
248+
249+
```bash
250+
curl -X POST \
251+
https://localhost/api/image-dimensions \
252+
-F 'file=@/path/to/image.jpg'
253+
```
254+
255+
The server responds with:
256+
257+
{
258+
"filename": "image.jpg",
259+
"dimensions": {
260+
"width": 800,
261+
"height": 600
262+
}
263+
}
264+
265+
### Resize Image
266+
267+
**Endpoint:** `/api/resize-image`
268+
**Method:** POST
269+
270+
Resizes an image while maintaining the aspect ratio.
271+
272+
- `file`: The image file to be resized.
273+
- `width`: The desired width of the resized image.
274+
- `height`: The desired height of the resized image.
275+
276+
#### Example Usage
277+
278+
Use a tool like Postman or curl to make a request:
279+
280+
```bash
281+
curl -X POST \
282+
https://localhost/api/resize-image \
283+
-F 'file=@/path/to/image.jpg' \
284+
-F 'width=800' \
285+
-F 'height=600'
286+
```
287+
288+
The server responds with the resized image file.
289+
290+
## Error Handling
291+
292+
The API handles errors gracefully and returns appropriate error responses:
293+
294+
- **400 Bad Request**: Invalid request parameters.
295+
- **404 Not Found**: Resource not found.
296+
- **405 Method Not Allowed**: Invalid request method (not POST).
297+
- **500 Internal Server Error**: Unexpected server error.
298+
299+
## Contribute
300+
301+
Contributions to this project are welcome. Please fork the repository and submit a pull request with your changes or improvements.
302+
303+
## License
304+
305+
This project is licensed under the MIT License - see the LICENSE file for details.
306+
307+
## Share
308+
309+
[![Twitter](https://img.shields.io/badge/X-Tweet-blue)](https://twitter.com/intent/tweet?text=Check%20out%20this%20awesome%20project!&url=https://github.com/samestrin/image-api-netlify-edge-function) [![Facebook](https://img.shields.io/badge/Facebook-Share-blue)](https://www.facebook.com/sharer/sharer.php?u=https://github.com/samestrin/image-api-netlify-edge-function) [![LinkedIn](https://img.shields.io/badge/LinkedIn-Share-blue)](https://www.linkedin.com/sharing/share-offsite/?url=https://github.com/samestrin/image-api-netlify-edge-function)

netlify/edge-functions/analyze-image.ts

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,17 @@ export default async (request: Request) => {
5353

5454
export const config = { path: "/api/analyze-image" };
5555

56-
// Helper function to get brightness using ImageMagick
56+
/**
57+
* Calculates the brightness of an image.
58+
*
59+
* @param data - The image data as a Uint8Array.
60+
* @returns The average brightness of the image.
61+
* @throws Will throw an error if reading the image fails.
62+
*
63+
* @example
64+
* // How to use the function.
65+
* const brightness = await getBrightness(fileData);
66+
*/
5767
async function getBrightness(data: Uint8Array): Promise<number> {
5868
let brightness = 0;
5969
await ImageMagick.read(data, (image: MagickImage) => {
@@ -80,7 +90,17 @@ async function getBrightness(data: Uint8Array): Promise<number> {
8090
return brightness;
8191
}
8292

83-
// Custom function to get histogram data
93+
/**
94+
* Generates the histogram of an image.
95+
*
96+
* @param data - The image data as a Uint8Array.
97+
* @returns An object representing the histogram of the image.
98+
* @throws Will throw an error if generating the histogram fails.
99+
*
100+
* @example
101+
* // How to use the function.
102+
* const histogram = getHistogram(fileData);
103+
*/
84104
function getHistogram(data: Uint8Array): Record<string, number> {
85105
const histogram: Record<string, number> = {};
86106
for (let i = 0; i < data.length; i += 4) {

netlify/edge-functions/crop-image.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,17 @@ import {
99

1010
await initialize();
1111

12+
/**
13+
* Handles the image cropping request.
14+
*
15+
* @param request - The incoming HTTP request.
16+
* @returns The HTTP response with the cropped image or an error message.
17+
* @throws Will throw an error if the request method is not POST or if processing fails.
18+
*
19+
* @example
20+
* // How to call the function.
21+
* fetch('/api/crop-image', { method: 'POST', body: formData });
22+
*/
1223
export default async (request: Request) => {
1324
if (request.method === "POST") {
1425
try {

netlify/edge-functions/generate-thumbnail.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,17 @@ import {
99

1010
await initialize();
1111

12+
/**
13+
* Handles the image thumbnail generation request.
14+
*
15+
* @param request - The incoming HTTP request.
16+
* @returns The HTTP response with the generated thumbnail or an error message.
17+
* @throws Will throw an error if the request method is not POST or if processing fails.
18+
*
19+
* @example
20+
* // How to call the function.
21+
* fetch('/api/generate-thumbnail', { method: 'POST', body: formData });
22+
*/
1223
export default async (request: Request) => {
1324
if (request.method === "POST") {
1425
try {

0 commit comments

Comments
 (0)