1

I have a client that sends me text messages from his iPhone with images for me to upload into his gallery. I'm trying to create a admin system so I can simply take the images from the texts, go to the admin page on my iPhone and upload the images straight to the gallery.

This would save me tons of time in my day to day work schedule.

Using the provided code. How can I add the following functions:

  1. I would like to compress the file size down to a smaller size if possible, similar to the save to web jpg function in Photoshop. (Most images I get are around 1-3 MB. I would like to get them down to around 150-500kb max)

  2. I would like to automatically change the width to 760px, but keep the aspect ratio so the images are not squished. He sends me landscape and portrait images.

  3. Beings they are iPhone images. They have an extension .JPG (all caps) I would like this to change to .jpg (all lower case.) This is not a deal breaker I would just like to know how to do this for future use.

Either one of these functions would be very helpful, but all 3 would be ideal for my situation.

Here is the code I'm working with?

THIS IS THE FINAL CORRECT CODE FOR UPLOADING AND RESIZING IMAGES PROVIDED By @tman Make sure you have imagick installed in your php.ini file. Check with your hosting provider to install it.

<?php
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");



for($i=0;$i<count($_FILES["image"]["name"]);$i++){
if($_FILES["image"]["name"][$i] != ''){ // don't insert if file name empty
$dataType = mysql_real_escape_string($_POST["dataType"][$i]);
$title = mysql_real_escape_string($_POST["title"][$i]);

$fileData = pathinfo($_FILES["image"]["name"][$i]);
$fileName = uniqid() . '.' . $fileData['extension'];
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $fileName;

if (move_uploaded_file($_FILES["image"]["tmp_name"][$i], $target_path)){ // The file is in the images/gallery folder.
// Insert record into database by executing the following query:
$sql="INSERT INTO images (data_type, title, file_name) "."VALUES('$dataType','$title','$fileName')";
$retval = mysql_query($sql);


///NEW

$size = getimagesize($target_path);
$width=$size[0];

$height=$size[1]; 
$newwidth = 760;
$newheight = $height*($newwidth/$width);
$pic = new Imagick($target_path);//specify name
$pic->resizeImage($newwidth,$newhight,Imagick::FILTER_LANCZOS,1);
unlink($target_path);
$pic->writeImage($target_path);
$pic->destroy();
///NEW


echo "The image {$_FILES['image']['name'][$i]} was successfully uploaded and added to the gallery<br />
<a href='index.php'>Add another image</a><br />";
}
else
{
echo "There was an error uploading the file {$_FILES['image']['name'][$i]}, please try again!<br />";
}
}
} // close your foreach
?>

uploader.php Original code. Allows me to upload 4 images at once. WORKS!!!

<?php
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");

for($i=0;$i<count($_FILES["image"]["name"]);$i++){
  if($_FILES["image"]["name"][$i] != ''){ // don't insert if file name empty
    $dataType = mysql_real_escape_string($_POST["dataType"][$i]);
    $title = mysql_real_escape_string($_POST["title"][$i]);

    $fileData = pathinfo($_FILES["image"]["name"][$i]);
    $fileName = uniqid() . '.' . $fileData['extension'];
    $target_path = $_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $fileName;

  if (move_uploaded_file($_FILES["image"]["tmp_name"][$i], $target_path)){    // The file is in the images/gallery folder. 
    // Insert record into database by executing the following query:
     $sql="INSERT INTO images (data_type, title, file_name) "."VALUES('$dataType','$title','$fileName')";
     $retval = mysql_query($sql);

    echo "The image {$_FILES['image']['name'][$i]} was successfully uploaded and added to the gallery<br />
     <a href='index.php'>Add another image</a><br />";
  }
  else
  {
   echo "There was an error uploading the file {$_FILES['image']['name'][$i]}, please try again!<br />";
    }
  }
} // close your foreach
?>

FYI, This will allow you to give a unique names to your images, resize the width, but keep the correct aspect ratio and upload multiple file at the same time.

Awesome Stuff!

daugaard47
  • 1,726
  • 5
  • 39
  • 74
  • 1
    You need to define `fit_image_file_to_width()`. – Pekka Jul 15 '13 at 06:04
  • it would be much easier to set this up with an email address that who ever just sends an email with the pics to an address. You could run a cron job to automatically upload the files and now your always working when your not and your free to do something else :) – tyler Jul 15 '13 at 06:07
  • can you explain in a little more detail. I tried changing $type to $_FILES but that didn't work. Sorry very new at this. – daugaard47 Jul 15 '13 at 06:09
  • fit_image_file_to_width means nothing in your current code. You need to define this in a function. My guess is you grabbed this code thinking it did it all! go back they probably define the function else where – tyler Jul 15 '13 at 06:10
  • @tman I like the email solution, but thats way over my head at the moment. do you know of any tuts that can explain that process. Also, how would I define that function? – daugaard47 Jul 15 '13 at 06:13
  • you ask and you receive wooooshhhhhh~ – tyler Jul 15 '13 at 06:14

