Просмотр исходного кода

fixing image upload and thumnail greation

svalavuo 1 месяц назад
Родитель
Сommit
5be8840845
2 измененных файлов с 142 добавлено и 7 удалено
  1. 79 0
      admin/fix_thumbnails.php
  2. 63 7
      admin/upload_image.php

+ 79 - 0
admin/fix_thumbnails.php

@@ -0,0 +1,79 @@
+<?php
+/**
+ * Fix broken thumbnails in database
+ * This script removes thumbnail_filename for images that don't have actual thumbnail files
+ */
+
+require_once '../includes/config.php';
+require_once '../includes/database.php';
+
+// Create uploads directory if it doesn't exist
+$thumbsDir = '../uploads/images/thumbs';
+if (!file_exists($thumbsDir)) {
+    mkdir($thumbsDir, 0755, true);
+}
+
+$db = Database::getInstance();
+
+echo "<h1>Fixing Broken Thumbnails</h1>\n";
+
+// Get all images with thumbnail filenames
+$images = $db->fetchAll("SELECT id, filename, thumbnail_filename FROM images WHERE thumbnail_filename IS NOT NULL AND thumbnail_filename != ''");
+
+echo "<p>Found " . count($images) . " images with thumbnail filenames</p>\n";
+
+$fixed = 0;
+$removed = 0;
+
+foreach ($images as $image) {
+    $thumbPath = $thumbsDir . '/' . $image['thumbnail_filename'];
+    
+    if (!file_exists($thumbPath)) {
+        echo "<p>Thumbnail file missing for image ID {$image['id']}: {$image['thumbnail_filename']}</p>\n";
+        
+        // Remove thumbnail filename from database (fallback to original)
+        $db->update('images', ['thumbnail_filename' => null], 'id = ?', [$image['id']]);
+        echo "<p style='color: orange;'>✓ Removed thumbnail filename for image ID {$image['id']}</p>\n";
+        $removed++;
+    } else {
+        echo "<p style='color: green;'>✓ Thumbnail exists for image ID {$image['id']}</p>\n";
+        $fixed++;
+    }
+}
+
+echo "<h2>Summary</h2>\n";
+echo "<p>Images with valid thumbnails: {$fixed}</p>\n";
+echo "<p>Broken thumbnail entries removed: {$removed}</p>\n";
+
+// Test thumbnail generation on a sample image
+$testImages = $db->fetchAll("SELECT id, filename FROM images WHERE thumbnail_filename IS NULL LIMIT 3");
+
+if (!empty($testImages)) {
+    echo "<h2>Testing Thumbnail Generation</h2>\n";
+    
+    foreach ($testImages as $image) {
+        $sourcePath = '../uploads/images/' . $image['filename'];
+        $thumbFilename = 'thumb_' . $image['filename'];
+        $thumbPath = $thumbsDir . '/' . $thumbFilename;
+        
+        if (file_exists($sourcePath)) {
+            echo "<p>Testing thumbnail generation for: {$image['filename']}</p>\n";
+            
+            // Include the thumbnail generation function
+            require_once 'upload_image.php';
+            
+            if (generateThumbnail($sourcePath, $thumbPath)) {
+                // Update database with new thumbnail filename
+                $db->update('images', ['thumbnail_filename' => $thumbFilename], 'id = ?', [$image['id']]);
+                echo "<p style='color: green;'>✓ Successfully generated thumbnail for image ID {$image['id']}</p>\n";
+            } else {
+                echo "<p style='color: red;'>✗ Failed to generate thumbnail for image ID {$image['id']}</p>\n";
+            }
+        } else {
+            echo "<p style='color: red;'>✗ Source file not found: {$image['filename']}</p>\n";
+        }
+    }
+}
+
+echo "<p><a href='edit.php'>← Back to Editor</a></p>\n";
+?>

+ 63 - 7
admin/upload_image.php

