php 上传PHP后修复iOS图片方向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22308921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:49:17  来源:igfitidea点击:

Fix iOS picture orientation after upload PHP

phpiosiphoneimageupload

提问by John Doe

Is there a way to rotate a picture with PHP onlyif it is not correctly positioned after uploaded from iOS?

当从 iOS 上传后图片位置不正确时,是否可以使用 PHP 旋转图片?

Some pictures are rotated 90 degrees while others upload correctly.

一些图片旋转了 90 度,而其他图片正确上传。

回答by Thomas Sahlin

Use exif_read_datato find out the orientation of the image:

使用exif_read_data找出图像的方向:

$exif = exif_read_data('image.jpg');

if (isset($exif['Orientation']))
{
  switch ($exif['Orientation'])
  {
    case 3:
      // Need to rotate 180 deg
      break;

    case 6:
      // Need to rotate 90 deg clockwise
      break;

    case 8:
      // Need to rotate 90 deg counter clockwise
      break;
  }
}

You'll find an explanation of the orientation codes here: http://www.impulseadventure.com/photo/exif-orientation.html

您可以在此处找到方向代码的说明:http: //www.impulseadventure.com/photo/exif-orientation.html

回答by Bhupesh

The image is rotating because you are saving the image in JPEG, if you save your image in PNG then the orientation will not change. here is the code to fix orientation issue.

图像正在旋转,因为您将图像保存为 JPEG,如果您将图像保存为 PNG,则方向不会改变。这是修复方向问题的代码。

- (UIImage *)fixrotation:(UIImage *)image{   

    if (image.imageOrientation == UIImageOrientationUp) return image;
    CGAffineTransform transform = CGAffineTransformIdentity;

    switch (image.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, image.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;

        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;

        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, image.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationUpMirrored:
            break;
    }

    switch (image.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;

        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationDown:
        case UIImageOrientationLeft:
        case UIImageOrientationRight:
            break;
    }

    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, image.size.width, image.size.height,
                                             CGImageGetBitsPerComponent(image.CGImage), 0,
                                             CGImageGetColorSpace(image.CGImage),
                                             CGImageGetBitmapInfo(image.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (image.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,image.size.height,image.size.width), image.CGImage);
            break;

        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,image.size.width,image.size.height), image.CGImage);
            break;
    }

    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

回答by Mathuvathanan

I have created a function to correct archived images and you can use this with small modification for the on air correction.

我创建了一个功能来校正存档图像,您可以使用它进行小修改以进行直播校正。

gist link of the function

函数的要点链接

<?php
/*
Correct image orientation v1.0

Author: Mathuvathanan Mounasamy

Licensed under the MIT license

This function correct all the images' orientation in a given path or directory.

Run:    php -r "require 'correctImageOrientation.php'; correctImageOrientation('test/');"
        or
        php -r "require 'correctImageOrientation.php'; correctImageOrientation('test/test1');"
        or
        php -r "require 'correctImageOrientation.php'; correctImageOrientation('test');"
*/
function correctImageOrientation($directory) {
    $scanned_directory = array_diff(scandir($directory), array('..', '.'));
    echo "<pre>";
    print_r("scanned directory: \r\n");
    print_r($scanned_directory);
    echo "</pre>\r\n";
    foreach ($scanned_directory as &$file) {

        if (is_dir($directory."/".$file)) {
            correctImageOrientation($directory."/".$file);
        } else {                                    
            $filen = explode(".", $file);
            $ext = end($filen);
            try {

                $exif = @exif_read_data($directory."/".$file);

                $orientation = $exif['Orientation'];

                if (isset($orientation) && $orientation != 1){
                    switch ($orientation) {
                        case 3:
                        $deg = 180;
                        break;
                        case 6:
                        $deg = 270;
                        break;
                        case 8:
                        $deg = 90;
                        break;
                    }

                    if ($deg) {

                        // If png
                        if ($ext == "png") {
                            $img_new = imagecreatefrompng($directory."/".$file);
                            $img_new = imagerotate($img_new, $deg, 0);

                            // Save rotated image
                            imagepng($img_new,$directory.$file);
                        }else {
                            $img_new = imagecreatefromjpeg($directory."/".$file);
                            $img_new = imagerotate($img_new, $deg, 0);

                            // Save rotated image
                            imagejpeg($img_new,$directory."/".$file,80);
                        }
                    }
                    echo "<pre>";
                    print_r("image changed: \r\n");
                    print_r($directory."/".$file);
                    echo "</pre>\r\n";
                }

            } catch (Exception $e) {
                echo "error:";
                echo $e;
                echo "error";
            }
        }
    }
    unset($file);
}

?>

回答by Martin

It doesn't quite answer your question but I always use this script to fix the orientation and scale to a sensible size pre-upload. This way you save hte app user some bandwidth and don't have anything to do server side.

它不能完全回答你的问题,但我总是使用这个脚本来修复方向和缩放到一个合理的预上传大小。通过这种方式,您可以为 hte 应用程序用户节省一些带宽,而无需在服务器端做任何事情。

