Refactor image optimization to use Astro's built-in image service and update configuration for improved performance
This commit is contained in:
@@ -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: {
|
||||
|
@@ -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) {
|
||||
|
Reference in New Issue
Block a user