Search code examples
phpfile-uploadimage-resizingautoresize

Auto Resize the image in PHP


I want to auto resize the image while uploading.I have wondered many site but in every site users have put the new-width and new-height for all the images but i want auto resize becasue problem is when user will upload same dimension image then we will easily cut but when user upload landscape or portrait dimension image then image will messed and cut wrong dimensions. So i am facing this issue.


Solution

  • In auto resize case this may be helpful.i am using this code in my oproject 
    
    list($originalWidth, $originalHeight) = getimagesize($imageFile);
    $ratio = $originalWidth / $originalHeight;
    
    
    $targetWidth = $targetHeight = min($size, max($originalWidth, $originalHeight));
    
    if ($ratio < 1) {
        $targetWidth = $targetHeight * $ratio;
    } else {
        $targetHeight = $targetWidth / $ratio;
    }
    
    $srcWidth = $originalWidth;
    $srcHeight = $originalHeight;
    $srcX = $srcY = 0;
    
    
    $targetWidth = $targetHeight = min($originalWidth, $originalHeight, $size);
    
    if ($ratio < 1) {
        $srcX = 0;
        $srcY = ($originalHeight / 2) - ($originalWidth / 2);
        $srcWidth = $srcHeight = $originalWidth;
    } else {
        $srcY = 0;
        $srcX = ($originalWidth / 2) - ($originalHeight / 2);
        $srcWidth = $srcHeight = $originalHeight;
    }
    
    $targetImage = imagecreatetruecolor($targetWidth, $targetHeight);
    imagecopyresampled($targetImage, $originalImage, 0, 0, $srcX, $srcY, $targetWidth, $targetHeight, $srcWidth, $srcHeight);