Fix iOS Picture Orientation After Upload PHP

Fix iOS picture orientation after upload PHP

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.

- (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;
}

How can I fix iOS image orientation issues when uploading an image with php and after is has been uploaded

I use the solution below from Lee Sherwood to fix the orientation:

https://github.com/leesherwood/Orientation-Fix-PHP

AKA: I couldn't care less what you do with it, im just a nice guy and i want to share. But it would be nice if you left me a little credit :)

Here is the main function that does the actual job.

Pass a string representing the image path and filename such as /var/www/images/image.jpg and it will change the name of the image to include "orig." (for the sake of not deleting your image if something goes wrong) and then create a new image with the same filename, with the orientation fixed

The return bool is not informative and should only be used to to tell your script that there is a proper orientated image available (or not). If you want to know why it failed (theres many reason) then you need to make the return values for informative, or use exceptions.

function fix_orientation($fileandpath){
// Does the file exist to start with?
if( !file_exists( $fileandpath ) )
return false;
// Get all the exif data from the file
// By @kormanowsky: I used '@' to prevent annoying warnings
$exif = @read_exif_data( $fileandpath, 'IFD0' );
// If we dont get any exif data at all, then we may as well stop now
if( !$exif || !is_array( $exif ) )
return false;
// I hate case juggling, so we're using loweercase throughout just in case
$exif = array_change_key_case( $exif, CASE_LOWER );
// If theres no orientation key, then we can give up, the camera hasn't told us the
// orientation of itself when taking the image, and i'm not writing a script to guess at it!
if( !array_key_exists( 'orientation', $exif ) )
return false;
// Gets the GD image resource for loaded image
$img_res = get_image_resource( $fileandpath );
// If it failed to load a resource, give up
if( is_null( $img_res ) )
return false;
// The meat of the script really, the orientation is supplied as an integer,
// so we just rotate/flip it back to the correct orientation based on what we
// are told it currently is
switch( $exif['orientation'] ) {

// Standard/Normal Orientation (no need to do anything, we'll return true as in theory, it was successful)
case 1:
return true;
// Flipped on the horizontal axis (might do it at some point in the future)
case 2:
//By @kormanowsky: imageflip() returns TRUE or FALSE so it's wrong to assign its return value to $final_img
imageflip( $img_res, IMG_FLIP_HORIZONTAL );
break;
// Turned 180 deg
case 3:
imageflip( $img_res, IMG_FLIP_BOTH );
break;
// Upside-Down
case 4:
imageflip( $img_res, IMG_FLIP_VERTICAL );
break;
// Turned 90 deg to the left and flipped
case 5:
imageflip( $img_res, IMG_FLIP_VERTICAL );
// Turned 90 deg to the left
case 6:
$img_res = imagerotate( $img_res, -90, 0 );
break;
// Turned 90 deg to the right and flipped
case 7:
imageflip( $img_res, IMG_FLIP_VERTICAL );
// Turned 90 deg to the right
case 8:
$img_res = imagerotate( $img_res, 90, 0 );
break;
}
//-- rename original (very ugly, could probably be rewritten, but i can't be arsed at this stage)
$parts = explode( "/", $fileandpath );
$oldname = array_pop( $parts );
$path = implode( '/', $parts );
$oldname_parts = explode( ".", $oldname );
$ext = array_pop( $oldname_parts );
$newname = implode( '.', $oldname_parts ) . '.orig.' . $ext;
rename( $fileandpath, $path . '/' . $newname );
// Save it and the return the result (true or false)
$done = save_image_resource( $img_res, $fileandpath );
return $done;
}
function get_image_resource($file)
{
$img = null;
$p = explode( ".", strtolower( $file ) );
$ext = array_pop( $p );
switch( $ext ) {

case "png":
$img = imagecreatefrompng( $file );
break;
case "jpg":
case "jpeg":
$img = imagecreatefromjpeg( $file );
break;
case "gif":
$img = imagecreatefromgif( $file );
break;
}
return $img;
}
function save_image_resource($resource, $location)
{
$success = false;
$p = explode( ".", strtolower( $location ) );
$ext = array_pop( $p );
switch( $ext ) {

case "png":
$success = imagepng( $resource, $location );
break;
case "jpg":
case "jpeg":
$success = imagejpeg( $resource, $location );
break;
case "gif":
$success = imagegif( $resource, $location );
break;
}
return $success;
}
if( !function_exists( 'imageflip' ) ) {
define( "IMG_FLIP_HORIZONTAL", 1 );
define( "IMG_FLIP_VERTICAL", 2 );
define( "IMG_FLIP_BOTH", 3 );
function imageflip(&$resource, $mode)
{

if( $mode == IMG_FLIP_VERTICAL || $mode == IMG_FLIP_BOTH )
$resource = imagerotate( $resource, 180, 0 );
if( $mode == IMG_FLIP_HORIZONTAL || $mode == IMG_FLIP_BOTH )
$resource = imagerotate( $resource, 90, 0 );
}
}

