如何在上传时仅旋转jpg和jpeg?

时间:2016-04-15 08:39:20

标签: php image-processing imagemagick

下面我有一个非常简单的上传脚本,可以上传png,jpg和jpeg格式的图片。

我知道png图像会保持方向,因为该文件没有关于其方向的信息 但是,在上传jpg或jpeg时,纵向图像会逆时针旋转90度。

如何只旋转jpg和jpeg以获得正确的方向?

P.s此上传脚本还会将图像路径更新为MySQL

非常感谢您的帮助!

<?php

if (isset($_FILES['image'])) {
   $errors = array();
   $file_name = $_FILES['image']['name'];
   $file_size = $_FILES['image']['size'];
   $file_tmp = $_FILES['image']['tmp_name'];
   $file_type = $_FILES['image']['type'];
   $file_ext = strtolower(end(explode('.',$_FILES['image']['name'])));
   $img_path = ("images/".$file_name);
   $expensions = array("jpeg","jpg","png");

   if (in_array($file_ext,$expensions)=== false) {
       $errors[] = "extension not allowed, please choose a JPEG or PNG file.";
   }

   if ($file_size > 2097152) {
       $errors[] = 'File too large';
   }

   if (empty($errors) == true) {
       // connect to the database
       $servername = 'HOST';
       $username = 'USER';
       $password = 'PASS';
       $dbname = 'TABLE';
       $current_user = $_SESSION['user_name'];

       try {
           $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
           // set the PDO error mode to exception
           $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

           $sql = "UPDATE users SET image_name='$file_name', image_size='$file_size', image_path='$img_path'  WHERE user_id = $current_user";

           // Prepare statement
           $stmt = $conn->prepare($sql);

           // execute the query
           $stmt->execute();

           // echo a message to say the UPDATE succeeded
           echo "";
       } catch(PDOException $e) {
           echo $sql . "<br>" . $e->getMessage();
       }

       $conn = null;

       move_uploaded_file($file_tmp,"images/".$file_name);
       echo "";
   } else {
       print_r($errors);
   }
}
?>     

1 个答案:

答案 0 :(得分:3)

您需要使用imagerotate() php函数。

$degrees = 90; //required value here
$img_path = ("images/".$file_name);
$source = imagecreatefromjpeg($filename);
$rotate = imagerotate($source, $degrees, 0);
$extension = substr(strrchr($file_name,'.'),1);

if ($extension == jpg || $extension == jpeg)
{
imagejpeg($rotate);
}
imagedestroy($source); //free memory
imagedestroy($rotate);