【问题标题】:Create an image from uploaded file从上传的文件创建图像
【发布时间】:2019-08-26 21:11:12
【问题描述】:

我正在像这样上传文件。 (我可以同时上传多个,输入会动态添加)

<form method="POST" action="ajax.php" enctype="multipart/form-data">
     <input type="file" name="uploadImage[]" id="file_input"> 
     <input type="file" name="uploadImage[]" id="file_input1"> 
     <input type="file" name="uploadImage[]" id="file_input2"> 
     <input type="submit" name="sendBtn" value="Click me">
</form> 

然后我提交到我的 ajax,我需要从上传的图像创建一个 thumbnail 并上传图像和缩略图。

这是我从$_FILES 获得的上传影片的结构。

Array
(
    [name] => array.png
    [type] => image/png
    [tmp_name] => /tmp/phpKw4V3s
    [error] => 0
    [size] => 53038
)

我如何在这种结构中使用像imagepng() 这样的函数?

我可以很容易地使用图像的完整路径来做到这一点,但我不能使用 php 的客户端路径。

【问题讨论】:

  • 为什么不做move_uploaded_file,然后做图片转换?
  • 如果这只是为了学习目的,我建议使用一些 jQuery 插件,例如 blueimp.github.io/jQuery-File-Upload
  • @zod 没想到。因此,为了能够使用该上传的文件,我需要将其移动到不同的地方(不是临时的),然后我可以获得完整路径?如果我将文件路径写入静态,它工作正常。我的问题是让它与 tmp_name 一起工作,而不是真正的完整路径。

标签: php image-upload


【解决方案1】:

我建议将现有库用于此类任务,例如 https://blueimp.github.io/jQuery-File-Upload/http://image.intervention.io/

但从头开始,您需要先创建一个图像资源:

$src = imagecreatefrompng($path_to_img);

如果你想为头像调整它的大小,你可以这样做:

  list($width, $height) = getimagesize($path_to_img);

  // COMPUTE NEW width and new height..
  // ..
  // creates black image of new size
  $final = imagecreatetruecolor($w, $h);

  // set background to white
  $white = imagecolorallocate($final, 255, 255, 255);
  imagefill($final, 0, 0, $white);

  // copys and resized original image ($width,$height) into new image ($newWidth,$newHeight)
  imagecopyresampled($final, $src, $dst_x, $dst_y, 0, 0, $newWidth, $newHeight, $width, $height);

将其保存到文件或输出将使用

 imagepng($src, $path_to_new_file);

【讨论】:

  • 谢谢。我已经在做。我只是不能让它与那个结构一起工作。例如使用$file['tmp_name'] 而不是完整路径。
  • @PlayHardGoPro 所以imagecreatefrompng($file['tmp_name']) 不起作用?
  • @PlayHardGoPro imagepng 确实需要图像源,而不是路径 $file['tmp_name']。您需要将$file['tmp_name'] 转换为带有imagecreatefrompng 的图像源,这是imagepng 的第一个参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-14
  • 2013-11-17
  • 1970-01-01
相关资源
最近更新 更多