2 Answers2

4

Like this:

$filelocation='http://help.com/images/help.jpg';
$newfilelocation='http://help.com/images/help1.jpg';

$size = getimagesize($filelocation);
$width=$size[0];//might need to be ['1'] im tired .. :)
$height=$size[1];
// Plz note im not sure of units pixles? & i could have the width and height   confused
//just had some knee surgery so im kinda loopy :) 
$newwidth = 760;
$newheight = $height*($newwidth/$width) 


 $pic = new Imagick( $filelocation);//specify name
 $pic->resizeImage($newwidth,$newhight,Imagick::FILTER_LANCZOS,1);
 //again might have width and heing confused
 $pic->writeImage($newfilelocation);//output name
 $pic->destroy();
 unlink($filelocation);//deletes image
tyler
  • 1,273
  • 2
  • 16
  • 40
  • Awesome thank you for being so kind. Okay so I have an understanding of this code. How would I set it to create 760 width? – daugaard47 Jul 15 '13 at 06:15
  • 1
    Well to be fair http://stackoverflow.com/questions/7553247/php-image-resizing .....read that post if you still need help im here :) – tyler Jul 15 '13 at 06:20
  • Your not doing too bad being that you have only been working on it a month! this is a difficult task to achieve as a beginner...Best of luck! – tyler Jul 15 '13 at 06:26
  • Okay I'm trying to do this fast as It's getting late and I got to be at work in the morning, but I dont want to lose your guidance. Bases off the link you provided I updaated my code, but not working. It uploads the image but no width resize and throughs up a bunch of errors. – daugaard47 Jul 15 '13 at 06:35
  • ERRORS: Notice: Undefined index: photo in C:\xampp\htdocs\bgtree.com\admin\uploader.php on line 28 Notice: Undefined index: photo in C:\xampp\htdocs\bgtree.com\admin\uploader.php on line 29 Notice: Undefined index: photo in C:\xampp\htdocs\bgtree.com\admin\uploader.php on line 30 Notice: Undefined index: photo in C:\xampp\htdocs\bgtree.com\admin\uploader.php on line 31 Warning: getimagesize(): Filename cannot be empty in C:\xampp\htdocs\bgtree.com\admin\uploader.php on line 6 Warning: Division by zero in C:\xampp\htdocs\bgtree.com\admin\uploader.php on line 8 – daugaard47 Jul 15 '13 at 06:36
  • have u tested without the change width function? – tyler Jul 15 '13 at 06:42
  • Not sure what you mean..? I took out fit_image_file_to_width($temp_name, 760, $type); I get these erros: Notice: Undefined index: photo in C:\xampp\htdocs\bgtree.com\admin\uploader.php on line 57 Notice: Undefined index: photo in C:\xampp\htdocs\bgtree.com\admin\uploader.php on line 58 Notice: Undefined index: photo in C:\xampp\htdocs\bgtree.com\admin\uploader.php on line 59 Notice: Undefined index: photo in C:\xampp\htdocs\bgtree.com\admin\uploader.php on line 60 I also added JPG to the extension. `case 'image/gif'; $src = imagecreatefromgif($file); break;` – daugaard47 Jul 15 '13 at 06:47
  • 1
    http://php.net/manual/en/imagick.resizeimage.php didnt even know this existed should help alot – tyler Jul 15 '13 at 06:48
  • can you upload images yet? Does your code function except for the re-sizing or could we be dealing with multiple types of errors ie not just from trying to upload – tyler Jul 15 '13 at 06:49
  • Yea the images upload fine. Just not resizing the width to 760px w – daugaard47 Jul 15 '13 at 06:52
  • just uploaded 4 images successfully but no resize. – daugaard47 Jul 15 '13 at 06:54
  • ok if you could post the code above that uploads the file! remove anything that is considered non working. I want to see exactly what you have working – tyler Jul 15 '13 at 06:55
  • okay I provided the original code and the code I'm currently trying to resize with. – daugaard47 Jul 15 '13 at 07:01
  • is resizing after uploaded an option or do you need to do it prior to upload – tyler Jul 15 '13 at 07:02
  • Doesn't matter to me. I'm not educated enough on the matter to give you a straight answer, but I dont really want to store the images in the data base, rather just the file names. Just an FYI I have add a unique id function to give a random name to the images do to iPhones naming each photo image. – daugaard47 Jul 15 '13 at 07:05
  • 1
    so you have 2 options upload the full size and then resize it ... `$pic = new Imagick('myimage.gif');//specify name $pic->resizeImage(320,240,Imagick::FILTER_LANCZOS,1);//just change the 320 and 240 $pic->writeImage('resized.gif');//output name $pic->destroy(); ` and then we could add some code to delete it ...option 2 is use the power of the iphone an app that resizes https://itunes.apple.com/us/app/simple-resize/id327776379?mt=8 this would make your upload time faster for obvious reasons – tyler Jul 15 '13 at 07:06
  • So do I have to specify the height? I would like the height to be auto generated by the 760px width...? – daugaard47 Jul 15 '13 at 07:08
  • I mean for option 1 the Imagick. Would i have to specify the height. – daugaard47 Jul 15 '13 at 07:15
  • you may have to but we can do some math to ensure its correct ... for example grab the height and width of uploaded find original width/760px is equal to height/x we solve for x and we are done ... – tyler Jul 15 '13 at 07:15
  • x is equal to height*(760px/width) where x is your new height for the scaled image – tyler Jul 15 '13 at 07:18
  • can you get the height and width or ya need help? – tyler Jul 15 '13 at 07:18
  • looks like most are 1600 x 1200 and 1200 x 1600, but this could change if he uses a different setting such as HDR while taking the pics – daugaard47 Jul 15 '13 at 07:19
  • wont matter we can get dimensions with php – tyler Jul 15 '13 at 07:19
  • hold on ill be back woooshhhh! – tyler Jul 15 '13 at 07:21
  • check it out... think that should do it – tyler Jul 15 '13 at 07:28
  • Warning: getimagesize(help.com/images/help.jpg): failed to open stream: No such file or directory in C:\xampp\htdocs\bgtree.com\admin\uploader.php on line 7 Warning: Division by zero in C:\xampp\htdocs\bgtree.com\admin\uploader.php on line 13 Fatal error: Class 'Imagick' not found in C:\xampp\htdocs\bgtree.com\admin\uploader.php on line 16 – daugaard47 Jul 15 '13 at 07:33
  • I added the latest code I'm using at the top of the page. Sorry man not understanding...=( – daugaard47 Jul 15 '13 at 07:36
  • '$size = $etimagesize('http://redwirelogic.com/images/redwire_logo.png'); echo $size[1];' You need you put the enire file path http:// everything – tyler Jul 15 '13 at 07:38
  • made a big mistake on the size.. should be $size[0] and size[1] – tyler Jul 15 '13 at 07:43
  • Warning: Division by zero in C:\xampp\htdocs\bgtree.com\admin\uploader.php on line 13 Fatal error: Class 'Imagick' not found in C:\xampp\htdocs\bgtree.com\admin\uploader.php on line 16 – daugaard47 Jul 15 '13 at 07:44
  • u havent uploaded yet ... we need to run the get size after its uploaded – tyler Jul 15 '13 at 07:45
  • updated the latest code again check it at top of page. what am i missing besides a brain here. lol – daugaard47 Jul 15 '13 at 07:47
  • move all the re-sizing to the end except for the line that defines the files location – tyler Jul 15 '13 at 07:48
  • move to bottom`$size = getimagesize('http://dev.bgtree.com/images/gallery/'); $width=$size[0];//might need to be ['1'] im tired .. :) $height=$size[1]; // Plz note im not sure of units pixles? & i could have the width and height confused //just had some knee surgery so im kinda loopy :) $newwidth = 760; $newheight = $height*($newwidth/$width); $pic = new Imagick( $filelocation);//specify name $pic->resizeImage($newwidth,$newhight,Imagick::FILTER_LANCZOS,1); //again might have width and heing confused $pic->writeImage($newfilelocation); $pic->destroy(); unlink($filelocation);` – tyler Jul 15 '13 at 07:50
  • because you want to upload more then 1 at a time you need to embed that string of code into the for loop right after you echo that its successful... its easy but i feel like your just plug code in and asking why dont it work... its only going to do what you tell it... take your time you have everything you need now to do it – tyler Jul 15 '13 at 07:56
  • Okay I updated the latest code at the top of the page, If you dont mind take another look and if you could point out the error. I really do apreciate your help and kindness, I'm trying to learn this stuff as fast as possible due to a current situation im in. But I admit I do tent to plug and play to much. I'll take a good look at this in the morning. Again thank you for the help. – daugaard47 Jul 15 '13 at 08:04
  • FYI : latest errors: The image IMG_0806.JPG was successfully uploaded and added to the gallery Add another image Notice: Undefined variable: filelocation in C:\xampp\htdocs\bgtree.com\admin\uploader.php on line 30 Warning: getimagesize(): Filename cannot be empty in C:\xampp\htdocs\bgtree.com\admin\uploader.php on line 30 Warning: Division by zero in C:\xampp\htdocs\bgtree.com\admin\uploader.php on line 33 Fatal error: Class 'Imagick' not found in C:\xampp\htdocs\bgtree.com\admin\uploader.php on line 33 – daugaard47 Jul 15 '13 at 08:05
  • 1
    yes it would say : Filename cannot be empty in ...make it say ` getimagesize($_FILES['image']['name'][$i])` and move all the lines associated with resizong above this line echo "The image {$_FILES['image']['name'][$i]} was successfully uploaded and added to the gallery
    Add another image
    ";
    – tyler Jul 15 '13 at 08:09
  • and while your at it you could +1 this answer for my continual effort – tyler Jul 15 '13 at 08:19
  • Still not working ,but I'll figure it out. Sooo tired. Thank you again. What needs to go here in this error? Fatal error: Class 'Imagick' not found in C:\xampp\htdocs\bgtree.com\admin\uploader.php on line 23 – daugaard47 Jul 15 '13 at 08:23
  • are you running on your own server? – tyler Jul 15 '13 at 08:25
  • Would i add this to it `($_FILES['image']['name'][$i])` – daugaard47 Jul 15 '13 at 08:25
  • Yes running of xampp local host dev – daugaard47 Jul 15 '13 at 08:26
  • well the Imagick is not recognized by your set up! you will need to find an alternative like the first try ...Im going to bed now my self. Feel free to contact me tom – tyler Jul 15 '13 at 08:29
  • 1
    let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/33472/discussion-between-tman-and-daugaard47) – tyler Jul 15 '13 at 08:31
  • Im in chat the link you provided if your available. – daugaard47 Jul 15 '13 at 19:18
  • ah sweet you think we can go at it again? I got the site live now and installed imagick through my hosting provider, but still not getting the resizing down. – daugaard47 Jul 15 '13 at 22:05
  • Leaving the office now its 5:20 Ill be back in a little bit, could really use your help if you dont mind. – daugaard47 Jul 15 '13 at 22:21
  • yep we can ...just msg me – tyler Jul 15 '13 at 22:27
  • I back just let me know when your ready to go. I'll leave me computer on and I'll be in our chat room. – daugaard47 Jul 16 '13 at 00:15
