如何将上传的图像转换为JPG格式?

时间:2013-01-27 17:54:25

标签: php

我只需上传:

$ path =“uploads /”;

$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
move_uploaded_file($tmp, $path.$actual_image_name);

我如何添加此功能imagejpeg?我希望始终以JPG格式保存图像。

2 个答案:

答案 0 :(得分:13)

试试这个:

<?php

$path = "uploads/";

$img = $_FILES['photoimg']['tmp_name'];
$dst = $path . $_FILES['photoimg']['name'];

if (($img_info = getimagesize($img)) === FALSE)
  die("Image not found or not an image");

$width = $img_info[0];
$height = $img_info[1];

switch ($img_info[2]) {
  case IMAGETYPE_GIF  : $src = imagecreatefromgif($img);  break;
  case IMAGETYPE_JPEG : $src = imagecreatefromjpeg($img); break;
  case IMAGETYPE_PNG  : $src = imagecreatefrompng($img);  break;
  default : die("Unknown filetype");
}

$tmp = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $width, $height, $width, $height);
imagejpeg($tmp, $dst.".jpg");

?>

答案 1 :(得分:2)

确保已安装GD库并使用它将gif或png转换为jpg,如

    if ($_FILES["photoimg"]["type"] == "image/jpeg" || $_FILES["photoimg"]["type"] == "image/png" || $_FILES["photoimg"]["type"] == "image/gif" )
    {
      if ($_FILES["photoimg"]["type"] == "image/png" || $_FILES["photoimg"]["type"] == "image/gif" )
      {
       imagejpeg(imagecreatefromstring(file_get_contents($_FILES["photoimg"]["tmp_name"])), "converted.jpg");
       $actual_image_name = time().$session_id.".".$ext;
       move_uploaded_file("converted.jpg", $path.$actual_image_name);
      }
      else
      {
        $actual_image_name = time().$session_id.".".$ext;
        $tmp = $_FILES['photoimg']['tmp_name'];
        move_uploaded_file($tmp, $path.$actual_image_name);
      }
    }