Refactor image optimization to use Astro's built-in image service and update configuration for improved performance
Some checks failed
GitHub Actions / build (18) (push) Has been cancelled
GitHub Actions / build (20) (push) Has been cancelled
GitHub Actions / build (22) (push) Has been cancelled
GitHub Actions / check (push) Has been cancelled

This commit is contained in:
becarta
2025-05-10 00:10:57 +02:00
parent 1d7883a9c7
commit b93f038071
2 changed files with 14 additions and 52 deletions

View File

@@ -118,17 +118,9 @@ export default defineConfig({
],
image: {
domains: ['cdn.pixabay.com', 'raw.githubusercontent.com'],
remotePatterns: [
{
protocol: 'https',
hostname: 'cdn.pixabay.com',
},
{
protocol: 'https',
hostname: 'raw.githubusercontent.com',
},
],
service: {
entrypoint: 'astro/assets/services/sharp',
},
},
markdown: {

View File

@@ -1,4 +1,4 @@
import sharp from 'sharp';
import { getImage } from 'astro:assets';
import type { ImageMetadata } from 'astro';
interface OptimizeImageOptions {
@@ -7,7 +7,6 @@ interface OptimizeImageOptions {
height?: number;
format?: 'webp' | 'avif' | 'jpeg' | 'png';
quality?: number;
fit?: keyof sharp.FitEnum;
}
export async function optimizeImage({
@@ -16,49 +15,20 @@ export async function optimizeImage({
height,
format = 'webp',
quality = 80,
fit = 'cover',
}: OptimizeImageOptions): Promise<ImageMetadata> {
try {
// Load the image
const image = sharp(src);
const optimized = await getImage({
src,
width,
height,
format,
quality,
});
// Get original metadata
const metadata = await image.metadata();
// Resize if dimensions are provided
if (width || height) {
image.resize({
width: width || undefined,
height: height || undefined,
fit,
withoutEnlargement: true,
});
}
// Convert to specified format
switch (format) {
case 'webp':
image.webp({ quality });
break;
case 'avif':
image.avif({ quality });
break;
case 'jpeg':
image.jpeg({ quality });
break;
case 'png':
image.png({ quality });
break;
}
// Generate optimized buffer
const optimizedBuffer = await image.toBuffer();
// Return metadata
return {
src: `data:image/${format};base64,${optimizedBuffer.toString('base64')}`,
width: width || metadata.width || 0,
height: height || metadata.height || 0,
src: optimized.src,
width: optimized.attributes.width,
height: optimized.attributes.height,
format,
};
} catch (error) {