Created
October 12, 2025 21:22
-
-
Save varo6/aee69dd293f3b27331432a426efa08d9 to your computer and use it in GitHub Desktop.
bun's profile pic compress and storage it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Hono } from 'hono' | |
| import sharp from 'sharp' | |
| import { mkdir } from 'fs/promises' | |
| import { join } from 'path' | |
| import { randomUUID } from 'crypto' | |
| const app = new Hono() | |
| const UPLOAD_DIR = 'uploads' | |
| await mkdir(UPLOAD_DIR, { recursive: true }) | |
| app.post('/compress', async (c) => { | |
| const body = await c.req.parseBody() | |
| const file = body['image'] | |
| if (!file || !(file instanceof File)) { | |
| return c.json({ error: 'No image provided' }, 400) | |
| } | |
| const buffer = await file.arrayBuffer() | |
| const compressed = await sharp(buffer) | |
| .resize(512, 512, { fit: 'cover' }) | |
| .webp({ quality: 85 }) | |
| .toBuffer() | |
| const filename = `${randomUUID()}.webp` | |
| await Bun.write(join(UPLOAD_DIR, filename), compressed) | |
| return c.json({ filename }) | |
| }) | |
| app.get('/image/:filename', async (c) => { | |
| const filename = c.req.param('filename') | |
| const filepath = join(UPLOAD_DIR, filename) | |
| try { | |
| const image = await Bun.file(filepath).arrayBuffer() | |
| return new Response(image, { | |
| headers: { 'Content-Type': 'image/webp' } | |
| }) | |
| } catch { | |
| return c.json({ error: 'Image not found' }, 404) | |
| } | |
| }) | |
| app.get('/', (c) => { | |
| return c.text('Usage: POST /compress to compress an image and GET /image/:filename to receive the image') | |
| }) | |
| export default app |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment