Image Handling with Cloudflare Images

Image Handling with Cloudflare Images

This guide covers image handling in the AutoElite API, which uses Cloudflare Images for storage, optimization, and delivery.

Overview

AutoElite uses Cloudflare Images to store and serve vehicle images. This service provides:

  • Optimized image delivery
  • Automatic resizing and format conversion
  • Global CDN distribution
  • Secure, authenticated access

Image URL Structure

All images in AutoElite are served through Cloudflare's imagedelivery.net domain with the following URL structure:

https://imagedelivery.net/fxSXhaLsNKtcGJIGPzWBwA/{image_id}/{variant}

Where:

  • fxSXhaLsNKtcGJIGPzWBwA is the AutoElite account hash
  • {image_id} is the unique identifier for the image
  • {variant} is the delivery variant (e.g., "public", "thumbnail")

Accessing Vehicle Images

To retrieve images for a specific vehicle, use the vehicles endpoint:

Using cURL

curl -X GET "https://api.autoelite.io/api/vehicles/{vehicle_id}/images" \
  -H "X-API-Key: your-api-key-here" \
  -H "Content-Type: application/json"

Using JavaScript/Fetch

fetch(`https://api.autoelite.io/api/vehicles/${vehicleId}/images`, {
  headers: {
    'X-API-Key': 'your-api-key-here',
    'Content-Type': 'application/json'
  }
})
.then(response => response.json())
.then(data => {
  // Process the images
  const images = data;
  console.log('Vehicle images:', images);
});

Response Format

[
  {
    "id": 1,
    "vehicle_id": 123,
    "image_url": "https://imagedelivery.net/fxSXhaLsNKtcGJIGPzWBwA/abc123def/public",
    "cloudflare_id": "abc123def",
    "is_primary": true,
    "display_order": 0,
    "created_at": "2025-01-15T14:22:33Z"
  },
  {
    "id": 2,
    "vehicle_id": 123,
    "image_url": "https://imagedelivery.net/fxSXhaLsNKtcGJIGPzWBwA/xyz789uvw/public",
    "cloudflare_id": "xyz789uvw",
    "is_primary": false,
    "display_order": 1,
    "created_at": "2025-01-15T14:22:45Z"
  }
]

Image Variants

Cloudflare Images provides different variants for each image. The AutoElite API uses the following variants:

Variant Description Use Case
public Full-size optimized image Default display
thumbnail Small thumbnail (200px width) Listings and thumbnails
medium Medium-sized image (800px width) Gallery views
large Large image (1200px width) Detail views

To request a specific variant, append it to the image URL:

https://imagedelivery.net/fxSXhaLsNKtcGJIGPzWBwA/{image_id}/thumbnail

Image Optimization

When displaying images in your application, you can take advantage of Cloudflare's built-in optimization features:

Responsive Images

Use the srcset attribute to provide multiple image sizes:

<img 
  src="https://imagedelivery.net/fxSXhaLsNKtcGJIGPzWBwA/{image_id}/medium" 
  srcset="
    https://imagedelivery.net/fxSXhaLsNKtcGJIGPzWBwA/{image_id}/thumbnail 200w,
    https://imagedelivery.net/fxSXhaLsNKtcGJIGPzWBwA/{image_id}/medium 800w,
    https://imagedelivery.net/fxSXhaLsNKtcGJIGPzWBwA/{image_id}/large 1200w
  "
  sizes="(max-width: 600px) 200px, (max-width: 1200px) 800px, 1200px"
  alt="Vehicle image"
/>

Lazy Loading

Implement lazy loading to improve page performance:

<img 
  src="https://imagedelivery.net/fxSXhaLsNKtcGJIGPzWBwA/{image_id}/thumbnail" 
  data-src="https://imagedelivery.net/fxSXhaLsNKtcGJIGPzWBwA/{image_id}/medium"
  loading="lazy"
  alt="Vehicle image"
/>

Best Practices

  1. Always use HTTPS for image URLs
  2. Implement responsive images using the appropriate variants
  3. Cache images in your application when appropriate
  4. Use lazy loading for images below the fold
  5. Include proper alt text for accessibility

Example Implementation

Here's a complete example of displaying vehicle images in a React component:

import React from 'react';

const VehicleGallery = ({ vehicleId }) => {
  const [images, setImages] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    const fetchImages = async () => {
      try {
        const response = await fetch(
          `https://api.autoelite.io/api/vehicles/${vehicleId}/images`,
          {
            headers: {
              'X-API-Key': 'your-api-key-here',
              'Content-Type': 'application/json'
            }
          }
        );
        
        if (!response.ok) {
          throw new Error(`Error fetching images: ${response.status}`);
        }
        
        const data = await response.json();
        setImages(data);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };
    
    fetchImages();
  }, [vehicleId]);
  
  if (loading) return <div>Loading images...</div>;
  if (error) return <div>Error: {error}</div>;
  if (images.length === 0) return <div>No images available</div>;
  
  // Find the primary image
  const primaryImage = images.find(img => img.is_primary) || images[0];
  
  return (
    <div className="vehicle-gallery">
      <div className="primary-image">
        <img 
          src={primaryImage.image_url}
          alt="Primary vehicle image"
          className="main-image"
        />
      </div>
      
      <div className="thumbnails">
        {images.map(image => (
          <div 
            key={image.id} 
            className={`thumbnail ${image.is_primary ? 'active' : ''}`}
          >
            <img 
              src={image.image_url.replace('/public', '/thumbnail')}
              alt={`Vehicle thumbnail ${image.display_order + 1}`}
              loading="lazy"
            />
          </div>
        ))}
      </div>
    </div>
  );
};

export default VehicleGallery;