- (UIImage *)scaleAndRotateImage:(UIImage *)image {
    int kMaxResolution = 1024; // Or whatever

    CGImageRef imgRef = image.CGImage;

    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);


    CGAffineTransform transform = CGAffineTransformIdentity;
    CGRect bounds = CGRectMake(0, 0, width, height);
    if (width > kMaxResolution || height > kMaxResolution) {
        CGFloat ratio = width/height;
        if (ratio > 1) {
            bounds.size.width = kMaxResolution;
            bounds.size.height = roundf(bounds.size.width / ratio);
        }
        else {
            bounds.size.height = kMaxResolution;
            bounds.size.width = roundf(bounds.size.height * ratio);
        }
    }

    CGFloat scaleRatio = bounds.size.width / width;
    CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
    CGFloat boundHeight;
    UIImageOrientation orient = image.imageOrientation;
    switch(orient) {

        case UIImageOrientationUp: //EXIF = 1
            transform = CGAffineTransformIdentity;
            break;

        case UIImageOrientationUpMirrored: //EXIF = 2
            transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            break;

        case UIImageOrientationDown: //EXIF = 3
            transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;

        case UIImageOrientationDownMirrored: //EXIF = 4
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
            transform = CGAffineTransformScale(transform, 1.0, -1.0);
            break;

        case UIImageOrientationLeftMirrored: //EXIF = 5
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;

        case UIImageOrientationLeft: //EXIF = 6
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;

        case UIImageOrientationRightMirrored: //EXIF = 7
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeScale(-1.0, 1.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;

        case UIImageOrientationRight: //EXIF = 8
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;

        default:
            [NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];

    }

    UIGraphicsBeginImageContext(bounds.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
        CGContextScaleCTM(context, -scaleRatio, scaleRatio);
        CGContextTranslateCTM(context, -height, 0);
    }
    else {
        CGContextScaleCTM(context, scaleRatio, -scaleRatio);
       CGContextTranslateCTM(context, 0, -height);
    }

    CGContextConcatCTM(context, transform);

    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return imageCopy;
}

回答by Ketan Chaudhari

you can add below script after upload image in folder

您可以在文件夹中上传图像后添加以下脚本

 $filename = "/files/1.jpg"; /*ADD YOUR FILENAME WITH PATH*/
 $exif = exif_read_data($filename);
 $ort = $exif['Orientation']; /*STORES ORIENTATION FROM IMAGE */
 $ort1 = $ort;
 $exif = exif_read_data($filename, 0, true);
    if (!empty($ort1))
     {
       $image = imagecreatefromjpeg($filename);
       $ort = $ort1;
          switch ($ort) {
                case 3:
                    $image = imagerotate($image, 180, 0);
                    break;

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

                case 8:
                    $image = imagerotate($image, 90, 0);
                    break;
            }
        }
       imagejpeg($image,$filename, 90); /*IF FOUND ORIENTATION THEN ROTATE IMAGE IN PERFECT DIMENSION*/

this script works after image will uploaded in folder, so you can add this script after upload file in folder

此脚本在图像上传到文件夹后工作,因此您可以在文件夹中上传文件后添加此脚本

回答by jemiloii

Using the GD Library we can manipulate images in PHP. This script uses the imagerotate () function to rotate a photo. In our case we are rotating it 90 degrees but this can be changed in the script.

使用 GD 库,我们可以在 PHP 中操作图像。该脚本使用 imagerotate() 函数来旋转照片。在我们的例子中,我们将它旋转 90 度,但这可以在脚本中更改。

 <?php 
 // The file you are rotating
 $image = 'myfile.jpg';

 //How many degrees you wish to rotate
 $degrees = 90;

 // This sets the image type to .jpg but can be changed to png or gif
 header('Content-type: image/jpeg') ;

 // Create the canvas
 $source = imagecreatefromjpeg($image) ;

 // Rotates the image
 $rotate = imagerotate($source, $degrees, 0) ;

 // Outputs a jpg image, you could change this to gif or png if needed
 imagejpeg($rotate) ;
 ?> 

The most important part of this script, the rotating, is done with the imagerotate() function. The parameters of this function are:

这个脚本最重要的部分,旋转,是用 imagerotate() 函数完成的。这个函数的参数是:

imagerotate (The_image, degrees_to_rotate, background_color, Optional_ignore_transparency)

If the optional ignore transparency is blank or 0, then the transparency is preserved.

如果可选的忽略透明度为空白或 0,则保留透明度。

array getimagesize ( string $filename [, array &$imageinfo ] )

The getimagesize() function will determine the size of any given image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML IMG tag and the correspondant HTTP content type.

getimagesize() 函数将确定任何给定图像文件的大小,并返回尺寸以及文件类型和要在普通 HTML IMG 标签内使用的高度/宽度文本字符串和相应的 HTTP 内容类型。

You should use this to check how the phone image is oriented so you can know when to call imagerotate().

您应该使用它来检查手机图像的方向,以便您知道何时调用 imagerotate()。

You can also save the image with imagejpeg. http://www.php.net/manual/en/function.imagejpeg.php

您还可以使用 imagejpeg 保存图像。http://www.php.net/manual/en/function.imagejpeg.php

// Save the image as 'path/to/myfile.jpg'
imagejpeg($image, 'path/to/myfile.jpg');

// Free up memory
imagedestroy($image);

回答by akr

// File and rotation
$filename = 'test.jpg';
$degrees = 180;

// Content type
header('Content-type: image/jpeg');

// Load
$source = imagecreatefromjpeg($filename);

// Rotate
$rotate = imagerotate($source, $degrees, 0);

// Output
imagejpeg($rotate);

check this link :
http://www.php.net/manual/en/function.imagerotate.php

回答by JLGarcia

if you are using ImageMagick there is a a very simple fix for it, just add -auto-orient to your command.

如果您使用 ImageMagick,有一个非常简单的修复方法,只需将 -auto-orient 添加到您的命令中即可。

convert -auto-orient -quality 90 -resize 1200x800 $f-new