Search code examples
phpimageimage-resizingaspect-ratio

How to re-size an image keeping there aspect ratio and upload it


I have a button which uploads a background image to a folder and saves the file name to the database, but I cant figure how to re size the image before uploading it. Actually I am facing two problems. 1 - How to resize the image and upload it. 2 - How to display the image as background image for a div which is having a different dimension.

What I have done till now :

Html

<div class="image_load_div">
 <form id="imageform" enctype="multipart/form-data" method="post" action="upload.php">
   <input name="photoimg" id="photoimg" type="file"/>
 </form>
</div>

javascript

$("#imageform").ajaxForm().submit(); 

php - upload file

$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
   name = $_FILES['photoimg']['name'];
   $size = $_FILES['photoimg']['size'];
   if(strlen($name)) {
 list($txt, $ext) = explode(".", $name);
 if(in_array($ext,$valid_formats)) {
   if($size<(1024*1024)) {
          session_start();
      $id = $_SESSION['QuestionId'];
      $path = "/images/Img/".$id."_bg.".$ext;

          if( move_uploaded_file($_FILES["photoimg"]["tmp_name"],$path) ) {
             // Save the file name into database
          }
        else { echo "<script>alert('Upload failed');</script>"; }
   else { echo "<script>alert('Image file size max 1 MB');</script>"; }                 
    else {  echo "<script>alert('Invalid file format..');</script>"; }  
 else { echo "<script>alert('Please select image..!');</script>";   exit; }

I would like to save the image as height:408px; width:490px; and when displaying the image I want to display this image width:174px; height:108px; IMP !During uploading and when displaying, need to consider the aspect ratio; for now uploading is working.

please help me to solve this. Thanks.


Solution

  • This is working and well tested code. Hope it will work for you.

    Calling methode:

    $newname="xyz";
    $filename=$_FILES['featured-img']['name'];
    $extension=strtolower(substr(strrchr($filename, '.'), 1)); //Get extension
    $extension=trim($extension);
    $newfilename=$newname.$extension;
    $newfilename=preg_replace('/\s+/', '_',$newfilename);
    
    $target1 = "directory_path".$newfilename;
    if(move_uploaded_file($_FILES['featured-img']['tmp_name'],$target1));   
    scaleImage($target1,500, 350, $target1);
    

    Method defination:

    function scaleImage($source_image_path, $maxWidth, $maxHeight, $thumbnail_image_path){
    
    
              list($source_image_width, $source_image_height, $source_image_type) = getimagesize($source_image_path);
        switch ($source_image_type) {
            case IMAGETYPE_GIF:
                $source_gd_image = imagecreatefromgif($source_image_path);
                break;
            case IMAGETYPE_JPEG:
                $source_gd_image = imagecreatefromjpeg($source_image_path);
                break;
            case IMAGETYPE_PNG:
                $source_gd_image = imagecreatefrompng($source_image_path);
                break;
        }
        if ($source_gd_image === false) {
            return false;
        }
        $thumbnail_image_width=$maxWidth;
        $thumbnail_image_height=$maxHeight;
    
    
        $thumbnail_gd_image = imagecreatetruecolor($thumbnail_image_width, $thumbnail_image_height);
        imagecopyresampled($thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height);
        imagejpeg($thumbnail_gd_image, $thumbnail_image_path, 90);
        imagedestroy($source_gd_image);
        imagedestroy($thumbnail_gd_image);
        return true;
    
    
    }