Sobes.tech
Junior

How can images be obtained from a server?

sobes.tech AI

Answer from AI

There are several main ways to obtain images from the server in the Frontend:

  1. <img> tag: The simplest and most common method. Uses the src attribute to specify the image URL.

    <img src="/images/logo.png" alt="Company Logo">
    
  2. CSS property background-image: Used to place an image as the background of an element.

    .hero-section {
      background-image: url('/images/hero.jpg');
      background-size: cover;
    }
    
  3. AJAX (XMLHttpRequest or Fetch API): Allows asynchronous fetching of images, often for dynamic content updates or image data manipulation (e.g., creating previews or client-side processing). The fetched data can be in various formats (e.g., Base64).

    fetch('/api/image/123')
      .then(response => response.blob()) // Get data as Blob
      .then(blob => {
        const imageUrl = URL.createObjectURL(blob); // Create URL for Blob
        const img = document.createElement('img');
        img.src = imageUrl;
        document.body.appendChild(img);
      })
      .catch(error => console.error('Error loading image:', error));
    

    Getting image in base64 format:

    fetch('/api/image/base64/123')
      .then(response => response.text()) // Get data as text (Base64 string)
      .then(base64String => {
        const img = document.createElement('img');
        img.src = 'data:image/png;base64,' + base64String; // For PNG
        document.body.appendChild(img);
      })
      .catch(error => console.error('Error loading image:', error));
    
  4. WebSockets: For real-time image reception, e.g., in streaming applications or games. Images can be transmitted as binary data.

    const socket = new WebSocket('ws://localhost:8080');
    
    socket.onmessage = (event) => {
      if (event.data instanceof Blob) {
        const img = document.createElement('img');
        img.src = URL.createObjectURL(event.data);
        document.body.appendChild(img);
      }
    };
    
  5. <canvas> with drawImage: Images can be loaded via AJAX or <img> and then drawn onto a <canvas> element.

    const canvas = document.getElementById('myCanvas');
    const ctx = canvas.getContext('2d');
    const img = new Image();
    
    img.onload = () => {
      ctx.drawImage(img, 0, 0);
    };
    
    img.src = '/images/image_for_canvas.png';
    
  6. Streaming (using ReadableStream): For processing large images or transmitting images in parts.

    fetch('/large-image-stream')
      .then(response => response.body)
      .then(reader => {
        // Read and process the image data stream
        // For example, use TextDecoder for text or process ArrayBuffer for binary data
      })
      .catch(error => console.error('Streaming error:', error));
    

The choice of method depends on the specific task, performance requirements, need for asynchronous loading, and the type of image data.