0

Here is something kind of similar, lets check the size and compress if the image seems that it is too big. I didn't resize it which just requires that you get the dimensions and resize based on desire.

All this is doing is if the file is greater than 250KB compress it to 85% ..

    $bytes = filesize($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);

    //$maxSizeInBytes = 26400; //is 250KB? No? compress it.
    if ($bytes > 26400) {

                $img = new Imagick($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
                $img->setImageCompression(imagick::COMPRESSION_JPEG);
                $img->stripImage();
                $img->setImageCompressionQuality(85);
                $img->writeImage($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);

            }

OR:

            // resize with imagejpeg  ($image, $destination, $quality); if greater than byte size KB
            // Assume only supported file formats on website are jpg,jpeg,png, and gif. (any others will not be compressed)
            $bytes = filesize($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);

            //$maxSizeInBytes = 26400; //is gtr than 250KB? No? compress it.
            if ($bytes > 26400) {

                $info = getimagesize($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
                $quality = 85; //(1-100), 85-92 produces 75% quality 

                if ($info['mime'] == 'image/jpeg') {

                    $image = imagecreatefromjpeg($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
                    imagejpeg($image,$inventory_path.DIRECTORY_SEPARATOR.$this->uploadName,$quality);

                } elseif ($info['mime'] == 'image/gif') { 

                    $image = imagecreatefromgif($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
                    imagejpeg($image,$inventory_path.DIRECTORY_SEPARATOR.$this->uploadName,$quality);

                } elseif ($info['mime'] == 'image/png') { 

                    $image = imagecreatefrompng($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName
                    imagejpeg($image,$inventory_path.DIRECTORY_SEPARATOR.$this->uploadName,$quality);

                }


            }
Mike Q
  • 6,716
  • 5
  • 55
  • 62