首页 > 解决方案 > PHP在创建缩略图和上传之前从移动设备修复图像方向

问题描述

我有一个表格供用户将图像上传到画廊,目前手机和平板电脑拍摄的某些图像显示方向错误。

我正在尝试读取 EXIF 数据以更正此问题,然后创建一个缩略图。我正在阅读此处此处的示例,但是在将图像保存到服务器之前,这些示例都不会继续调整图像,而且我无法确定是否必须在创建缩略图之前将其保存在某个地方。

我的脚本验证工作正常,确保文件格式正确、不存在且小于 5mb。

我已将变量设置为;

$userimage = $_FILES["userimage"]["name"];
$filePath = $_FILES['userimage']['tmp_name'];
$filetype = $_FILES["userimage"]["type"];
$targetDir = "../public/img/uploads/";
$targetFilePath = $targetDir . $userimage;  
$targetThumbFilePath = "../public/img/uploads/thumbs/";
$ext = pathinfo(strtolower($userimage), PATHINFO_EXTENSION);

然后这是我创建缩略图和上传的代码;(一旦我解决了这个问题,我就知道文件名应该由我指定)。

$exif = exif_read_data($_FILES['userimage']['tmp_name']);
if (!empty($exif['Orientation'])) {

    $image = imagecreatefromstring($filePath); 
    switch ($exif['Orientation']) {
        case 3:
        $image = imagerotate($image, 180, 0);

        break;
        case 6:
        $image = imagerotate($image, -90, 0);

        break;
        case 8:
        $image = imagerotate($image, 90, 0);

        break;
        default:                        
    } 
}

if (move_uploaded_file($image, $targetFilePath)){

  $upload = '../public/img/uploads/' . $_FILES["userimage"]["name"];
  list ($width, $height, $type) = getimagesize ($upload);

  //switches content-type and calls the imagecreatefrom... function
  if ($type == 1)
  {                    
      $image = imagecreatefromgif($upload);
  }
  elseif ($type == 2)
  {                    
      $image = imagecreatefromjpeg($upload);
  }
  elseif ($type == 3)
  {                    
      $image = imagecreatefrompng($upload);
  }

  $src = '../public/img/uploads/thumbs/thumb-' . $_FILES["userimage"]["name"];                 

  // calculate thumbnail size
  $new_width = 616;

  $new_height = floor( $height * ( $new_width / $width ) );

  // create a new temporary image
  $tmp_img = imagecreatetruecolor($new_width, $new_height);

  // copy and resize old image into new image 
  imagecopyresized( $tmp_img, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

  //switches content-type and saves thumbnail
  if ($type == 1)
  {
      imagegif($tmp_img, $src);
  }
  elseif ($type == 2)
  {
      imagejpeg($tmp_img, $src);
  }
  elseif ($type == 3)
  {
      imagepng($tmp_img, $src);
  }

}

标签: phpmysqlhtml

解决方案


推荐阅读