Astro Image Component: Optimize รูปภาพอัตโนมัติ
#astro13 เม.ย. 2569
ทำไม Image Optimization ถึงสำคัญ
รูปภาพมักเป็นสาเหตุหลักที่ทำให้เว็บช้า Astro มี Image component ที่ optimize รูปอัตโนมัติ
Image Component
---
import { Image } from 'astro:assets';
import heroImage from '../assets/hero.jpg';
---
<!-- Basic usage -->
<Image
src={heroImage}
alt="Hero image"
width={800}
height={400}
/>
<!-- WebP format -->
<Image
src={heroImage}
alt="Hero"
format="webp"
quality={80}
/>
<!-- Lazy loading -->
<Image
src={heroImage}
alt="Hero"
loading="lazy"
/>
<!-- Priority (above the fold) -->
<Image
src={heroImage}
alt="Hero"
loading="eager"
/>
Picture Component (Responsive)
---
import { Picture } from 'astro:assets';
import heroImage from '../assets/hero.jpg';
---
<Picture
src={heroImage}
formats={['avif', 'webp', 'jpeg']}
widths={[400, 800, 1200]}
sizes="(max-width: 400px) 400px, (max-width: 800px) 800px, 1200px"
alt="Hero"
/>
Remote Images
// astro.config.mjs
export default defineConfig({
image: {
domains: ['images.unsplash.com', 'cdn.example.com'],
remotePatterns: [{ protocol: 'https' }]
}
});
<Image
src="https://images.unsplash.com/photo-xxx"
alt="Remote image"
width={800}
height={600}
/>
Background Images
---
import { getImage } from 'astro:assets';
import bgImage from '../assets/bg.jpg';
const optimizedBg = await getImage({
src: bgImage,
format: 'webp',
width: 1920
});
---
<div style={`background-image: url(${optimizedBg.src})`}>
<slot />
</div>
ผลลัพธ์
ก่อน: hero.jpg = 2.5MB
หลัง: hero.webp = 120KB (ลดลง 95%!)
Lighthouse:
- LCP: 0.8s (จาก 3.2s)
- Performance: 98 (จาก 72)
สรุป
Astro Image component ทำ optimization ให้อัตโนมัติ แปลงเป็น WebP/AVIF, resize ตาม viewport และ lazy load ช่วยให้ Lighthouse score ดีขึ้นมากครับ