@@ -61,8 +61,22 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['images'])) {
                 
                 // Move file to uploads directory
                 if (move_uploaded_file($file['tmp_name'], $filepath)) {
-                    // Generate thumbnail
-                    $thumbnailGenerated = generateThumbnail($filepath, $thumbPath);
+                    // Generate thumbnail with fallback
+                    $thumbFilename = null;
+                    $thumbnailUrl = '/uploads/images/' . $filename; // Fallback to original
+                    
+                    // Try to generate thumbnail
+                    $thumbFilenameTemp = 'thumb_' . $filename;
+                    $thumbPathTemp = $thumbsDir . '/' . $thumbFilenameTemp;
+                    
+                    if (generateThumbnail($filepath, $thumbPathTemp)) {
+                        // Thumbnail generation successful
+                        $thumbFilename = $thumbFilenameTemp;
+                        $thumbnailUrl = '/uploads/images/thumbs/' . $thumbFilenameTemp;
+                    } else {
+                        // Thumbnail generation failed, log error but continue
+                        error_log('Thumbnail generation failed for ' . $file['name'] . ', using original image as fallback');
+                    }
                     
                     // Save to database
                     $imageId = saveImageToDatabase($filename, $file['name'], $file['size'], $thumbFilename);
@@ -74,13 +88,13 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['images'])) {
                             'original_name' => $file['name'],
                             'size' => $file['size'],
                             'url' => '/uploads/images/' . $filename,
-                            'thumbnail_url' => '/uploads/images/thumbs/' . $thumbFilename
+                            'thumbnail_url' => $thumbnailUrl
                         ];
                     } else {
                         $errors[] = 'Failed to save ' . $file['name'] . ' to database';
                         unlink($filepath); // Remove uploaded file
-                        if ($thumbnailGenerated) {
-                            unlink($thumbPath); // Remove thumbnail if generated
+                        if ($thumbFilename && file_exists($thumbPathTemp)) {
+                            unlink($thumbPathTemp); // Remove thumbnail if generated
                         }
                     }
                 } else {
@@ -160,10 +174,17 @@ function generateThumbnail($sourcePath, $destPath, $maxWidth = 300, $maxHeight =
         return false;
     }
     
+    // Check if source file exists and is readable
+    if (!file_exists($sourcePath) || !is_readable($sourcePath)) {
+        error_log('Source file not found or not readable: ' . $sourcePath);
+        return false;
+    }
+    
     try {
         // Get image info
         $imageInfo = getimagesize($sourcePath);
         if (!$imageInfo) {
+            error_log('Unable to get image info for: ' . $sourcePath);
             return false;
         }
         
@@ -171,12 +192,17 @@ function generateThumbnail($sourcePath, $destPath, $maxWidth = 300, $maxHeight =
         $height = $imageInfo[1];
         $type = $imageInfo[2];
         
+        error_log("Processing image: {$sourcePath} - Size: {$width}x{$height}, Type: {$type}");
+        
         // Calculate new dimensions
         $ratio = min($maxWidth / $width, $maxHeight / $height);
         $newWidth = (int)($width * $ratio);
         $newHeight = (int)($height * $ratio);
         
+        error_log("New thumbnail size: {$newWidth}x{$newHeight}");
+        
         // Create image resource based on type
+        $source = null;
         switch ($type) {
             case IMAGETYPE_JPEG:
                 $source = imagecreatefromjpeg($sourcePath);
@@ -188,15 +214,22 @@ function generateThumbnail($sourcePath, $destPath, $maxWidth = 300, $maxHeight =
                 $source = imagecreatefromgif($sourcePath);
                 break;
             default:
+                error_log("Unsupported image type: {$type}");
                 return false;
         }
         
         if (!$source) {
+            error_log('Failed to create image resource from: ' . $sourcePath);
             return false;
         }
         
         // Create new image
         $thumb = imagecreatetruecolor($newWidth, $newHeight);
+        if (!$thumb) {
+            error_log('Failed to create true color image for thumbnail');
+            imagedestroy($source);
+            return false;
+        }
         
         // Preserve transparency for PNG and GIF
         if ($type == IMAGETYPE_PNG || $type == IMAGETYPE_GIF) {
@@ -207,7 +240,24 @@ function generateThumbnail($sourcePath, $destPath, $maxWidth = 300, $maxHeight =
         }
         
         // Resize image
-        imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
+        $resizeResult = imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
+        if (!$resizeResult) {
+            error_log('Failed to resize image');
+            imagedestroy($source);
+            imagedestroy($thumb);
+            return false;
+        }
+        
+        // Ensure destination directory exists
+        $destDir = dirname($destPath);
+        if (!is_dir($destDir)) {
+            if (!mkdir($destDir, 0755, true)) {
+                error_log('Failed to create thumbnail directory: ' . $destDir);
+                imagedestroy($source);
+                imagedestroy($thumb);
+                return false;
+            }
+        }
         
         // Save thumbnail
         $result = false;
@@ -227,7 +277,13 @@ function generateThumbnail($sourcePath, $destPath, $maxWidth = 300, $maxHeight =
         imagedestroy($source);
         imagedestroy($thumb);
         
-        return $result;
+        if ($result && file_exists($destPath)) {
+            error_log('Thumbnail successfully created: ' . $destPath);
+            return true;
+        } else {
+            error_log('Failed to save thumbnail: ' . $destPath);
+            return false;
+        }
         
     } catch (Exception $e) {
         error_log('Error generating thumbnail: ' . $e->getMessage());