Question

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.

Was it helpful?

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

OTHER TIPS

You should use those tutorials, but calculate the other value yourself. For example you have an image with a width of 600px and a height of 1200px; and you want it to be 200px width. Calculate it like this:

$newImageWidth = 200;
$imageWidth = 600;
$imageHeight = 1200;
$ratio = $imageHeight / $imageWidth;
$newImageHeight = $newImageWidth * ratio;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top