Skip to content

Instantly share code, notes, and snippets.

@hellsan631
Created February 18, 2023 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hellsan631/50807a248594316d5116c845e09d9ff2 to your computer and use it in GitHub Desktop.
Save hellsan631/50807a248594316d5116c845e09d9ff2 to your computer and use it in GitHub Desktop.
import { useState, useEffect } from 'react';
export const getCloudinaryUrl = (filename, width = 250) => {
// const base = 'https://res.cloudinary.com/laurabaker/image/fetch'
const base = 'https://res.cloudinary.com/laurabaker/image/upload'
const formats = {
eco: `c_limit,f_auto,fl_apng.awebp,q_auto:low,w_${width}`,
ecoFull: `c_limit,f_auto,fl_apng.awebp,q_auto:low,w_1024`,
thumb: `c_limit,f_auto,fl_apng.awebp,q_auto,w_${width}`,
med: 'c_limit,f_auto,fl_apng.awebp,q_auto:good,w_1024,h_1024',
full: 'c_limit,f_auto,fl_apng.awebp,fl_preserve_transparency,h_2048,q_100,w_2048',
}
return Object.keys(formats).reduce((result, format) => {
return {
...result,
[format]: `${base}/${formats[format]}/remote_media/${filename}`,
}
}, {});
}
export const getCloudinaryFilenameFromFile = ({ hash, ext }) => `${hash}${ext}`
export const LoadImage = (src, fallbackOnError) => {
return new Promise((resolve, reject) => {
requestIdleCallback(() => {
const image = new Image()
image.src = src
image.onload = () => {
return resolve(src);
}
image.onerror = (error) => {
if (fallbackOnError) {
return resolve(fallbackOnError)
}
return reject(error);
}
})
})
}
export function useImgResource({ image, ref }, quality = 'full', loadingQuality = 'eco') {
console.log(image)
const imageUrls = getCloudinaryUrl(getCloudinaryFilenameFromFile(image));
const [imageLoadedUrl, setImageLoadedUrl] = useState(imageUrls[loadingQuality]);
const loadImageState = async () => {
if (ref && ref.current) {
ref.current.onload = async () => {
setTimeout(async () => {
setImageLoadedUrl(
await LoadImage(imageUrls[quality], image.url),
);
}, 1000)
}
} else {
setImageLoadedUrl(
await LoadImage(imageUrls[quality], image.url),
);
}
}
useEffect(() => {
loadImageState();
}, [image]);
return imageLoadedUrl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment