You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中解决图片上传后旋转问题的方案求助

解决头像上传后图片旋转的问题

问题根源是手机拍摄的图片会在EXIF元数据中记录拍摄时的方向(Orientation),但GD库默认不会根据这个信息自动调整图片方向,导致处理后的图片出现旋转。以下是修复后的完整代码,加入了EXIF方向检测与图片纠正逻辑:

function generateRandomString($length = 10) 
{
  $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  $randomString = '';
  
  for ($i = 0; $i < $length; $i++) {
    $randomString .= $characters[rand(0, strlen($characters) - 1)];
  }

  return $randomString . '.jpg';
}

// 根据EXIF方向纠正图片
function fixImageOrientation($imagePath) {
    // 检查PHP环境是否支持EXIF扩展
    if (!function_exists('exif_read_data')) {
        return;
    }
    
    $exif = exif_read_data($imagePath);
    if (!isset($exif['Orientation'])) {
        return;
    }
    
    $orientation = $exif['Orientation'];
    $source = imagecreatefromjpeg($imagePath);
    
    // 根据不同的方向值处理图片
    switch ($orientation) {
        case 3: // 旋转180度
            $source = imagerotate($source, 180, 0);
            break;
        case 6: // 顺时针旋转90度
            $source = imagerotate($source, -90, 0);
            break;
        case 8: // 逆时针旋转90度
            $source = imagerotate($source, 90, 0);
            break;
    }
    
    imagejpeg($source, $imagePath, 75);
    imagedestroy($source);
}

if(isset($_FILES["studentProfile"]))
{
  $uploadDir = '../../vendor/img/students/';
  $fileName = $_FILES['studentProfile']['name'];
  $fileTmpName = $_FILES['studentProfile']['tmp_name'];
  $fileType = $_FILES['studentProfile']['type'];
  
  if ($_FILES['studentProfile']['error'] === UPLOAD_ERR_NO_FILE)
  {
    if($stuGender === "male")
    {
      $StuImgId = "male.jpg";
    } 
    elseif($stuGender === "female")
    {
      $StuImgId = "female.jpg";
    } 
    else
    {
      $StuImgId = "default.jpg";
    }
  } 
  else 
  {
    $allowedTypes = ['image/jpeg', 'image/png'];
    
    if (!in_array($fileType, $allowedTypes)) 
    {
      $message = "Error: Only JPG or PNG files are allowed.";
      exit;
    }

    if ($fileType == 'image/png') 
    {
      $source = imagecreatefrompng($fileTmpName);
      $fileName = $uploadDir . generateRandomString();
      imagejpeg($source, $fileName);
      imagedestroy($source);
      // PNG转JPG后纠正方向
      fixImageOrientation($fileName);
    } 
    else 
    {
      $fileName = $uploadDir . generateRandomString();
      move_uploaded_file($fileTmpName, $fileName);
      // 直接纠正JPG图片方向
      fixImageOrientation($fileName);
    }

    $newWidth = 413;
    $newHeight = 531;
    list($width, $height) = getimagesize($fileName);
    $imageResized = imagecreatetruecolor($newWidth, $newHeight);
    $source = imagecreatefromjpeg($fileName);
    imagecopyresized($imageResized, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    imagejpeg($imageResized, $fileName);
    imagedestroy($source);
    imagedestroy($imageResized);
    $compressionQuality = 75;
    $source = imagecreatefromjpeg($fileName);
    imagejpeg($source, $fileName, $compressionQuality);
    imagedestroy($source);
    $upath = parse_url($fileName, PHP_URL_PATH);
    $StuImgId = basename($upath); 
  }
}

关键修改说明:

  • 新增fixImageOrientation函数:读取图片的EXIF方向信息,根据不同的Orientation值对图片进行旋转纠正
  • 在PNG转JPG完成后、以及JPG文件上传完成后,调用该函数纠正图片方向
  • 注意:需要确保服务器PHP环境开启了exif扩展,否则无法读取EXIF数据(可通过phpinfo()查看是否开启)

内容的提问来源于stack exchange,提问作者Harsh Vishwakarma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 15:41:08