Skip to content

Instantly share code, notes, and snippets.

@Sandstedt
Last active May 20, 2022 12:37
Show Gist options
  • Save Sandstedt/bbde2b9626600706f2e013b6fa3ca6d8 to your computer and use it in GitHub Desktop.
Save Sandstedt/bbde2b9626600706f2e013b6fa3ca6d8 to your computer and use it in GitHub Desktop.
Create an image prop for use with strapi-plugin-local-image-sharp for use with next/image
const CMS_URL = "http://localhost:1337"
/*
Create an image object for strapi-plugin-local-image-sharp
Docs: https://github.com/strapi-community/strapi-plugin-local-image-sharp
Credit: Jonas Sandstedt, Fully Studios
Licence: MIT
Basic Usage:
<Image
{...SharpImageProps({
url: image.url,
ratio: [16, 9]
}}
sizes="100vw"
alt={image.alternativeText}
/>
Grayscale:
<Image
{...SharpImageProps({
url: image.url,
ratio: [16, 9]
grayscale: true,
}}
sizes="100vw"
alt={image.alternativeText}
/>
Controll with, height and/or position:
<Image
{...SharpImageProps({
url: image.url,
width: 4000,
height: 4000,
position: "right",
}}
sizes="100vw"
alt={image.alternativeText}
/>
Colorize or other custom props:
<Image
{...SharpImageProps({
url: image.url,
ratio: [16, 9]
otherProps: ["tint_1098123", "quality_50"],
}}
sizes="100vw"
alt={image.alternativeText}
/>
*/
/**
* @param {string} url - The image URL from Strapi - ex "/uploads/test1_686afb340a.jpg"
* @param {array|boolean} [ratio] - An array with the ratio. Ex [16, 9]
* @param {number} [width] - The generated image width
* @param {number} [height] - The generated image height
* @param {string} [position] - Crop position. Ex: top, right top, right, right bottom, bottom, left bottom, left, left top.
* @returns
*/
export function SharpImageProps(props) {
const {
url = false,
ratio = false,
width = 3840, // default largest device size in next.config.js
height = 1080,
position = "center",
grayscale = false,
otherProps = [],
} = props;
if (!url) {
console.log("No url provided", props);
return false;
}
const sizeObj = ratio ? RatioCalculator(ratio, width) : [width, height];
const size = `,s_${sizeObj[0] + "x" + sizeObj[1]}`;
const obj = {
src: `${CMS_URL}${url}`.replace(
"uploads",
`$&/enlarge${size},pos_${position}${grayscale ? ",grayscale" : ""}${
otherProps.length ? "," + String(otherProps) : ""
}`
),
width: sizeObj[0],
height: sizeObj[1],
};
return obj;
}
/**
*
* @param {array} aspect - Array with the ratio. Ex [16, 9]
* @param {*} width - The width you wanna apply the ratio to. Ex 1000
* @returns - Returns a with and height as an array. Ex [1000, 563]
*/
export function RatioCalculator(aspect, width) {
// (original height / original width) x new width = new height
const height = (aspect[1] / aspect[0]) * width;
return [width, height];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment