Sometimes you might need to use a generated image URL directly with applied transformations instead of the <NuxtImg> and <NuxtPicture> components. This is where useImage() comes in (and the helper function it returns, which you will often see referenced directly as $img or img).
const img = useImage()
img(src, modifiers, options)
Example: Generate image URL for backgroundImage style.
const img = useImage()
const backgroundStyles = computed(() => {
const imgUrl = img('https://github.com/nuxt.png', { width: 100 })
return { backgroundImage: `url('${imgUrl}')` }
})
img.getSizesconst img = useImage()
img.getSizes(src, { sizes, modifiers })
getSizes API might change or be removed.Parameters:
src: (string) Source to original image idsizes: (string) List of responsive image sizes ({breakpoint}:{size}{unit})modifiers: (object) Modifiers passed to provider for resizing and optimizing
width: resize to the specified width (in pixels)height: resize to specified height (in pixels)quality: Change image quality (0 to 100)format: Change the image formatoptions: (object)
Example: Responsive srcset with Vuetify v-img
<template>
<v-img
:lazy-src="img(src, { width: 10, quality: 70 })"
:src="img(src, { height, quality: 70 })"
:srcset="_srcset.srcset"
:height="height"
:sizes="_srcset.sizes"
/>
</template>
<script setup lang="ts">
const props = defineProps({
height: {
type: [Number, String],
default: 500
},
src: {
type: String,
default: '/img/header-bg.jpg'
}
})
const img = useImage()
const _srcset = computed(() => {
return img.getSizes(props.src, {
sizes: 'sm:100vw md:100vw lg:100vw xl:100vw',
modifiers: {
format: 'webp',
quality: 70,
height: props.height
}
})
})
</script>