Select Page

The following code creates a 480 X 320 px thumbnail and calls the upload function to upload the blob data.

Example Screenshots:

Extract PDF document thumbnail: JavaScript Function

function extractDocThumbnail() {
    const pdfUrl = document.getElementById('mediaURL').value;
    if (pdfUrl) {
        fetch(pdfUrl)
            .then(response => response.arrayBuffer())
            .then(data => {
                const pdfData = new Uint8Array(data);
                pdfjsLib.getDocument(pdfData).promise.then(function(pdf) {
                    // Render the first page of the PDF
                    pdf.getPage(1).then(function(page) {
                        const canvas = document.getElementById('canvasElement');
                        const ctx = canvas.getContext('2d');

                        // Calculate scale to make the PDF page width fit 480px
                        const desiredWidth = 480;
                        const viewport = page.getViewport({ scale: 1 });
                        const scale = desiredWidth / viewport.width;
                        const scaledViewport = page.getViewport({ scale: scale });

                        // Set canvas dimensions to the desired thumbnail size
                        canvas.width = 480;
                        canvas.height = 320;

                        // Create a temporary canvas for the full PDF page rendering
                        const tempCanvas = document.createElement('canvas');
                        tempCanvas.width = scaledViewport.width;
                        tempCanvas.height = scaledViewport.height;
                        const tempCtx = tempCanvas.getContext('2d');

                        // Render the PDF page onto the temporary canvas
                        const renderContext = {
                            canvasContext: tempCtx,
                            viewport: scaledViewport
                        };

                        page.render(renderContext).promise.then(function() {
                            // Crop the top portion of the rendered page to fit the thumbnail
                            ctx.drawImage(
                                tempCanvas,        // Source canvas
                                0, 0,              // Source x, y
                                480, 320,          // Source width, height
                                0, 0,              // Destination x, y
                                480, 320           // Destination width, height
                            );

                            // Convert the canvas to a base64 image
                            const dataUrl = canvas.toDataURL('image/jpeg');

                            // Upload the thumbnail to the server
                            uploadThumbnail(dataUrl);
                        });
                    });
                });
            })
            .catch(error => {
                console.error('Error fetching PDF:', error);
            });
    } else {
        console.error('PDF URL is missing.');
    }
}

Extract Video Thumbnail to certain seek time: JavaScript Function

function extractVideoThumbnail() {
  const videoElement = document.getElementById('videoPreview');
  const canvas = document.getElementById('canvasElement');
  const ctx = canvas.getContext('2d');

  // Load the video and wait until it's loaded
  videoElement.onloadedmetadata = function() {
    // Seek to 1 second
    videoElement.currentTime = 1;

    // Wait for the video to seek to that point
    videoElement.onseeked = function() {
      // Set canvas dimensions to match the video size
      canvas.width = videoElement.videoWidth;
      canvas.height = videoElement.videoHeight;

      // Draw the current video frame to the canvas
      ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height);

      // Convert the canvas image to a base64 data URL
      const dataUrl = canvas.toDataURL('image/jpeg');

      // Upload the thumbnail to the server
      uploadThumbnail(dataUrl);
    };
  };

  // Start loading the video metadata (this is important for seeking to a point)
  videoElement.load();
}

Upload Thumbnail: JavaScript Function

// Upload thumbnail image 
function uploadThumbnail(base64Image) {
    
    console.log( base64Image );
    document.getElementById('mediaThumbnailURL').value = 'this-is-new-thumbnail-url'; // set hidden input value of thumbnail
    
    const formData = new FormData();
    formData.append('thumbnail', base64Image);

    $.ajax({
      url: '<?=$data['baseurl'] ?>genthumbnail',  // Replace with your actual server URL
      type: 'POST',
      data: formData,
      cache: false, 
      dataType: 'json',
      processData: false,
      contentType: false,
      success: function (json) {
          // Assuming you want to update an input field with the file URL
          // You can adjust this part as needed
          var file_url = "<?=$data['baseurl'] ?>"+json.file;
          $('#mediaThumbnailURL').val(file_url); // Assuming 'json.file' contains the uploaded file URL
          console.log('Thumbnail uploaded successfully. URL:', json.file);
      },
      error: function (jqXHR, textStatus, errorThrown) {
          console.log('Error uploading thumbnail:', errorThrown);
      }
    });
}

PHP function to upload a thumbnail:

public function genthumbnail(){
  
    if (isset($_POST['thumbnail'])) {
        // Extract the base64 image data
        $imageData = $_POST['thumbnail'];
        // print_r($imageData);die();
        // Ensure the base64 string starts with 'data:image/jpeg;base64,' (for JPEG images)
        if (preg_match('/^data:image\/(jpeg|png|jpg);base64,/', $imageData)) {
            // Remove the 'data:image/jpeg;base64,' part of the data URL
            $filteredData = substr($imageData, strpos($imageData, ",") + 1);
            // Decode the base64 string
            $decodedData = base64_decode($filteredData);
            // Check for decoding errors
            if ($decodedData === false) {
                echo json_encode(['success' => false, 'message' => 'Failed to decode base64 image data.']);
                exit;
            }
            // Generate a unique filename
            $filePath = 'upload/' . uniqid('thumbnail_', true) . '.jpg';
            // Ensure the 'uploads' directory exists and is writable
            if (!is_dir('upload')) {
                mkdir('upload', 0755, true);
            }
            // Save the image to the server
            if (file_put_contents($filePath, $decodedData)) {
                // Respond with the file URL
                echo json_encode(['success' => true, 'file' => $filePath]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to save the file to the server.']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Invalid image data.']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'No thumbnail data received.']);
    }

  }