Site icon Puneet Sharma – Freelance Web Developer

Create Thumbnail of pdf and video file with certain width and height – JavaScript Function

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) {
        console.error('PDF URL is missing.');
        return;
    }

    // Fetch the PDF with CORS handling
    fetch(pdfUrl, { mode: 'cors', credentials: 'omit' })
        .then(response => {
            if (!response.ok) {
                throw new Error(`Failed to fetch PDF: ${response.statusText}`);
            }
            return response.arrayBuffer();
        })
        .then(data => {
            const pdfData = new Uint8Array(data);
            pdfjsLib.getDocument({ data: pdfData }).promise.then(pdf => {
                pdf.getPage(1).then(page => {
                    const canvas = document.getElementById('canvasElement');
                    const ctx = canvas.getContext('2d', { willReadFrequently: true });

                    const desiredWidth = 480;
                    const viewport = page.getViewport({ scale: 1 });
                    const scale = desiredWidth / viewport.width;
                    const scaledViewport = page.getViewport({ scale });

                    canvas.width = 480;
                    canvas.height = 320;

                    const tempCanvas = document.createElement('canvas');
                    tempCanvas.width = scaledViewport.width;
                    tempCanvas.height = scaledViewport.height;
                    const tempCtx = tempCanvas.getContext('2d');

                    const renderContext = {
                        canvasContext: tempCtx,
                        viewport: scaledViewport
                    };

                    page.render(renderContext).promise.then(() => {
                        try {
                            ctx.drawImage(tempCanvas, 0, 0, 480, 320, 0, 0, 480, 320);

                            const dataUrl = canvas.toDataURL('image/jpeg');

                            uploadThumbnail(dataUrl);
                        } catch (error) {
                            console.error("Error processing thumbnail:", error);
                        }
                    });
                });
            });
        })
        .catch(error => {
            console.error('Error fetching or rendering PDF:', error);
        });
}

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');

    // Ensure CORS is handled
    videoElement.crossOrigin = "anonymous";

    videoElement.onloadedmetadata = function () {
        // Seek to 1 second
        videoElement.currentTime = 1;
    };

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

        try {
            // 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);
        } catch (error) {
            console.error("Error extracting thumbnail:", error);
        }
    };

    // Load the video metadata
    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.']);
    }

  }
Exit mobile version