Question about <picture> for WebP/AVIF support #68
-
This is more of a curiosity than a feature request and might be limited by my own understanding as responsive images can melt the brain a bit! Is your feature request related to a problem? Please describe. Describe the solution you'd like Describe alternatives you've considered |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 5 replies
-
I hadn't even noticed that Contentful didn't support auto-format! That's quite a shortcoming. I have thought about creating a |
Beta Was this translation helpful? Give feedback.
-
The biggest problem we have for creating a |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
If anyone stumbles across this and wants a starter, here's my first crack at it in a NextJS project. Note this is for adding AVIF support and doesn't have any art-direction features. import { Image, Source, ImageProps } from "@unpic/react"
import { clsx } from "clsx/lite"
import React from "react"
type TContentfulImageProps = {
fit?: "pad" | "fill" | "scale" | "crop" | "thumb"
focusArea?: string | null
formats?: Array<"jpg" | "png" | "webp" | "gif" | "avif">
radius?: "max"
quality?: number
style?: React.CSSProperties
} & ImageProps
export const ContentfulImage = ({
alt,
fit = "fill",
focusArea,
formats = ["avif", "webp", "jpg"],
background = "auto",
className,
radius,
quality = 75,
src,
...props
}: TContentfulImageProps) => {
// Ensure the src is an absolute URL this should never happen but... u know
src = src.startsWith("http") ? src : `https:${src}`
focusArea = focusArea ?? "faces"
const url = new URL(src)
url.searchParams.append("fit", fit)
url.searchParams.append("f", focusArea)
url.searchParams.append("q", quality.toString())
if (radius) {
url.searchParams.append("r", radius)
}
const sourceTags = formats.map(format => {
const sourceUrl = new URL(url)
sourceUrl.searchParams.append("fm", format)
return (
<Source
type={`image/${format}`}
{...props}
key={format}
src={sourceUrl.toString()}
/>
)
})
return (
<picture>
{sourceTags}
<Image
className={clsx(
styles.image,
className
)}
{...props}
background={background}
alt={alt}
src={url.toString()}
cdn={"contentful"}
/>
</picture>
)
} |
Beta Was this translation helpful? Give feedback.
<picture>
tag support is in the latest release: https://dev.to/ascorbic/level-up-your-web-images-with-unpic-picture-tags-4jh1