-
Notifications
You must be signed in to change notification settings - Fork 20
/
optimize-image.ts
executable file
·88 lines (72 loc) · 2.12 KB
/
optimize-image.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import type { ImageOptions, ImageOptimized } from '~~/types/image'
export const useOptimizeImage = () => {
const img = useImage()
const optimizeImage = (
src: string,
optionsWithSizes: ImageOptions = {},
bgStyles = false,
): ImageOptimized => {
const {
sizes = 'xs:100vw sm:100vw md:100vw lg:100vw xl:100vw',
...optionsWithPlaceholder
} = optionsWithSizes
const {
placeholder = {
width: 10,
height: 10,
quality: 50,
blur: 3,
},
...options
} = optionsWithPlaceholder
const resolvedImage = img.getImage(src, {
...options,
})
const placeholderImage =
placeholder &&
img.getImage(src, {
...options,
placeholder,
})
const imageSizes = img.getSizes(src, {
...options,
sizes,
})
const imageOptimized: ImageOptimized = Object.assign(
{},
{
src: resolvedImage.url,
lazySrc: placeholderImage?.url,
...imageSizes,
},
)
if (bgStyles) {
try {
// https://dev.to/ingosteinke/responsive-background-images-with-image-set-the-srcset-for-background-image-259a
const responsiveImages = computed(() => {
return imageOptimized.srcset
.split(', ')
.filter(
(imgUrl) => imgUrl.endsWith('768w') || imgUrl.endsWith('2560w'),
)
})
const responsiveImageSrc = `url("${responsiveImages.value[0]}")`
const responsiveImageSrcImageSet = `image-set(url("${responsiveImages.value[0]}") 1x,url("${responsiveImages.value[1]}") 2x)`
const responsiveImageSrcImageSetFallback = `-webkit-image-set(url("${responsiveImages.value[0]}") 1x,url("${responsiveImages.value[1]}") 2x)`
imageOptimized.bgStyles = [
responsiveImageSrc,
responsiveImageSrcImageSet,
responsiveImageSrcImageSetFallback,
].reduce((acc, bgStyle) => {
return `${acc}background-image:${bgStyle};`
}, '')
} catch (err) {
console.log(err)
}
}
return imageOptimized
}
return {
optimizeImage,
}
}