however I had some problem with JPEG, because the function read_exif_data supports no JPEG images. I had to make some changes.

Let me know if you had the same problems. I will suggest the edition on Github.

Have fun!

Problem with image orientation after upload

This is the solution that works for me now. The image orientation correction code is in lines 50-70. There may be a better solution, but this is the only thing I have managed to do, to work properly:

<?php
if(isset($_FILES['image'])){
$errors= array();
foreach($_FILES['image']['tmp_name'] as $key => $tmp_name ){
$file_name =$_FILES['image']['name'][$key];
$file_size =$_FILES['image']['size'][$key];
$file_tmp =$_FILES['image']['tmp_name'][$key];
$file_type=$_FILES['image']['type'][$key];

// Remove encoding problem
$file_name = Normalizer::normalize($file_name);
setlocale(LC_ALL,'bs_BA.UTF-8');

// get file extension
$fileType = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

$temp = pathinfo($file_name, PATHINFO_EXTENSION);
$name = str_replace($temp, '', $file_name);

// get filename without extension
$fileNewName = pathinfo($name, PATHINFO_FILENAME);
$watermarkImagePath = 'watermark.png';
$folderPath = "a/";
$sourceProperties = getimagesize($file_tmp);
$imageType = $sourceProperties[2];

// Resize code
switch ($imageType) {
case IMAGETYPE_PNG:
$imageResourceId = imagecreatefrompng($file_tmp);
$targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
imagepng($targetLayer,$folderPath. $fileNewName. ".jpg");
break;
case IMAGETYPE_GIF:
$imageResourceId = imagecreatefromgif($file_tmp);
$targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
imagegif($targetLayer,$folderPath. $fileNewName. ".jpg");
break;
case IMAGETYPE_JPEG:
$imageResourceId = imagecreatefromjpeg($file_tmp);
$targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
imagejpeg($targetLayer,$folderPath. $fileNewName. ".jpg");

break;
default:
echo "Invalid Image type.";
exit;
break;
}

// Image Orientation correction

$targetFilePath = $folderPath . $file_name;
$exif = exif_read_data($file_tmp);
if ($exif['Orientation']==3 OR $exif['Orientation']==6 OR $exif['Orientation']==8) {
$imageResource = imagecreatefromjpeg($targetFilePath);
switch ($exif['Orientation']) {
case 3:
$image = imagerotate($imageResource, 180, 0);
break;
case 6:
$image = imagerotate($imageResource, -90, 0);
break;
case 8:
$image = imagerotate($imageResource, 90, 0);
break;
}
imagejpeg($image, $targetFilePath);
imagedestroy($imageResource);
imagedestroy($image);
}

// watermark code

$watermarkImg = imagecreatefrompng($watermarkImagePath);

if(preg_match('/[.](jpg)$/i', $file_name)) {
$im = imagecreatefromjpeg($targetFilePath);
} else if (preg_match('/[.](jpeg)$/i', $file_name)) {
$im = imagecreatefromjpeg($targetFilePath);
} else if (preg_match('/[.](png)$/i', $file_name)) {
$im = imagecreatefrompng($targetFilePath);
} else if (preg_match('/[.](gif)$/i', $file_name)) {
$im = imagecreatefromgif($targetFilePath);
}

$marge_right = 1;
$marge_bottom = 1;

$sx = imagesx($watermarkImg);
$sy = imagesy($watermarkImg);

imagecopy($im, $watermarkImg, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($watermarkImg), imagesy($watermarkImg));

imagejpeg($im, $targetFilePath,70);
imagedestroy($im);

}
echo ' Successful upload';
}
function imageResize($imageResourceId,$width,$height) {
if($width > $height){
$targetWidth=1000;
$targetHeight=($height/$width)*$targetWidth;
} else {
$targetHeight=1000;
$targetWidth=($width/$height)*$targetHeight;}
$targetLayer=imagecreatetruecolor($targetWidth,$targetHeight);
imagecopyresampled($targetLayer,$imageResourceId,0,0,0,0,$targetWidth,$targetHeight, $width,$height);
return $targetLayer;
}

