Загрузка изображения PHP и поворот изображения

У меня проблема. Я нашел и скрипт загрузки изображений для нескольких изображений. Я отредактировал это, чтобы соответствовать моему проекту, и это работает. Есть только 1 проблема. Если вы делаете снимок в портретном режиме, снимок поворачивается, потому что вы держите камеру повернутой. Windows настраивает это автоматически, чтобы вы не заметили это в вашей ОС. только apache не делает, если я загружаю его, apears вращается на странице. Некоторое время назад у меня также была эта проблема в более простом проекте. Я сделал небольшой скрипт для проверки ориентации в данных exif, но на этот раз я не могу заставить его работать, я не знаю, когда запустить мой старый код.
Вот мой код Часть fixexif — это вращающаяся часть.

<?php

class UploadImageResize
{
//If you face any errors, increase values of "post_max_size", "upload_max_filesize" and "memory_limit" as required in php.ini

//Some Settings
private $ThumbSquareSize        = 100; //Thumbnail will be 200x200
private $BigImageMaxSize        = 2000; //Image Maximum height or width
private $ThumbPrefix            = "thumb_"; //Normal thumb Prefix
private $DestinationDirectory; //Upload Directory ends with / (slash)
private $Quality                = 90;
private $Image;



//ini_set('memory_limit', '-1'); // maximum memory!
public function __construct($tripname)
{
$this->DestinationDirectory     = 'res/img/Gallery/'.$tripname.'/';
mkdir($this->DestinationDirectory, 0775);

foreach ($_FILES as $file) {
// some information about image we need later.
$ImageName = $file['name'];
$ImageSize = $file['size'];
$TempSrc = $file['tmp_name'];
$ImageType = $file['type'];


if (is_array($ImageName)) {
$c = count($ImageName);

echo '<ul>';

for ($i = 0; $i < $c; $i++) {
$processImage = true;
$RandomNumber = rand(0, 9999999999);  // We need same random name for both files.

if (!isset($ImageName[$i]) || !is_uploaded_file($TempSrc[$i])) {
echo '<div class="error">Error occurred while trying to process <strong>' . $ImageName[$i] . '</strong>, may be file too big!</div>'; //output error
} else {
//Validate file + create image from uploaded file.
switch (strtolower($ImageType[$i])) {
case 'image/png':
$this->setImage(imagecreatefrompng($TempSrc[$i]));
break;
case 'image/gif':
$this->setImage(imagecreatefromgif($TempSrc[$i]));
break;
case 'image/jpeg':
case 'image/pjpeg':

$this->setImage(imagecreatefromjpeg($TempSrc[$i]));
break;
default:
$processImage = false; //image format is not supported!
}
//get Image Size
list($CurWidth, $CurHeight) = getimagesize($TempSrc[$i]);

//Get file extension from Image name, this will be re-added after random name
$ImageExt = substr($ImageName[$i], strrpos($ImageName[$i], '.'));
$ImageExt = str_replace('.', '', $ImageExt);

//Construct a new image name (with random number added) for our new image.
$NewImageName = $RandomNumber . '.' . $ImageExt;

//Set the Destination Image path with Random Name
$thumb_DestRandImageName = $this->DestinationDirectory . $this->ThumbPrefix . $NewImageName; //Thumb name
$DestRandImageName = $this->DestinationDirectory . $NewImageName; //Name for Big Image

//Resize image to our Specified Size by calling resizeImage function.
if ($processImage && $this->resizeImage($CurWidth, $CurHeight, $this->BigImageMaxSize, $DestRandImageName, $this->getImage(), $this->Quality, $ImageType[$i])) {
//Create a square Thumbnail right after, this time we are using cropImage() function
if (!$this->cropImage($CurWidth, $CurHeight, $this->ThumbSquareSize, $thumb_DestRandImageName, $this->getImage(), $this->Quality, $ImageType[$i])) {
echo 'Error Creating thumbnail';
}

} else {
echo '<div class="error">Error occurred while trying to process <strong>' . $ImageName[$i] . '</strong>! Please check if file is supported</div>'; //output error
}

}

}
echo '</ul>';
}
}
}

private function fixExif($filename)
{

$exif = exif_read_data($filename);
if(!empty($exif['Orientation'])) {
$ort = $exif['Orientation'];

switch ($ort) {
case 1: // nothing
break;

case 2: // horizontal flip
$this->setImage(imageflip($filename, 1));
break;

case 3: // 180 rotate left
$this->setImage(imagerotate($filename, 180, 0));
break;

case 4: // vertical flip
$this->setImage(imageflip($filename, 2));
break;

case 5: // vertical flip + 90 rotate right
$this->setImage(imageflip($filename, 2));
$this->setImage(imagerotate($this->getImage(), -90, 0));
break;

case 6: // 90 rotate right
$this->setImage(imagerotate($this->getImage(), -90, 0));
break;

case 7: // horizontal flip + 90 rotate right
$this->setImage(imageflip($this->getImage(), 1));
$this->setImage(imagerotate($this->getImage(), -90, 0));
break;

case 8:    // 90 rotate left
$this->setImage(imagerotate($this->getImage(), 90, 0));
break;
}
}

}

// This function will proportionally resize image
public function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)
{
//Check Image size is not 0
if($CurWidth <= 0 || $CurHeight <= 0)
{
return false;
}

//Construct a proportional size of new image
$ImageScale         = min($MaxSize/$CurWidth, $MaxSize/$CurHeight);
$NewWidth           = ceil($ImageScale*$CurWidth);
$NewHeight          = ceil($ImageScale*$CurHeight);

if($CurWidth < $NewWidth || $CurHeight < $NewHeight)
{
$NewWidth = $CurWidth;
$NewHeight = $CurHeight;
}
$NewCanves  = imagecreatetruecolor($NewWidth, $NewHeight);
// Resize Image
if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))
{
switch(strtolower($ImageType))
{
case 'image/png':
imagepng($this->getImage(),$DestFolder);
break;
case 'image/gif':
imagegif($this->getImage(),$DestFolder);
break;
case 'image/jpeg':
case 'image/pjpeg':
imagejpeg($this->getImage(),$DestFolder,$Quality);
break;
default:
return false;
}
if(is_resource($NewCanves)) {
imagedestroy($NewCanves);
}

return true;
}

}

