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

标签 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);
   }
}
?>     

最佳答案

您需要使用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);

关于php - 如何在上传时仅旋转 jpg 和 jpeg?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36642217/

相关文章:

php - 个人服务器无法登录

c++ - 将扭曲/转换后的图像与基本图像匹配的最快、最准确的方法?

php - Laravel 检查它是否有来自模型的数据

c# - 调整大小时,某些图像正在旋转

php - 估计 libGD 操作所需的内存

imagemagick - 使用 ImageMagick 绘制居中矩形

php - 如何在 Apache 中为 ImageMagick 设置路径,以便可以从 PHP system() 运行?

php - TCPDF - 如何从 PDF 中提取页面?

有数据时 PHP MySQL 得到零结果

javascript - 跨域页面刷新