?>
<div class="sender">
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image[]" multiple/>
<input type="submit" value="Send"/>
</form></div>

how to fix Orientation of the image and upload image using PHP

You haven't saved your image after rotating it. Save is as below before uploading it.

imagejpeg($image, $filePath);

//upload the image the and update the name of the image
if(move_uploaded_file($filePath, $image_target)){
....
}

Note: imagejpeg should be used for images with JPG extension. For PNG, use imagepng.

iPhone camera images are rotated when uploaded to web

The problem was that image rotation was added to the photo as EXIF data not used by most browsers. There are two solutions:

  1. Apply the rotation on the server side. I was using the Ruby plugin Paperclip (by Thoughtbot) and just had to include the auto-orient convert option to the has_attached_file command in the model:

    has_attached_file :photo, :convert_options => { :all => '-auto-orient' }

  2. Rotate the photo within the iPhone app. This was solved in another stackoverflow question; calling the scaleAndRotate method replaces the rotation meta-data with an image transform, thanks to @Squeegy.

How to check/fix image rotation before upload image using PHP

You are using imagerotate wrong. It expect first parameter to be resource while you are passing the filename. Check manual

Try this:

<?php

$filename = $_FILES['file']['name'];
$filePath = $_FILES['file']['tmp_name'];
$exif = exif_read_data($_FILES['file']['tmp_name']);
if (!empty($exif['Orientation'])) {
$imageResource = imagecreatefromjpeg($filePath); // provided that the image is jpeg. Use relevant function otherwise
switch ($exif['Orientation']) {
case 3:
$image = imagerotate($imageResource, 180, 0);
break;
case 6:
$image = imagerotate($imageResource, -90, 0);
break;
case 8:
$image = imagerotate($imageResource, 90, 0);
break;
default:
$image = $imageResource;
}
}

imagejpeg($image, $filename, 90);

?>

Do not forget to free the memory by adding following two lines:

imagedestroy($imageResource);
imagedestroy($image);

PHP image resize script rotate image uploaded from iPhone Camera

Images can have extra information about orientation (= landscape or portrait). See:

http://www.impulseadventure.com/photo/exif-orientation.html

This could explain your problem. If you look at:

http://php.net/manual/en/function.imagecreatefromjpeg.php

Then you can find this in the comments:

This function does not honour EXIF orientation data. Pictures that
are rotated using EXIF, will show up in the original orientation after
being handled by imagecreatefromjpeg(). Below is a function to create
an image from JPEG while honouring EXIF orientation data.

And how you can correct for it:

function imagecreatefromjpegexif($filename)
{
$img = imagecreatefromjpeg($filename);
$exif = exif_read_data($filename);
if ($img && $exif && isset($exif['Orientation']))
{
$ort = $exif['Orientation'];

if ($ort == 6 || $ort == 5)
$img = imagerotate($img, 270, null);
if ($ort == 3 || $ort == 4)
$img = imagerotate($img, 180, null);
if ($ort == 8 || $ort == 7)
$img = imagerotate($img, 90, null);

if ($ort == 5 || $ort == 4 || $ort == 7)
imageflip($img, IMG_FLIP_HORIZONTAL);
}
return $img;
}


Related Topics



Leave a reply



Submit