//This function corps image to create exact square images, no matter what its original size!
public function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType)
{
//Check Image size is not 0
if($CurWidth <= 0 || $CurHeight <= 0)
{
return false;
}

//abeautifulsite.net has excellent article about "Cropping an Image to Make Square"//http://www.abeautifulsite.net/blog/2009/08/cropping-an-image-to-make-square-thumbnails-in-php/
if($CurWidth>$CurHeight)
{
$y_offset = 0;
$x_offset = ($CurWidth - $CurHeight) / 2;
$square_size    = $CurWidth - ($x_offset * 2);
}else{
$x_offset = 0;
$y_offset = ($CurHeight - $CurWidth) / 2;
$square_size = $CurHeight - ($y_offset * 2);
}

$NewCanves  = imagecreatetruecolor($iSize, $iSize);
if(imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size))
{
switch(strtolower($ImageType))
{
case 'image/png':
imagepng($NewCanves,$DestFolder);
break;
case 'image/gif':
imagegif($NewCanves,$DestFolder);
break;
case 'image/jpeg':
case 'image/pjpeg':
imagejpeg($NewCanves,$DestFolder,$Quality);
break;
default:
return false;
}
if(is_resource($NewCanves)) {
imagedestroy($NewCanves);
}
return true;

}

}
public function getImage()
{
return $this->Image;
}

public function setImage($Image)
{
$this->Image = $Image;
}
}

0

Решение

Я исправил это, добавив это после проверки IMG $this->fixExif($TempSrc[$i]);

Весь код для использования другими:

<?php

