【问题标题】:Problem when uploading and saving image in database在数据库中上传和保存图像时出现问题
【发布时间】:2022-01-14 18:09:50
【问题描述】:

大家好,女士们,

我正在尝试上传图像并将其保存在数据库中。我的代码正在运行,但是当我对其进行测试时,图像将在三四次后部分保存,如下所示:

在我的代码中,我最多可以保存 12 张图片(如果已上传)。我正在测试 4 张图片。 我究竟做错了什么?是内存问题吗?如果是……是什么原因造成的? 谢谢你的帮助。

我的代码是:

//save up to 12 images in database
for($i=1;$i<=12;$i++){
  $fileName = $_FILES['image'.$i]['name'];
    if ($fileName){
      try{
        list($origWidth, $origHeight, $type) = getimagesize($_FILES['image'.$i]['tmp_name']);
          $temp_name = "tempupload/".$fileName;
          //make thumbnail to save in database
          //resize the image to 200px and save as/in $temp_name (see resizeImage function)
          resizeImage($_FILES['foto'.$i]['tmp_name'], $temp_name, 200, 200);
          //retrieve saved image to put a watermark on it
          switch(strtolower(image_type_to_mime_type($type)))
          {
            case 'image/jpeg':                      
              $im2 = @imagecreatefromjpeg($temp_name);      
              break;
            case 'image/png':                      
              $im2 = @imagecreatefrompng($temp_name);  
              break;
            }   
            //put watermark
            $watermark = imagecreatefrompng('../assets/images/logo/watermark.png');
            $marge_right = 10;
            $marge_bottom = 10;
            $sx = imagesx($watermark);
            $sy = imagesy($watermark);
            imagecopy($im2, $watermark, imagesx($im2) - $sx - $marge_right, imagesy($im2) - $sy - $marge_bottom, 0, 0, imagesx($watermark), imagesy($watermark));
            //save image with watermark     
            switch(strtolower(image_type_to_mime_type($type)))
            {
              case 'image/jpeg':                      
                imagejpeg($im2, $temp_name);   
                break;
              case 'image/png':                      
                imagepng($im2, $temp_name);  
                break;
            }
            //open saved temp image
            $saved_temp = fopen($temp_name,"rb");
            //addslashes to image to save in database as BLOB
            $image = addslashes(fread($saved_temp ,filesize($temp_name)));
            fclose($saved_temp );
            //End thumbnail
                    
            //Next part is to save the image in database in 1200px if user want this.
            //this is used so that the user can download and use the image afterwards   
            $downloadimage="";
            if(($_POST['image'.$i.'_Save']!="no") && ($_SESSION['package']!="A")){
              //if width or height are smaller 700 us original width or height
              $w = ($origWidth > 1200)?1200:$origWidth;
              $h = ($origHeight > 1200)?1200:$origHeight;
              if(($origWidth > 1200) || ($origHeight > 1200)){
                //use same $temp_name to save memory????
                resizeImage($_FILES['image'.$i]['tmp_name'], $temp_name, $w, $h,100);
              }else{
                //if image is to small, then move and save as $temp_name
                move_uploaded_file($_FILES['image'.$i]["tmp_name"],$temp_name);
              } 
              //put watermark
              if(($_SESSION['package']=="B")){
                // Get dimensions and type of $temp_name.
                list($origWidth, $origHeight, $type) = getimagesize($temp_name);
                    
                switch(strtolower(image_type_to_mime_type($type)))
                {
                  case 'image/jpeg':                      
                    $im2 = @imagecreatefromjpeg($temp_name);      
                    break;
                  case 'image/png':                      
                    $im2 = @imagecreatefrompng($temp_name);  
                    break;
                }
                imagecopy($im2, $watermark, imagesx($im2) - $sx - $marge_right, imagesy($im2) - $sy - $marge_bottom, 0, 0, imagesx($watermark), imagesy($watermark));
                switch(strtolower(image_type_to_mime_type($type)))
                {
                  case 'image/jpeg':                      
                    imagejpeg($im2, $temp_name);   
                    break;
                  case 'image/png':                      
                    imagepng($im2, $temp_name);  
                    break;
                }
            }
            $saved_temp = fopen($temp_name,"rb");
            $downloadimage = addslashes(fread($saved_temp ,filesize($temp_name)));
            fclose($saved_temp );
        }
        //End making downloadimage
        //SQL to save images in database            
        if(empty($downloadimage)){
            $sql = "INSERT INTO tb_images(image,strange_id) VALUES (:image,:strange_id)";
                        $st = $conn->prepare($sql);
                    }else{
                        $sql = "INSERT INTO tb_images(image,strange_id,downloadimage,type) VALUES (:image,:strange_id,:downloadimage,:type)";
                        $st = $conn->prepare($sql); 
                        $st->bindValue( ":downloadimage", $downloadimage, PDO::PARAM_LOB );
                        $st->bindValue( ":type", strtolower(image_type_to_mime_type($type)), PDO::PARAM_STR );
                    }
                    $st->bindValue( ":image", $image, PDO::PARAM_LOB );
                    $st->bindValue( ":strange_id", $strange_id, PDO::PARAM_INT );
                    
                    $st->execute();
                    
                    imagedestroy($watermark);
                    unlink($temp_name);
                    imagedestroy($im2);
                }
    catch (\Exception $e){
        echo e;
    }
  }
}

