|
| 1 | +// src/pages/api/image.ts |
| 2 | +import sharp from 'sharp'; |
| 3 | +import type { APIRoute } from 'astro'; |
| 4 | +import fs from 'fs'; |
| 5 | +import path from 'path'; |
| 6 | +import crypto from 'crypto'; |
| 7 | + |
| 8 | +export const prerender = false; |
| 9 | + |
| 10 | +const CACHE_DIR = './public/image-cache'; |
| 11 | + |
| 12 | +export const GET: APIRoute = async ({ url }) => { |
| 13 | + const searchParams = new URL(url).searchParams; |
| 14 | + const imageUrl = searchParams.get('src'); |
| 15 | + |
| 16 | + if (!imageUrl) { |
| 17 | + return new Response('Missing src parameter', { status: 400 }); |
| 18 | + } |
| 19 | + |
| 20 | + try { |
| 21 | + // Create cache key from URL |
| 22 | + const cacheKey = crypto.createHash('md5').update(imageUrl).digest('hex'); |
| 23 | + const cachePath = path.join(CACHE_DIR, `${cacheKey}.avif`); |
| 24 | + |
| 25 | + // Check if cached version exists |
| 26 | + if (fs.existsSync(cachePath)) { |
| 27 | + const cachedImage = fs.readFileSync(cachePath); |
| 28 | + return new Response(cachedImage, { |
| 29 | + headers: { |
| 30 | + 'Content-Type': 'image/avif', |
| 31 | + 'Cache-Control': 'public, max-age=31536000' // 1 year |
| 32 | + } |
| 33 | + }); |
| 34 | + } |
| 35 | + |
| 36 | + // Fetch original image |
| 37 | + const imageResponse = await fetch(imageUrl); |
| 38 | + if (!imageResponse.ok) { |
| 39 | + throw new Error(`Failed to fetch image: ${imageResponse.status}`); |
| 40 | + } |
| 41 | + |
| 42 | + const imageBuffer = await imageResponse.arrayBuffer(); |
| 43 | + |
| 44 | + // Process with Sharp: resize to 160x160 and convert to avif |
| 45 | + const processedImage = await sharp(Buffer.from(imageBuffer)) |
| 46 | + .resize(160, 160, { |
| 47 | + fit: 'cover', |
| 48 | + position: 'center' |
| 49 | + }) |
| 50 | + .avif({ quality: 75 }) |
| 51 | + .toBuffer(); |
| 52 | + |
| 53 | + // Cache the processed image |
| 54 | + fs.mkdirSync(CACHE_DIR, { recursive: true }); |
| 55 | + fs.writeFileSync(cachePath, processedImage); |
| 56 | + |
| 57 | + return new Response(processedImage, { |
| 58 | + headers: { |
| 59 | + 'Content-Type': 'image/avif', |
| 60 | + 'Cache-Control': 'public, max-age=31536000' |
| 61 | + } |
| 62 | + }); |
| 63 | + } catch (error) { |
| 64 | + console.error('Image processing error:', error); |
| 65 | + |
| 66 | + // Return your default image as fallback |
| 67 | + try { |
| 68 | + const fallbackPath = './public/images/www.png'; |
| 69 | + const fallbackImage = fs.readFileSync(fallbackPath); |
| 70 | + return new Response(fallbackImage, { |
| 71 | + headers: { 'Content-Type': 'image/png' } |
| 72 | + }); |
| 73 | + } catch { |
| 74 | + return new Response('Image not found', { status: 404 }); |
| 75 | + } |
| 76 | + } |
| 77 | +}; |
0 commit comments