daugaard47
daugaard47

Reputation: 1868

resize width and compress images on upload php mysql

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!

Upvotes: 1

Views: 10525

Answers (2)

Mike Q
Mike Q

Reputation: 7327

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);

                }


            }

Upvotes: 0

tyler
tyler

Reputation: 1293

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

Upvotes: 4

Related Questions