Image rotating 90 degrees when uploaded from mobile? PHP - php

I have a site where users can upload photos from mobile, but all the photos that are uploaded from mobiles, show 90 degrees to the left when upload. Live site is www.uneraportoj.com. I now the problem is the exeif but i tried using a plugin but is not working. Any help is recommended.
Share script code is:
<?php
include_once('help.php');
if(isset($_POST['submit'])){
$title = $_POST['title'];
$content = $_POST['content'];
$posted = $_POST['posted'];
$date = date("Y-m-d H:i:s");
$ip = $_SERVER["REMOTE_ADDR"];
$rand = rand(1,1000000);
if(empty($title)){
echo "Titulli eshte bosh.";
}else if(empty($content)){
echo "Permbajtja eshte bosh.";
}else if(empty($_FILES['image']['name'])){
echo "Imazhi eshte bosh.";
}else if (
($_FILES['image']['type'] == 'image/gif')
|| ($_FILES['image']['type'] == 'image/jpeg')
|| ($_FILES['image']['type'] == 'image/pjpeg')
|| ($_FILES['image']['type'] == 'image/png')
&& ($_FILES['image']['size'] < 200000)
){
$part = $rand.'_'.$_FILES['image']['name'];
if ($_FILES["image"]["error"] > 0) {
echo "return code" . $_FILES['image']['error'];
//Code from plugin start
if($_FILES['image']){
// If the image is jpg and has orientation data, make sure we orientate correctly before uploading
if($image->exif('Orientation'))
$image = orientate($image, $image->exif('Orientation'));
}
}else if(move_uploaded_file($_FILES['image']['tmp_name'],'images/'. $part.'')){
if(empty($posted)){
$posted = 'Anonim';
}
$sql = "INSERT INTO ***(title, content, date, image, posted, ip) VALUES (:title, :content, :date, :image, :posted, :ip)";
$query = $db->prepare($sql);
$results = $query->execute(array(
':title' => htmlentities ($title),
':content' => htmlentities ($content),
':date' => $date,
':image' => $part,
':posted' => htmlentities ($posted),
':ip' => $ip
));
echo "<div id='ok'>Lajmi u raportua me sukses. Kontrollojeni <a href='index.php'>ketu</a> .</div>";
}
}else{
echo "<div id='ok'>Imazhi nuk eshte i sakte. (Vetem jpg/png)</div>";
}
}
?>
Plugin code :
<?php /**
* Orientate an image, based on its exif rotation state
*
* #param Intervention\Image\Image $image
* #param integer $orientation Image exif orientation
* #return Intervention\Image\Image
*/
$image = $_FILES['image'];
function orientate($image, $orientation)
{
switch ($orientation) {
// 888888
// 88
// 8888
// 88
// 88
case 1:
return $image;
// 888888
// 88
// 8888
// 88
// 88
case 2:
return $image->flip('h');
// 88
// 88
// 8888
// 88
// 888888
case 3:
return $image->rotate(180);
// 88
// 88
// 8888
// 88
// 888888
case 4:
return $image->rotate(180)->flip('h');
// 8888888888
// 88 88
// 88
case 5:
return $image->rotate(-90)->flip('h');
// 88
// 88 88
// 8888888888
case 6:
return $image->rotate(-90);
// 88
// 88 88
// 8888888888
case 7:
return $image->rotate(-90)->flip('v');
// 8888888888
// 88 88
// 88
case 8:
return $image->rotate(90);
default:
return $image;
}
}
?>