class UploadImageResize
{
//If you face any errors, increase values of "post_max_size", "upload_max_filesize" and "memory_limit" as required in php.ini

//Some Settings
private $ThumbSquareSize        = 100; //Thumbnail will be 200x200
private $BigImageMaxSize        = 2000; //Image Maximum height or width
private $ThumbPrefix            = "thumb_"; //Normal thumb Prefix
private $DestinationDirectory; //Upload Directory ends with / (slash)
private $Quality                = 90;
private $Image;



//ini_set('memory_limit', '-1'); // maximum memory!
public function __construct($tripname)
{
$this->DestinationDirectory     = 'res/img/Gallery/'.$tripname.'/';
mkdir($this->DestinationDirectory, 0775);

foreach ($_FILES as $file) {
// some information about image we need later.
$ImageName = $file['name'];
$ImageSize = $file['size'];
$TempSrc = $file['tmp_name'];
$ImageType = $file['type'];


if (is_array($ImageName)) {
$c = count($ImageName);

echo '<ul>';

for ($i = 0; $i < $c; $i++) {
$processImage = true;
$RandomNumber = rand(0, 9999999999);  // We need same random name for both files.

if (!isset($ImageName[$i]) || !is_uploaded_file($TempSrc[$i])) {
echo '<div class="error">Error occurred while trying to process <strong>' . $ImageName[$i] . '</strong>, may be file too big!</div>'; //output error
} else {
//Validate file + create image from uploaded file.
switch (strtolower($ImageType[$i])) {
case 'image/png':
$this->setImage(imagecreatefrompng($TempSrc[$i]));
break;
case 'image/gif':
$this->setImage(imagecreatefromgif($TempSrc[$i]));
break;
case 'image/jpeg':
case 'image/pjpeg':
$this->setImage(imagecreatefromjpeg($TempSrc[$i]));
break;
default:
$processImage = false; //image format is not supported!
}
$this->fixExif($TempSrc[$i]);
//get Image Size
list($CurWidth, $CurHeight) = getimagesize($TempSrc[$i]);

//Get file extension from Image name, this will be re-added after random name
$ImageExt = substr($ImageName[$i], strrpos($ImageName[$i], '.'));
$ImageExt = str_replace('.', '', $ImageExt);

//Construct a new image name (with random number added) for our new image.
$NewImageName = $RandomNumber . '.' . $ImageExt;

//Set the Destination Image path with Random Name
$thumb_DestRandImageName = $this->DestinationDirectory . $this->ThumbPrefix . $NewImageName; //Thumb name
$DestRandImageName = $this->DestinationDirectory . $NewImageName; //Name for Big Image

//Resize image to our Specified Size by calling resizeImage function.
if ($processImage && $this->resizeImage($CurWidth, $CurHeight, $this->BigImageMaxSize, $DestRandImageName, $this->getImage(), $this->Quality, $ImageType[$i])) {
//Create a square Thumbnail right after, this time we are using cropImage() function
if (!$this->cropImage($CurWidth, $CurHeight, $this->ThumbSquareSize, $thumb_DestRandImageName, $this->getImage(), $this->Quality, $ImageType[$i])) {
echo 'Error Creating thumbnail';
}

} else {
echo '<div class="error">Error occurred while trying to process <strong>' . $ImageName[$i] . '</strong>! Please check if file is supported</div>'; //output error
}

}

}
echo '</ul>';
}
}
}

private function fixExif($filename)
{

$exif = exif_read_data($filename);
if(!empty($exif['Orientation'])) {
$ort = $exif['Orientation'];

switch ($ort) {
case 1: // nothing
break;

case 2: // horizontal flip
$this->setImage(imageflip($filename, 1));
break;

case 3: // 180 rotate left
$this->setImage(imagerotate($filename, 180, 0));
break;

case 4: // vertical flip
$this->setImage(imageflip($filename, 2));
break;

case 5: // vertical flip + 90 rotate right
$this->setImage(imageflip($filename, 2));
$this->setImage(imagerotate($this->getImage(), -90, 0));
break;

case 6: // 90 rotate right
$this->setImage(imagerotate($this->getImage(), -90, 0));
break;

case 7: // horizontal flip + 90 rotate right
$this->setImage(imageflip($this->getImage(), 1));
$this->setImage(imagerotate($this->getImage(), -90, 0));
break;

case 8:    // 90 rotate left
$this->setImage(imagerotate($this->getImage(), 90, 0));
break;
}
}

}

// This function will proportionally resize image
public function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)
{
//Check Image size is not 0
if($CurWidth <= 0 || $CurHeight <= 0)
{
return false;
}

//Construct a proportional size of new image
$ImageScale         = min($MaxSize/$CurWidth, $MaxSize/$CurHeight);
$NewWidth           = ceil($ImageScale*$CurWidth);
$NewHeight          = ceil($ImageScale*$CurHeight);

if($CurWidth < $NewWidth || $CurHeight < $NewHeight)
{
$NewWidth = $CurWidth;
$NewHeight = $CurHeight;
}
$NewCanves  = imagecreatetruecolor($NewWidth, $NewHeight);
// Resize Image
if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))
{
switch(strtolower($ImageType))
{
case 'image/png':
imagepng($this->getImage(),$DestFolder);
break;
case 'image/gif':
imagegif($this->getImage(),$DestFolder);
break;
case 'image/jpeg':
case 'image/pjpeg':
imagejpeg($this->getImage(),$DestFolder,$Quality);
break;
default:
return false;
}
if(is_resource($NewCanves)) {
imagedestroy($NewCanves);
}

return true;
}

}

//This function corps image to create exact square images, no matter what its original size!
public function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType)
{
//Check Image size is not 0
if($CurWidth <= 0 || $CurHeight <= 0)
{
return false;
}

//abeautifulsite.net has excellent article about "Cropping an Image to Make Square"//http://www.abeautifulsite.net/blog/2009/08/cropping-an-image-to-make-square-thumbnails-in-php/
if($CurWidth>$CurHeight)
{
$y_offset = 0;
$x_offset = ($CurWidth - $CurHeight) / 2;
$square_size    = $CurWidth - ($x_offset * 2);
}else{
$x_offset = 0;
$y_offset = ($CurHeight - $CurWidth) / 2;
$square_size = $CurHeight - ($y_offset * 2);
}

$NewCanves  = imagecreatetruecolor($iSize, $iSize);
if(imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size))
{
$this->fixExif($NewCanves);
switch(strtolower($ImageType))
{
case 'image/png':
imagepng($NewCanves,$DestFolder);
break;
case 'image/gif':
imagegif($NewCanves,$DestFolder);
break;
case 'image/jpeg':
case 'image/pjpeg':
imagejpeg($NewCanves,$DestFolder,$Quality);
break;
default:
return false;
}
if(is_resource($NewCanves)) {
imagedestroy($NewCanves);
}
return true;

}

}
public function getImage()
{
return $this->Image;
}

public function setImage($Image)
{
$this->Image = $Image;
}
}
0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector