导航菜单

Cloudflare Adapter Image Optimization

Why optimize images?

  • Originals are heavy (MB-level).
  • Devices vary; need different sizes and formats (WebP/AVIF/JPEG).
  • Optimized assets improve LCP and cut bandwidth.
  1. Upload originals (dashboard/CLI/API).

  2. Define variants (size, quality, format).

  3. URLs: https://imagedelivery.net/{hash}/{id}/{variant}.

  4. Astro example:

    ---
    const base = "https://imagedelivery.net/<hash>/<id>";
    const variants = [
      { name: "thumb", media: "(max-width: 640px)" },
      { name: "mid", media: "(max-width: 1024px)" },
      { name: "lg", media: "" },
    ];
    ---
    <picture>
      {variants.map((v) => (
        <source srcset={`${base}/${v.name}`} media={v.media} />
      ))}
      <img src={`${base}/lg`} alt="demo" loading="lazy" width="1200" height="600" />
    </picture>
    

Adapter Image Service

  • compile: transcode at build; faster first visit, bigger build time/size.
  • passthrough: transcode at runtime; smaller build, first hit may be slower, depends on Cloudflare runtime.

Passthrough config:

import cloudflare from "@astrojs/cloudflare";
import { defineConfig } from "astro/config";
export default defineConfig({
  adapter: cloudflare({
    imageService: { service: "cloudflare", config: { mode: "passthrough" } },
  }),
});

Edge function transforms (object storage)

  • If images live in S3/OSS: use Pages Functions/Workers + image resizing.
  • URLs like /img?w=800&fmt=webp&url=https://bucket/xxx.jpg.
  • Cache transformed results; cache originals even longer.

Astro usage tips

  • <img> with srcset/sizes; or lightweight @astrojs/image.
  • Always set width/height or aspect-ratio to avoid CLS; add loading="lazy", decoding="async".
  • Backgrounds: multiple sizes/media queries instead of one huge asset.

Quality and formats

  • Prefer WebP/AVIF; fall back to JPEG/PNG when needed.
  • Quality 70–85 is common; use SVG for vectors.

Troubleshooting

  • 404: variant/path mismatch.
  • Slow first hit: passthrough needs initial transcode; pre-warm or switch to compile.
  • Color issues: check quality/format and color space.
  • Large size: lower quality or add more size variants.
  • CLS: ensure width/height.

Summary

With Cloudflare Images or the adapter’s image service, you can:

  1. Improve performance via format/size/quality optimization.
  2. Simplify workflow—no manual image processing.
  3. Leverage CDN caching for optimized assets.

Choose the mode that fits your project to balance build time and runtime performance.***

搜索