I found this youtube video to be super helpful on image oriantaion with exif data
check it out
https://www.youtube.com/watch?v=HjHSgGFqAtE
print 'exif orientation';
$original_filename = 'car1.jpg';
$exif_data = exif_read_data($original_filename);
// displays exif data
// print '<pre>';
// print_r($exif_data);
// print '<pre>';
$orientation = orientation($exif_data);
$degrees = orientation_flag($orientation);
print '<pre>';
print_r($orientation);
print '</pre>';
print '<pre>';
print_r($degrees);
print '</pre>';
$image_data = imagecreatefromjpeg($original_filename);
$image_rotate = imagerotate($image_data, $degrees, 0);
$rotated_filename = 'rotated_' . $original_filename;
imagejpeg($image_rotate, $rotated_filename);
imagedestroy($image_data);
imagedestroy($image_rotate);
// finds orientation value in exif data
function orientation($exif_data) {
// search array for orientation
foreach($exif_data as $key => $val) {
// print '<pre>';
// print_r($key);
// print '<pre>';
if(strtolower($key) == 'orientation') {
return $val;
}
}
}
// gets orientation data and returns degrees needed for rotation
function orientation_flag($orientation) {
switch($orientation):
case 1:
return 0;
case 8:
return 90;
case 3:
return 180;
case 6:
return 270;
endswitch;
}
?>
<img src="car1.jpg" width="400"/>
<br>
<img src="rotated_car1.jpg" width="400"/>

You have your function call under the if(error) statement, meaning it will only rotate if there is an error. Place it after your image has passed the error checks and you have moved it to the final location.
if ($_FILES["image"]["error"] > 0) {
echo "return code" . $_FILES['image']['error'];
}else if(move_uploaded_file($_FILES['image']{'tmp_name'],'images/'. $part.'')){
if(file_exists('images/'. $part.'')){
/* read exif data (returns it as an array) */
$exif_read = exif_read_data('images/'. $part.'');
/* if exif contains orientation property (some images don't) */
if(!empty($exif_read['Orientation'])){
$orientation_data = $exif_read['Orientation'];
$image = orientate($image, $Orientation_data);
}
Edit:
I copied and pasted the exact code that I am using for image uploading. For what I'm doing, I only have to worry about orientations 3, 6, and 8, but you can add the rest if you think you'll need them. Use PHP's imageflip() function after imagerotate() (read how to use that here)
<?php
require("../db_credentials.php");
if($_FILES['file']['name']){
$name = htmlspecialchars($_FILES['file']['name']);
$ext = end((explode(".", $name)));
$ext = strtolower($ext);
//if no errors...
if(!$_FILES['file']['error']){
//now is the time to modify the future file name and validate the file
$new_file_name = date('ymdHisu'). ".". $ext;
if($_FILES['file']['size'] > (6144000)){
$valid_file = false;
echo 'Oops! Your file\'s size is to large.';
}
elseif($ext !== "jpg" && $ext !== "png" && $ext !== "jpeg" && $ext != "gif" && $ext !== "bmp") {
$valid_file = false;
echo "Your file must be in jpg, jpeg, png, gif, or bmp formats.";
}
else{
$valid_file = true;
}
//if the file has passed the test
if($valid_file){
//move it to where we want it to be
move_uploaded_file($_FILES['file']['tmp_name'], 'images/'.$new_file_name);
$exif_read = exif_read_data("images/".$new_file_name);
if(!empty($exif_read['Orientation'])){
$orientation_data = exif_read_data("images/".$new_file_name)['Orientation'];
}
if(isset($orientation_data) && $orientation_data !== 1){
$path = "../images/". $new_file_name;
$buffer = ImageCreateFromJPEG($path);
$exif = exif_read_data($path);
if(!empty($exif['Orientation'])){
switch($exif['Orientation']){
case 8:
$buffer = imagerotate($buffer,90,0);
break;
case 3:
$buffer = imagerotate($buffer,180,0);
break;
case 6:
$buffer = imagerotate($buffer,-90,0);
break;
}
imagejpeg($buffer, $path, 90);
}
}
}
}
//if there is an error...
else
{
//set that to be the returned message
echo 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
?>

Related

How to rotate all images in a folder based on exif and override old photos W/php

I have a group of photos uploaded by ftp in to /Photos (some are .JPG .jpg .png ect) but not all are rotated correctly i have a php script that is able to tell me how much they need to be rotated to be the right way round (landscaped/portrait) but i cant seem to work out how to save them or do the actual rotating
I have tried
//define image path
$filename="image.jpg";
// Load the image
$source = imagecreatefromjpeg($filename);
// Rotate
$rotate = imagerotate($source, $degrees, 0);
//and save it on your server...
imagejpeg($rotate, "myNEWimage.jpg");
And:
<?php
$files = glob('{**.jpg,*.JPG,*.png, *.PNG, *.PNG}',GLOB_BRACE);
echo '<pre>'; print_r($files); echo '</pre>';
foreach ($files as $i)
{
// GET Rotate
$exif = #exif_read_data($i,0,true);
$orientation = #$exif['IFD0']['Orientation'];
if($orientation == 7 || $orientation == 8) {
$degrees = 90;
echo " | 90";
} elseif($orientation == 5 || $orientation == 6) {
$degrees = 270;
echo " | 270";
} elseif($orientation == 3 || $orientation == 4) {
$degrees = 180;
echo " | 180";
} else {
$degrees = 0;
echo " | 0";
}
$filename= $i;
$source = imagecreatefromjpeg($filename);
$rotate = imagerotate($source, $degrees, 0);
//and save it on your server...
imagejpeg($rotate, $i);
}
echo '<pre>'; print_r($files); echo '</pre>';
echo"ROTATED: ";
foreach ($files as $i){
printf("<img style='max-height: 100px;'src='%s'/>", basename($i));
}
?>
My current code:
<?php
$files = glob('{**.jpg,*.JPG,*.png, *.PNG, *.PNG}',GLOB_BRACE);
echo '<pre>'; print_r($files); echo '</pre>';
foreach ($files as $i)
{
// GET Rotate
$exif = #exif_read_data($i,0,true);
$orientation = #$exif['IFD0']['Orientation'];
if($orientation == 7 || $orientation == 8) {
$degrees = 90;
echo " | 90";
} elseif($orientation == 5 || $orientation == 6) {
$degrees = 270;
echo " | 270";
} elseif($orientation == 3 || $orientation == 4) {
$degrees = 180;
echo " | 180";
} else {
$degrees = 0;
echo " | 0";
}
}
echo '<pre>'; print_r($files); echo '</pre>';
echo"ROTATED: ";
foreach ($files as $i){
printf("<img style='max-height: 100px;'src='%s'/>", basename($i));
}
?>
no error messages. this script is inside the photos folder (for debugging reasons) but it is able to output the photos and not rotate and save them
Your code is not logic, You need to use $rotate for your $files
Take a look at main documentation imagerotate Function
I have found a solution by adding a bit to someone eles code to make it scan a folder and edit all the photos, im sure i could make it more efficient
<?PHP
/**
* Document : EXIF Image Rotate Class
* OG Author : josephtinsley
* Edited by : Sir Charles (Added for each loop to edit more than one file <3)
* Description: PHP class that detects a JPEG image current orientation and rotates a image using the images EXIF data.
* http://twitter.com/josephtinsley
*/
class RotateImage {
/*
* #param string $setFilename - Set the original image filename
* #param array $exifData - Set the original image filename
* #param string $savedFilename - Set the rotated image filename
*/
private $setFilename = "";
private $exifData = "";
private $degrees = "";
public function __construct($setFilename)
{
try{
if(!file_exists($setFilename))
{
throw new Exception('File not found.');
}
$this->setFilename = $setFilename;
} catch (Exception $e ) {
die($e->getMessage());
}
}
/*
* EXTRACTS EXIF DATA FROM THE JPEG IMAGE
*/
public function processExifData()
{
$orientation = 0;
$this->exifData = exif_read_data($this->setFilename);
foreach($this->exifData as $key => $val)
{
if(strtolower($key) == "orientation" )
{
$orientation = $val;
break;
}
}
if( $orientation == 0 )
{
$this->_setOrientationDegree(1);
}
$this->_setOrientationDegree($orientation);
}
/*
* DETECTS AND SETS THE IMAGE ORIENTATION
* Orientation flag info http://www.impulseadventure.com/photo/exif-orientation.html
*/
private function _setOrientationDegree($orientation)
{
switch($orientation):
case 1:
$this->degrees = 0;
break;
case 8:
$this->degrees = 90;
break;
case 3:
$this->degrees = 180;
break;
case 6:
$this->degrees = 270;
break;
endswitch;
$this->_rotateImage();
}
/*
* ROTATE THE IMAGE BASED ON THE IMAGE ORIENTATION
*/
private function _rotateImage()
{
if($this->degrees < 1 )
{
return FALSE;
}
$image_data = imagecreatefromjpeg($this->setFilename);
return imagerotate($image_data, $this->degrees, 0);
}
/*
* SAVE THE IMAGE WITH THE SAME FILENAME
*/
public function savedFileName($savedFilename)
{
if($this->degrees < 1 )
{
return false;
}
$imageResource = $this->_rotateImage();
if($imageResource == FALSE)
{
return false;
}
imagejpeg($imageResource, $savedFilename);
}
} //END CLASS
$files = glob('{**.jpg,*.JPG,*.png, *.PNG, *.PNG}',GLOB_BRACE); //Get all files in current dir with extenshions .jpg .JPG .png .PNG .PNG (CASE SENSITIVE)
echo '<pre>'; print_r($files); echo '</pre>';//print the arry so you know what files where edited
foreach ($files as $i)
{
$imageFile = $i;//just pass on this var in case you want to specific a set file change $i to "FILE_NAME.JPG"
$savedFile = $imageFile;//if you want to have it under a new file name use $savedFile = "rotated_".$imageFile;
$rotate = new RotateImage($imageFile);
$rotate->processExifData();
$rotate->savedFileName($savedFile);
// print '<img src="'.$imageFile.'" width="250"/>'."<br>";// this is for if you save it under a diffrent name to see the diffrence (good for debuging)
print '<img src="'.$savedFile.'" width="250"/>'."<br>"; //!SHOW THE SAVED ROTATED IMAGE
print '<h1>'.$i.'</h1><br>';//show the image name under the img (good for debbuging)
}
?>

File not uploading into database. Validation ok?

I have a site where users can upload photos from mobile, but all the photos that are uploaded from mobiles, show 90 degrees to the left when upload. I fixed this problem but now, after the file is validated, its not going into the db. please any help..
Share script code is:
<?php
require('help.php');
if(isset($_POST['submit'])){
$title = $_POST['title'];
$content = $_POST['content'];
$posted = $_POST['posted'];
$date = date("Y-m-d H:i:s");
$ip = $_SERVER["REMOTE_ADDR"];
$rand = rand(1,1000000);
if(empty($title)){
echo "Titulli eshte bosh.";
}else if(empty($content)){
echo "Permbajtja eshte bosh.";
}else if(empty($_FILES['file']['name'])){
echo "Imazhi eshte bosh.";
}else if($_FILES['file']['name']){
$name = htmlspecialchars($_FILES['file']['name']);
$ext = end((explode(".", $name)));
$ext = strtolower($ext);
//if no errors...
if(!$_FILES['file']['error']){
//now is the time to modify the future file name and validate the file
$new_file_name = date('ymdHisu'). ".". $ext;
if($_FILES['file']['size'] > (6144000)){
$valid_file = false;
echo 'Oops! Your file\'s size is to large.';
}
elseif($ext !== "jpg" && $ext !== "png" && $ext !== "jpeg" && $ext != "gif" && $ext !== "bmp") {
$valid_file = false;
echo "Your file must be in jpg, jpeg, png, gif, or bmp formats.";
}else{
$valid_file = true;
}
//if the file has passed the test
if($valid_file){
//move it to where we want it to be
move_uploaded_file($_FILES['file']['tmp_name'], 'images/'.$new_file_name);
$exif_read = exif_read_data("images/".$new_file_name);
if(!empty($exif_read['Orientation'])){
$orientation_data = exif_read_data("images/".$new_file_name)['Orientation'];
}
if(isset($orientation_data) && $orientation_data !== 1){
$path = "images/". $new_file_name;
$buffer = ImageCreateFromJPEG($path);
$exif = exif_read_data($path);
if(!empty($exif['Orientation'])){
switch($exif['Orientation']){
case 8:
$buffer = imagerotate($buffer,90,0);
break;
case 3:
$buffer = imagerotate($buffer,180,0);
break;
case 6:
$buffer = imagerotate($buffer,-90,0);
break;
}
$image = imagejpeg($buffer, $path, 90);
}
}
if(empty($posted)){
$posted = 'Anonim';
}
$sql = "INSERT INTO problems(title, content, date, image, posted, ip) VALUES (:title, :content, :date, :image, :posted, :ip)";
$query = $db->prepare($sql);
$results = $query->execute(array(
':title' => htmlentities ($title),
':content' => htmlentities ($content),
':date' => $date,
':image' => $path,
':posted' => htmlentities ($posted),
':ip' => $ip
));
echo "<div id='ok'>Lajmi u raportua me sukses. Kontrollojeni <a href='index.php'>ketu</a> .</div>";
}
}else{
//set that to be the returned message
echo 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
}
?>
Problem:
after the file is validated, its not going into the db.
Solution
That's because your $path is undefined when you try to insert record into the database. Move the $path variable outside of the if(isset($orientation_data) && $orientation_data !== 1){ ... } block, like this:
// your code
$path = "images/". $new_file_name; // moved this outside of the if block
if(isset($orientation_data) && $orientation_data !== 1){
$buffer = ImageCreateFromJPEG($path);
$exif = exif_read_data($path);
if(!empty($exif['Orientation'])){
switch($exif['Orientation']){
case 8:
$buffer = imagerotate($buffer,90,0);
break;
case 3:
$buffer = imagerotate($buffer,180,0);
break;
case 6:
$buffer = imagerotate($buffer,-90,0);
break;
}
$image = imagejpeg($buffer, $path, 90);
}
}
// your code

how can I add imaging handling got this script effectively

hopefully someone can help me here. been up all night browsing and nothing I try seems to work, but im new to php so im slow. I need to upload 6 images, and this works great. but then I realized you can upload not only images but all other file types. Im trying to be able to limit it to just images under 100kb each. heeeeelllllllpppppp!!!! please!
function findexts ($filename) { $filename = strtolower('$filename') ;
$exts = preg_split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
$ext = findexts ($_FILES['images']['name']) ;
$ran = rand ();
$ran2 = $ran.".";
while(list($key,$value) = each($_FILES['images']['name']))
{
if(!empty($value))
{
$filename = $ran.$value;
$filename=str_replace(" "," _ ",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "media/".$ran."$filename";
$insert_query = "INSERT INTO ....VALUES ...";
//echo $_FILES['images']['type'][$key];
// echo "<br>";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
mysql_query($insert_query);
}
}
See the answer to both your questions here:
https://stackoverflow.com/a/9153419/723855
Add this function to your script (modified from link):
function acceptFileUpload($thefile){
if(isset($_FILES[$thefile])) {
$errors = array();
$maxsize = 2097152;
$acceptable = array(
'application/pdf',
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if(($_FILES[$thefile]['size'] >= $maxsize) || ($_FILES[$thefile]["size"] == 0)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
if(!in_array($_FILES[$thefile]['type'], $acceptable)) && (!empty($_FILES[$thefile]["type"]))) {
$errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
}
if(count($errors) !== 0) {
return true;
} else {
foreach($errors as $error) {
echo '<script>alert("'.$error.'");</script>';
return false;
}
die(); //Ensure no more processing is done
}
}
}
Then in your script change your while loop to use this function to check for a valid file:
while(list($key,$value) = each($_FILES['images']['name']))
{
if(!empty($value))
{
if(acceptFileUpload('images'))
{
$filename = $ran.$value;
$filename=str_replace(" "," _ ",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "media/".$ran."$filename";
$insert_query = "INSERT INTO ....VALUES ...";
//echo $_FILES['images']['type'][$key];
// echo "<br>";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
mysql_query($insert_query);
}
}
}
I might not have that parameter right that is getting passed to acceptFileUpload().
Four functions to run on the processing script on each file, if all tests pass then the file meets your conditions and can be safely stored (png / jpg / gif + non-zero + 10Kb limit + is uploaded file)
//Example Call: checkFileExtension($_FILES['fieldname']['name']);
function checkFileExtension($filename) {
$filename = strtolower($filename) ;
$filenamePartsArray = preg_split("[/\\.]", $filename) ;
$extension = $filenamePartsArray[count($filenamePartsArray) - 1];
if (($extension == 'gif') || ($extension == 'jpeg') || ($extension == 'jpg') || ($extension == 'png')) {
return true;
} else {
return false;
}
}
//Example Call: checkFileMIME($_FILES['fieldname']['type']);
function checkFileMIME($filetype) {
if (($filetype == 'image/png') || ($filetype == 'image/jpeg') || ($filetype == 'image/gif')) {
return true;
} else {
return false;
}
}
//Example Call: checkFileSize($_FILES['fieldname']['size'], 10);
function checkFileSize($filesize, $limitKb = 0) {
if ($filesize == 0) {
return false;
}
if ($limitKb != 0) {
if ($filesize > ($limitKb * 1024)) {
return false;
}
}
return true;
}
//Native Call: is_uploaded_file($_FILES['fieldname']['tmp_name']);
Edit: pseudo example use
foreach ($_FILES as $fieldname => $file) {
if ((checkFileExtension($file['name'])) && (checkFileMIME($file['type'])) && (checkFileSize($file['size'], 10)) && (is_uploaded_file($file['tmp_name']))) {
//Move the image with move_uploaded_file
//Save the file location with DB insert
}
}
you can check the file type with
$_FILES['image']['type']
or if you want to check the extension too
$extension = explode('.',(string)$_FILES['image']['name']);
//then check if its "jpg", "gif" or "png"
the file size can be checked with
$_FILES['image']['size']
so your script should be like this for each of your image updates:
$extension = explode('.',$_FILES['image']['name']);
$imgextensions = array();
$size = $_FILES['image']['size'];
if(($extension == 'jpg' || $extension == 'gif' || $extension == 'png') &&
$size < 100000 ){
// upload your file to your filesystem
}else{
//inform the user
}

Extend variable from one function to another

I'm having an image upload function I did create for few weeks ago - it has an variable called $newname, which contains the path and file.
I'm then using the imageupload() function in another function called EditFrontPage(), which is used to 'update' some content.
If I update the image, it runs the imageupload function, which is great, it resize and optimize the image, and it moves it to the folder I specified.
What I then want, is within' my EditFrontPage() function, is to echo out the $newname variable from the imageUpload function.
is there a way to do this? in a smart way? :D
Here is my code:
<?php
function EditFrontPage($db)
{
$stmt = $db->prepare("SELECT `id`, `heading`, `content`, `image` FROM `content` WHERE `page` = 'forside';");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(isset($_POST['EditFrontpageSubmit']))
{
imageUpload(10000, 100, 100, '', 5);
global $newname;
echo $newname;
}
?>
<form class="adminForm" enctype="multipart/form-data" action="" method="post">
<h2>Overskrift</h2>
<input type="text" value="<?=$row['heading']?>" />
<input type="file" name="image[]" />
<h2>Tekst</h2>
<textarea><?=br2nl($row['content'])?></textarea>
<input type="submit" name="EditFrontpageSubmit" value="Opdater nyhed" />
</form>
<?php
}
function imageUpload($maxsize = 2000, $quality = 95, $imgwidth = 400, $imgheight = '', $numOfImages = 5, $path = '/lucas/images/')
{
// Turn on error reporting
error_reporting(-1);
//Set the max upload size in kilobytes
define("MAX_SIZE", "$maxsize");
if(empty($imgheight) && empty($imgwidth))
{
echo "<h1>Fejl: Definer bredde eller højde</h1>";
die();
}
//Makes a function that check the extension
function getExtension($str){
$i = strrpos($str, ".");
if(!$i){return "";}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//Set errors to 0 from standard
$errors = 0;
//Define the size as a variable
$size = '';
//foreach image selected
foreach($_FILES['image']['error'] as $key => $error)
{
//If no errors, return true
if($error == UPLOAD_ERR_OK)
{
//Gets the filename
$filename = stripslashes($_FILES['image']['name'][$key]);
//Gets the extension
$extension = getExtension($filename);
//convert the extension to lowercase
$extension = strtolower($extension);
//if the file extension doesn't match, return error
if(($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
echo "<h1>Unknown Extension!</h1>";
$errors = 1;
}
//This check if the amount of images is over 5.
elseif(count($_FILES['image']['name']) > $numOfImages)
{
//If it's over 5 images, return error and exit
echo "Too many images";
exit();
}
else
{
//Get the filesize of the image (total amount if multiple images).
$size += filesize($_FILES['image']['tmp_name'][$key]);
//if the filesize is over the defined amount
if($size > MAX_SIZE*1024)
{
echo "<h1>Du har overskredet maksimum fil-upload størrelse!</h1>";
$errors = 1;
}
//This renames the image, to contain, the microtime, and a unique ID + extension
$image_name = microtime(true) . uniqid('',true) . '.' . $extension;
//This sets the path of the image.
$newname = $_SERVER['DOCUMENT_ROOT'] . $path . $image_name;
//It moves the file(s) to the path defined above!
$copied = move_uploaded_file($_FILES['image']['tmp_name'][$key], $newname);
//Check if the extension is png
//if($extension == "png")
//{
//converts the quality from 'jpeg/gif' quality to png compression method
//$pngquality = round($quality/100 * 9);
//Executes a shell command optimizing the png
//shell_exec("gm mogrify -quality $pngquality -thumbnail ". $imgwidth ."x". $imgheight ."\> $newname $newname");
//}
//else
//Executes a shell command optimizing the jpeg/gif
//shell_exec("gm mogrify -quality $quality -thumbnail ". $imgwidth ."x". $imgheight ."\> $newname $newname");
//If the image isn't copied, return an error
if(!$copied)
{
echo "<h1>Der skete en fejl!</h1>";
$errors = 1;
}
//Creates an array of the images
$array[] = $newname;
}
}
}
//If the submit is set, and errors = 0 return true
if(isset($_POST['Submit']) && $errors != 1)
{
echo "<h1>Fil blev uploaded som den skulle!</h1>";
//Makes a for loop, that echo's out all uploaded images
for($i = 0; $i < count($array); $i++)
{
echo "<img src='{$array[$i]}' /><p>".preg_replace("/.*\//i", '', $array[$i])."</p>";
}
}
}
?>
Thank you a lot guys!
Have the imageupload() function return the $newname variable, and then set it like so on the EditFrontPage() function:
$newName = imageUpload(10000, 100, 100, '', 5);
just return $newname at the end of imageUpload function and modify this part:
if(isset($_POST['EditFrontpageSubmit']))
{
echo imageUpload(10000, 100, 100, '', 5);
}

php resize images script

I am using directory iterator to iterate through directories and resize images found in that directory, I am doing this from browser cause I don't have ssh access to that server.
Most pictures resize fine but for every 10 pictures (more or less) I get jiberish data out.
I think it's a picture source. in that data there is always a string CREATOR: gd-jpeg v1.0 so I'm wondering what is this? I disabled any error output with # sign.
EDIT:
Here is the code, and also I disabled error output cause there aren't any errors and I thought that disabling error output would disable this jiberish data, but data is displayed no matter.
Code:
<?php
/*
big = 350
thumb = 90
thumb2 = 70
top = 215
*/
set_time_limit(0);
ini_set('memory_limit', '128M');
ini_set('display_errors', 'On');
class ResizeImages
{
private $dir = 'images/articles_backup_2009-12-19';
private $imageType = array(
'_big' => 'h:350',
'_thumb' => 'm:90',
'_thumb2' => 'h:70',
'_top' => 'h:215'
);
public function __construct()
{
$this->deleteImages();
$this->resizeImages();
}
private function resizeImages()
{
$n = 0;
$dh = opendir($this->dir);
while (($file = readdir($dh)) !== false)
{
if(is_dir($this->dir."/".$file) && $file != '.' && $file != '..')
{
echo $this->dir."/".$file.'<br />';
$deldir = opendir($this->dir."/".$file);
while (($filedel = readdir($deldir)) !== false)
{
if ($filedel != '.' && $filedel != '..' && $filedel != 'Thumbs.db')
{
$val = $this->resize($this->dir."/".$file."/".$filedel);
$n++;
}
}
}
}
closedir($dh);
}
private function resize($target)
{
$img = $target;
$origSize = getimagesize($img);
$origWidth = $origSize[0];
$origHeight = $origSize[1];
foreach($this->imageType as $key=>$value)
{
$attr = explode(':', $value);
if(strpos($attr[0], 'w') !== false)
{
$this->imageWidth = $attr[1];
$this->imageHeight = false;
}
if(strpos($attr[0], 'h') !== false)
{
$this->imageHeight = $attr[1];
$this->imageWidth = false;
}
$imageTmp = explode('.', $img);
if(count($imageTmp) == 2) $image_name_fin = $imageTmp[0].$key.'.'.$imageTmp[1];
else if(count($imageTmp) == 4) $image_name_fin = $imageTmp[0].'.'.$imageTmp[1].$key.'.'.$imageTmp[2];
if($this->imageWidth != false)
{
if($origWidth <= $this->imageWidth)
{
$resizeHeight = $origHeight;
$resizeWidth = $origWidth;
}
else
{
$resizeHeight = round($origHeight / ($origWidth / $this->imageWidth));
$resizeWidth = $this->imageWidth;
}
}
else if($this->imageHeight != false)
{
if($origHeight <= $this->imageHeight)
{
$resizeHeight = $origHeight;
$resizeWidth = $origWidth;
}
else
{
$resizeWidth = round($origWidth / ($origHeight / $this->imageHeight));
$resizeHeight = $this->imageHeight;
}
}
$im = ImageCreateFromJPEG ($img) or // Read JPEG Image
$im = ImageCreateFromPNG ($img) or // or PNG Image
$im = ImageCreateFromGIF ($img) or // or GIF Image
$im = false; // If image is not JPEG, PNG, or GIF
if (!$im)
{
$this->error = array(
'error' => true,
'notice' => 'UPLOADUNSUCCESSFULL'
);
return $this->error;
}
$thumb = ImageCreateTrueColor ($resizeWidth, $resizeHeight);
ImageCopyResampled ($thumb, $im, 0, 0, 0, 0, $resizeWidth, $resizeHeight, $origWidth, $origHeight);
ImageJPEG ($thumb, $image_name_fin, $this->imageQuality);
//echo $image_name_fin.'<br />';
}
$this->error = array(
'imageUrl' => $image_name,
'error' => false,
'notice' => 'IMAGEUPLOADED'
);
return $this->error;
}
private function deleteImages()
{
$dh = opendir($this->dir);
while (($file = readdir($dh)) !== false)
{
if(is_dir($this->dir."/".$file))
{
//echo $file.'<br />';
$deldir = opendir($this->dir."/".$file);
while (($filedel = readdir($deldir)) !== false)
{
if(strpos($this->dir."/".$file."/".$filedel, '_big.') !== false || strpos($this->dir."/".$file."/".$filedel, '_thumb.') !== false || strpos($this->dir."/".$file."/".$filedel, '_thumb2.') !== false || strpos($this->dir."/".$file."/".$filedel, '_top.') !== false)
{
unlink($this->dir."/".$file."/".$filedel);
}
}
}
}
closedir($dh);
}
}
$batch = new ResizeImages;
?>
At the top add this:
error_reporting(E_ALL);
And try changing this:
$im = ImageCreateFromJPEG ($img) or // Read JPEG Image
$im = ImageCreateFromPNG ($img) or // or PNG Image
$im = ImageCreateFromGIF ($img) or // or GIF Image
$im = false; // If image is not JPEG, PNG, or GIF
To this:
$im = ImageCreateFromString(file_get_contents($img));
Did it help? Also is there any pattern on the corrupted images? Are they all of the same type?
Well, the first thing would be to remove the error suppression to see if there is any errors. Seeing some of your code could be helpful as well.
EDIT
Ok, too late to fix your problem, but here is another suggestion for your code. All that "readdir, decide if file, build path" stuff is just a pain to use (and look at). Try this for an alternative:
class ImageFilterIterator extends FilterIterator
{
public function accept()
{
$ext = pathinfo($this->current()->getRealPath(), PATHINFO_EXTENSION);
return stripos('.gif|.jpg|.png', $ext);
}
}
$path = '.';
$images = new ImageFilterIterator(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path)));
Iterators are from the SPL and while they are somewhat puzzling to use at first, they can make development much easier once you understood them. With the above you can now loop over $image and get all filenames ending in .gif, .jpg or .png from all directories below path, like this:
foreach($images as $image) {
echo $image;
}
In fact, $image is not just a string, but an SplFileInfo object, so you also get a bunch of useful other methods with it.

Categories