Updated image component

This commit is contained in:
Patrick Alvin Alcala 2025-08-26 17:59:33 +08:00
parent 3029cafec6
commit 578af482d9

View file

@ -1,4 +1,6 @@
import sharp from 'sharp' import sharp from 'sharp'
import { createSignal } from 'solid-js'
import fs from 'fs'
interface Props { interface Props {
src: string src: string
@ -7,22 +9,28 @@ interface Props {
} }
const convertImage = async (props: Props) => { const convertImage = async (props: Props) => {
const webp = await sharp(`src/assets/images/${props.src}`).webp({ quality: 75 }).resize(props.size).toBuffer() const webpOutputPath = `src/assets/compressed-images/${props.src.split('.').slice(0, -1).join('.')}.webp`
await sharp(webp).toFile(`src/assets/compressed-images/${props.src.split('.').slice(0, -1).join('.')}.webp`) const avifOutputPath = `src/assets/compressed-images/${props.src.split('.').slice(0, -1).join('.')}.avif`
const avif = await sharp(`src/assets/images/${props.src}`).avif({ quality: 60 }).resize(props.size).toBuffer() if (!fs.existsSync(webpOutputPath) || !fs.existsSync(avifOutputPath)) {
await sharp(avif).toFile(`src/assets/compressed-images/${props.src.split('.').slice(0, -1).join('.')}.avif`) const webpBuffer = await sharp(`src/assets/images/${props.src}`).webp({ quality: 75 }).resize(props.size).toBuffer()
await sharp(webpBuffer).toFile(webpOutputPath)
const avifBuffer = await sharp(`src/assets/images/${props.src}`).avif({ quality: 60 }).resize(props.size).toBuffer()
await sharp(avifBuffer).toFile(avifOutputPath)
}
} }
export default (props: Props) => { export default (props: Props) => {
let [imageSrc] = createSignal(`src/assets/compressed-images/${props.src.split('.').slice(0, -1).join('.')}.webp`)
convertImage(props) convertImage(props)
return ( return (
<> <>
<picture class="fullscreen"> <picture >
<source srcset={`src/assets/compressed-images/${props.src.split('.').slice(0, -1).join('.')}.avif`} type="image/avif" /> <source srcset={imageSrc().replace(/\.webp$/, '.avif')} type="image/avif" />
<source srcset={`src/assets/compressed-images/${props.src.split('.').slice(0, -1).join('.')}.webp`} type="image/webp" /> <source srcset={imageSrc()} type="image/webp" />
<img src={`src/assets/compressed-images/${props.src.split('.').slice(0, -1).join('.')}.webp`} width={props.size} height="auto" decoding="async" loading="lazy" alt={props.alt} /> <img src={imageSrc()} width={props.size} height="auto" decoding="async" loading="lazy" alt={props.alt} />
</picture> </picture>
</> </>
) )