본문 바로가기
FrontEnd

Cloudflare 이미지 변환을 활용한 최적화된 이미지 처리

by E_van 2025. 3. 4.

웹사이트에서 이미지 최적화는 필수적인 요소입니다. 특히, 다양한 해상도와 디바이스에서 최적의 품질을 유지하면서 로딩 속도를 개선하는 것이 중요합니다. Cloudflare의 이미지 변환(Image Resizing) 기능을 활용하면 URL을 통해 간단하게 이미지를 변환하고 최적화할 수 있습니다. 이 글에서는 Cloudflare의 이미지 변환 기능을 활용하여 최적화된 이미지 URL을 생성하는 imageConverter 함수와 반응형 이미지 URL을 생성하는 getSource 함수, 그리고 이를 활용한 makeConvertedThumb 함수를 소개합니다.

1. imageConverter: Cloudflare를 이용한 이미지 변환 URL 생성

const formats = { optimization: ['avif', 'webp'], old: ['jpeg', 'jpg', 'png'] }
const allFormat = [...formats.optimization, ...formats.old]

interface Converter {
  thumbnail: string
  options: {
    width: number
    height: number
    format?: (typeof allFormat)[number]
    dpr?: number
    quality?: number
    fit?: 'cover' | 'crop' | 'pad' | 'contain' | 'scale-down'
  }
}

export const imageConverter = ({ thumbnail, options }: Converter): string => {
  const transformOptions = {
    width: options.width,
    height: options.height,
    format: options.format ?? 'avif',
    dpr: options.dpr ?? 1,
    quality: options.quality ?? 100,
    fit: options.fit ?? 'cover'
  };
  
  const cdnUrl = env.VITE_CDN_URL;
  const splitKey = '/images';
  const contentUrl = thumbnail?.split(splitKey)[1] ?? '';
  const optionsString =
    Object.entries(transformOptions)
      ?.map(([key, value]) => `${key}=${value}`)
      .join(',') ?? '';
  
  return `${cdnUrl}/cdn-cgi/image/${optionsString}${splitKey}${contentUrl}`;
};

이 함수는 Cloudflare의 변환 기능을 활용하여 최적화된 이미지 URL을 반환합니다. 기본적으로 avif 형식을 사용하며, dpr, quality, fit 옵션도 조정할 수 있습니다.

2. getSource: 반응형 이미지 URL 생성

export const getSource = ({ thumbnail, options }: Converter): string => {
  const basicImage = imageConverter({ thumbnail, options })
  const doubleImage = imageConverter({ thumbnail, options: { ...options, dpr: 2 } })
  return `${basicImage} 1x, ${doubleImage} 2x`
}

이 함수는 dpr 값을 활용하여 1x2x 해상도의 이미지 URL을 생성합니다. 이를 통해 고해상도 디바이스에서도 최적화된 이미지를 제공할 수 있습니다.

3. makeConvertedThumb: 최적화된 썸네일 HTML 생성

export const makeConvertedThumb = ({ thumbnail, options, alt }: Converter & { alt: string }): string => {
  const sources = formats.optimization
    .map(
      (format) =>
        `<source srcset="${getSource({ thumbnail, options: { ...options, format } })}" type="image/${format}">`
    ).join('')

  return `
    <span class="thumb-box">
      <picture class="picture">
        ${sources}
        <img class="thumbnail" srcset="${getSource({ thumbnail, options: { ...options, format: 'jpeg' } })}"
          src="${thumbnail}" alt="${alt}" loading="lazy" width="${options.width}" height="${options.height}">
      </picture>
    </span>`
}

이 함수는 picture 요소를 활용하여 Formats로 선언된 포맷들의 (ex: avif, webp, jpeg)의 이미지 소스를 제공하며, srcset을 통해 반응형 이미지를 적용합니다.

4. 결론

Cloudflare의 이미지 변환 기능을 활용하면 URL을 통해 간편하게 이미지를 최적화하고 반응형으로 변환할 수 있습니다. 위에서 소개한 imageConverter, getSource, makeConvertedThumb 함수를 활용하면 프로젝트에서 더욱 효율적인 이미지 처리가 가능합니다. 앞으로도 이미지 최적화 및 웹 성능 개선을 위해 Cloudflare의 다양한 기능을 활용해 보세요!