How to modify images using the hotspot and crop attributes in Sanity.io

36 replies
Last updated: Dec 22, 2021
Hi, I just started with sanity not long ago. I was wondering how I can modify my image from the query using the hotspot and crop attributes from the query. I went through the documentation but it seems that it didn’t work for me.
Dec 2, 2021, 9:12 PM
Hi User. If you’re using JavaScript on your front end, the image builder is the way to go.
1. Import your client and the image-builder and configure a function. This is often done in its own file so that it can be easily imported into any file that uses it (see
sanity.js
).2. Import the function into the file(s) where you need it.
import { urlFor } from '../lib/sanity'
, for example.3. Use the function in your image’s
src
attribute (see
file.js
).
// lib/sanity.js (could be named whatever you want)
//
// I'm pulling in the dataset and projectId from a .env file

import sanityClient from '@sanity/client';
import imageUrlBuilder from '@sanity/image-url';

export const options = {
  dataset: process.env.NEXT_PUBLIC_SANITY_DATASET_NAME,
  projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
  useCdn: process.env.NODE_ENV === 'production',
  apiVersion: '2021-03-25',
};

export const client = sanityClient(options);

export function urlFor(source) {
  const imageBuilder = imageUrlBuilder(client);
  return imageBuilder.image(source);
}

// file.js
//
// However you're pulling in your data, let's assume you've
// destructured so there's an image called image and alt text
// in imageAlt. You can chain image builder methods per the
// docs at <https://www.sanity.io/docs/image-url>

<img
  src={urlFor(image).width(575).fit('max').url()}
  alt={imageAlt}
/>

// ...
The image builder will respect the crops and hotspots that have been set in the studio.
Dec 2, 2021, 9:27 PM
Will the image builder use all the properties from crop and hotspot from sanity ui?
Dec 2, 2021, 9:28 PM
Yes. Edited to add that bit.
Dec 2, 2021, 9:29 PM
Let me try that, thanks. I’ll follow up if I encounter issues
Dec 2, 2021, 9:29 PM
Sounds good! 🙌
Dec 2, 2021, 9:29 PM
Just one thing, to make sure im querying the proper stuff
Dec 2, 2021, 9:37 PM
My current code to query is this:
Dec 2, 2021, 9:37 PM
`*[_type == "post"] | order(publishedAt desc) {
					title,
					slug,
					publishedAt,
					description,
					mainImage {
						asset -> {
							_id,
							url
						},
						crop,
            			hotspot,
						alt
					}
				}`
Dec 2, 2021, 9:37 PM
In that case, I believe
<img src={urlFor(mainImage).url()} alt={mainImage.alt} />
should work (with whatever other methods you want—just put
url()
last).
Dec 2, 2021, 9:40 PM
In that case, I believe
<img src={urlFor(mainImage).url()} … />
should work (with whatever other methods you want—just put
url()
last).
Dec 2, 2021, 9:40 PM
.url() inside the src, right?
Dec 2, 2021, 9:41 PM
Correct.
Dec 2, 2021, 9:41 PM
alright, let me give it a try
Dec 2, 2021, 9:41 PM
And all of this inside of a
.map()
, since your query is returning an array of posts.
Dec 2, 2021, 9:42 PM
oh yeah, i have the map, i managed to get the rest of the data out
Dec 2, 2021, 9:42 PM
i just need to format the image which i couldnt
Dec 2, 2021, 9:42 PM
let me try the image thing
Dec 2, 2021, 9:42 PM
im trying to import urlFor
Dec 2, 2021, 9:51 PM
not sure where should i import it from
Dec 2, 2021, 9:51 PM
It would need to be set up and exported from a file (in my example above, the last 4 lines of
lib/sanity.js
).
Dec 2, 2021, 9:52 PM
oh so i can copy the example you gave me and put it in my src
Dec 2, 2021, 9:52 PM
You should be able to, yes. You’ll want to install those packages with npm or yarn, and you may need to change the bit where you specify your dataset and projectId, but otherwise it should be copy-and-pasteable.
Dec 2, 2021, 9:54 PM
let me try that 🙂
Dec 2, 2021, 9:55 PM
it doesnt seem to change anything
Dec 2, 2021, 10:22 PM
so heer is the query
Dec 2, 2021, 10:22 PM
`*[slug.current == "${slug}"]{
            title,
            _id,
            slug,
			publishedAt,
			postImage{
                asset->{
                    _id,
                    url
                },
				crop,
				hotspot,
				alt
            },
            mainImage{
                asset->{
                    _id,
                    url
                },
				crop,
				hotspot,
				alt
            },
            body,
            "name": author->name,
            "authorImage": author->image,
        }`
Dec 2, 2021, 10:22 PM
<img
						src={urlFor(singleInsight.postImage.asset.url).url()}
						alt={singleInsight.postImage.alt}
						/>
Dec 2, 2021, 10:23 PM
unless im doing it wrong haha
Dec 2, 2021, 10:24 PM
src={urlFor(singleInsight.postImage.asset.url).url()}
should be just
src={urlFor(singleInsight.postImage).url()}
(or maybe even
src={urlFor(postImage).url()}
).
Dec 2, 2021, 10:25 PM
oh
Dec 2, 2021, 10:26 PM
i see
Dec 2, 2021, 10:26 PM
yep it worked
Dec 2, 2021, 10:26 PM
thank you so much!
Dec 2, 2021, 10:26 PM
great help man! have a great day
Dec 2, 2021, 10:26 PM
Great! Glad to hear it. Thanks, you too! 🙌
Dec 2, 2021, 10:26 PM
Ah! I think your explanation,
user A
, is what I need. I'm reading the docs about the image builder but it wasn't clear to me where to put the imageBuilder code: in my config file under /lib, in each file or in its own file (somewhere). I think this will get me there. I'm commenting to say thanks for the explanation and to "bookmark" it so I can find it again!
I'm referring to this code:


import React from 'react'
import client from './sanityClient'
import imageUrlBuilder from '@sanity/image-url'

// Get a pre-configured url-builder from your sanity client
const builder = imageUrlBuilder(client)

// Then we like to make a simple function like this that gives the
// builder an image and returns the builder for you to specify additional
// parameters:
function urlFor(source) {
return builder.image(source)
}```

from
https://www.sanity.io/docs/presenting-images#mY9Be3Ph
(And sorry, I can't seem to code block on my tablet!)
Dec 22, 2021, 4:35 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?