php - 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);
}
}
解决方案
推荐阅读
- scala - 如何使用 Scala 在 lagom 中为 NoHostAvailableException 编写测试用例?
- react-native - 想要真实的图像是可点击的,但不应该点击 alpha 背景。请建议我该怎么做
- amazon-cognito - 将 AWS Cognito/Amplify 用作 OIDC 服务
- angular - 单击特定行时嵌套的 Mat-table
- amazon-dynamodb - 当我们将更多数据放入表中时,DynamodB 查询开始花费更多时间
- c# - 使用 Resharper SDK 查找 ITypeElement 或 IDeclaredElement 的用法
- forms - Flutter - 在点击 TextFormField 时显示对话框 NumberPicker
- android-gradle-plugin - 如何在gradle中修复“程序类型已经存在”
- django - 如何将多个参数从views.py传递给表单并在forms.py中获取它们并添加到django 2.1.7中的HiddenInput字段?
- sql - 进行全文研究并限制排名号返回的记录