【问题标题】:Not able to save uploaded PNG file无法保存上传的 PNG 文件
【发布时间】:2012-02-24 13:21:17
【问题描述】:

我可以上传 JPG 文件,但不能上传 PNG 文件。
PNG图像未保存,但输出此‰PNG À À°£ûïS JÄž Ÿ¬™Ù<íû;

我的代码是这样的:

  $source_gd_image = imagecreatefrompng( $sourcefile ); // <-- If PNG file
  $target_gd_image = imagecreatetruecolor( $target_image_width, $target_image_height );

  if($source_image_type == IMAGETYPE_PNG) {
    imagealphablending($target_gd_image, true); // Should this be false?
    imagesavealpha($target_gd_image, true); 
    imagepng($target_gd_image); // <-- This is where the gibberish is outputed
  }

  if($source_image_type == IMAGETYPE_JPEG) {
    imagecopyresampled( $target_gd_image, $source_gd_image, 0, 0, 0, 0, $target_image_width, $target_image_height, $source_image_width, $source_image_height );
    imagejpeg( $target_gd_image, $target_file, $quality );
  }

  imagedestroy( $source_gd_image );
  imagedestroy( $target_gd_image );

我做错了什么?

【问题讨论】:

  • 尝试在输出前添加header('Content-type: image/png');

标签: php upload png


【解决方案1】:

就像imagejpeg一样,如果要将其保存到文件中,则必须指定a file name as the second parameter,否则它只会输出到浏览器。

假设 $target_file 是所需的输出文件名,这意味着使用:

imagepng($target_gd_image, $target_file);

【讨论】:

  • 啊!我总是看不懂DOC bool imagepng ( resource $image [, string $filename [, int $quality [, int $filters ]]] )——不过既然你这么说,我也可以在$target_file之后加质量。
  • @Steven:确实,方括号表示可选元素——如果你想放 $quality,你还必须为 $filename 放一些东西。这种表示法在语言文档中很常见,因此了解它很有用。另请注意,由于 PNG 是无损的,因此“质量”确实是用词不当;它设置压缩级别,但这只会影响文件大小,而不影响实际的图像数据。
  • 背景仍然是黑色的。我尝试将 imagealphablending 设置为 true 和 false,但我得到了相同的结果。
  • @Steven:您永远不会将图像数据复制到目标图像。你也需要在这里使用imagecopyresampled
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-07
  • 2016-04-22
  • 2012-07-08
  • 1970-01-01
  • 1970-01-01
  • 2011-08-26
  • 1970-01-01
相关资源
最近更新 更多