调整大小功能

/**
     * Resize image - preserve ratio of width and height.
     * @param string $sourceImage path to source JPEG/PNG image
     * @param string $targetImage path to final JPEG/PNG image file
     * @param int $maxWidth maximum width of final image (value 0 - width is optional)
     * @param int $maxHeight maximum height of final image (value 0 - height is optional)
     * @param int $quality quality of final image (0-100)
     * @return bool
     */
    function resizeImage($sourceImage, $targetImage, $maxWidth, $maxHeight, $quality = 80)
    {
    $isValid = @getimagesize($sourceImage);

    if (!$isValid)
    {
        return false;
    }

    // Get dimensions and type of source image.
    list($origWidth, $origHeight, $type) = getimagesize($sourceImage);

    if ($maxWidth == 0)
    {
        $maxWidth  = $origWidth;
    }

    if ($maxHeight == 0)
    {
        $maxHeight = $origHeight;
    }

    // Calculate ratio of desired maximum sizes and original sizes.
    $widthRatio = $maxWidth / $origWidth;
    $heightRatio = $maxHeight / $origHeight;

    // Ratio used for calculating new image dimensions.
    $ratio = min($widthRatio, $heightRatio);

    // Calculate new image dimensions.
    $newWidth  = (int)$origWidth  * $ratio;
    $newHeight = (int)$origHeight * $ratio;

    // Create final image with new dimensions.
    $newImage = imagecreatetruecolor($newWidth, $newHeight);

    // Obtain image from given source file.
    switch(strtolower(image_type_to_mime_type($type)))
    {
        case 'image/jpeg':                      
            $image = @imagecreatefromjpeg($sourceImage);            
            if (!$image)
            {
                return false;
            }

            imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight); 

            if(imagejpeg($newImage,$targetImage,$quality))
            {
                // Free up the memory.
                imagedestroy($image);
                imagedestroy($newImage);
                return true;
            }            
        break;
        
        case 'image/png':
            $image = @imagecreatefrompng($sourceImage);

            if (!$image)
            {
                return false;
            }

            imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight);

            if(imagepng($newImage,$targetImage, floor($quality / 10)))
            {
                // Free up the memory.
                imagedestroy($image);
                imagedestroy($newImage);
                return true;
            }
        break;
                
                default:
                return false;
    }
    }

【问题讨论】:

  • 跳过所有调整大小和水印的东西,只做上传、数据库和查看。测试一堆。如果它总是有效,请添加调整大小并再次测试一堆。如果可行,请重新添加水印并重复。另外,删除@ 错误抑制

标签: php image memory upload resize


【解决方案1】:

好的...经过多次测试...这是我自己的问题的解决方案:)

首先是这一行...

resizeImage($_FILES['image'.$i]['tmp_name'], $temp_name, $w, $h,100);

为 PNG 设置 100% 质量是个问题。我不知道为什么,但我所做的只是替换这个: imagepng($newImage,$targetImage, floor($quality / 10)) 和: imagepng($newImage,$targetImage) 我也为 JPEG 做到了这一点。

那么第二个问题是在我的数据库中。 BLOB 必须是 LONG BLOB。

但现在我不再将图像存储在数据库中。我将它们保存在一个文件夹中。不是因为 LONG BLOB 问题,而是因为它更快,工作量更少。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-03
    • 2013-06-12
    • 2019-03-14
    • 2019-05-26
    • 2017-02-15
    • 1970-01-01
    • 2014-08-09
    • 2016-02-01
    相关资源
    最近更新 更多