上传最常见的图像类型并将其转换为 png 以获得织物画布背景图像


Upload and convert most common image types to png for fabric canvas background image

我正在尝试让此图像上传和转换脚本正常工作。我让脚本上传任何有效的图像并重命名它们,但后来我添加了转换代码,但我无法让它正常工作。我注释掉了//imagepng($image);因为这导致成功div 填充 PNG IHDR G, } IDATx i u' s ] %.......我已经为此工作了两天,查看了Stack上的很多帖子,并认为我了解需要什么。如果有人可以看看这个,也许能对我的问题有所了解,我将不胜感激。在当前配置中,我在服务器上没有收到任何错误。谢谢!

.PHP

 <?php
    include_once $_SERVER['DOCUMENT_ROOT'].'/include/session.php';
     // Detect the file params according to need
 $filename = $_FILES["myfile"]["name"];
 $filesize = $_FILES["myfile"]["size"];
 $tmp_name = $_FILES["myfile"]["tmp_name"];
 $custnum = $session->custnum; //Users account number from session
// Valid extensions for Upload
    $validExtensions = array('.jpeg', '.jpg', '.gif', '.png');
// Valid size in KB
  $max_size = 6000;
  // Detect file extension
    $extension = strtolower(strrchr($filename, "."));
      // Convert filesize in KB
       $getFileSize = round($filesize / 1024, 1);
         //Make the storage directory
           if (!file_exists("maps/accounts/".$custnum)) {
          mkdir("maps/accounts/".$custnum, 0777, true);
           }
            // Location to store the file
         $path = str_replace(''/''', '/', dirname(__FILE__)) . "/maps/accounts/".$custnum;
if( in_array($extension, $validExtensions) ){
 if( $getFileSize < $max_size ){
     if(is_dir($path)){
        //***********Start of image conversion***********
         $srcFile = $tmp_name;
list($width_orig, $height_orig, $type) = getimagesize($srcFile);        
// Get the aspect ratio
$ratio_orig = $width_orig / $height_orig;
//Set max size
$width  = 900; 
$height = 600;
// resize to height (orig is portrait) 
if ($ratio_orig < 1) {
    $width = $height * $ratio_orig;
} 
// resize to width (orig is landscape)
else {
    $height = $width / $ratio_orig;
}
// Temporarily increase the memory limit to allow for larger images
ini_set('memory_limit', '32M'); 
switch ($type) 
{
    case IMAGETYPE_GIF: 
        $image = imagecreatefromgif($srcFile); 
        break;   
    case IMAGETYPE_JPEG:  
        $image = imagecreatefromjpeg($srcFile); 
        break;   
    case IMAGETYPE_PNG:  
        $image = imagecreatefrompng($srcFile);
        break; 
    default:
        throw new Exception('Unrecognized image type ' . $type);
}
         // create a new blank image
   $newImage = imagecreatetruecolor($width, $height);
       // Copy the old image to the new image
   imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);  
      imagepng($newImage, $path . '/' . $custnum.'.png');
      imagedestroy($image);
      imagedestroy($newImage);      
        //******End of image conversion****************     

                // Success Message
           echo "<div id='success' class='alert alert-success'><strong>Your map image was uploaded!</strong>
                    <button type='"button'" class='"close'" data-dismiss='"alert'">&times;</button>
                 </div>";

     } else {
                  trigger_errors("Directory not Found!<br /> $path");
                  }
      } else {
      $error_msg = "<strong>Filesize should be less then $max_size KB!</strong><br />Your file is about $getFileSize KB";
     trigger_errors($error_msg);
  }
    } else {
         $error_msg = "<strong>File not Supproted for Upload!</strong><br />
                Please try with the files that has following extensions: .jpg, .jpeg, .gif, .png";
      trigger_errors($error_msg);
      }
   // Make function that
  // generate the Error
  function trigger_errors( $error_msg ){
   echo "<div class='alert alert-error'>
     <button type='"button'" class='"close'" data-dismiss='"alert'">&times;</button>
     $error_msg
     </div>";
   }
   ?>

这是我的JQuery Ajax脚本,它位于织物.js厨房水槽旁边.js它调用了上面的php脚本。

JQuery Ajax

$('#loading').hide();
$(function(){
var $form = $('#myform'),
    $result = $('#result');
$('form').on('change','#myfile', function(){
    $('#loading').show();
    $result.ajaxStart(function(){
    }); 
    $form.ajaxForm({
        target: $result
    }).submit();
          $( document ).ajaxComplete(function() {
               $('#loading').delay(1500).hide('slow');
            if ($('#success').hasClass('alert-success')){    
               canvas.setBackgroundImage(fullurl  , function() {
               canvas.renderAll();
                 });};
          });
});            
})

这是我当前的 html,它调用 Ajax 和 php 图像处理器。此 html 接收来自 php 和 ajax 的反馈,成功或失败以向用户提供反馈。

.HTML

<div>
  <form id="myform" action="image_uploader.php" method="post" enctype="multipart/form-data">
      <table align="center">
          <tr>
              <td width="100"><label>Select File: </label></td>
             <td>
                  <input class="btn shape" type="file" id="myfile" name="myfile">
              </td>
          </tr>
      </table>
  </form>
<div id="loading"><img src="fabric/img/loadingbar.gif" width="200" height="15" alt="" border="0"><img src="fabric/img/uploading-text.GIF" width="128" height="19" alt="" border="0"></div>
</div>
<div id="result"></div>

实际上你不需要调用move_uploaded_file。事实上,如果你这样做,你就不会得到你想要的结果。

// create a new blank image
$newImage = imagecreatetruecolor($width, $height);
// Copy the old image to the new image
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);  
imagepng($newImage, $path . '/' . $custnum);
imagedestroy($image);
imagedestroy($newImage);

您要这样做的原因是 imagepng 的第二个参数可以是保存文件的路径。由于您已经解决了转换文件的所有麻烦,因此调用move_uploaded_file会将原始文件移动到 png 文件名中。因此,如果我使用您的脚本上传 JPEG,它会将该 JPEG 移动到示例中.png。换句话说,它不会是PNG,它仍然是JPEG。

它转储你编写方式的原因是,如果没有该路径,该函数将返回原始图像,因此您的浏览器试图将该二进制数据解释为文本,因此,你会得到乱码和随机字符。

您只是在移动上传的文件。

所以。。删除此行。.

header('Content-Type: image/png');