Islam Linarez
Islam Linarez

Reputation: 169

Resize images with (4:3) PHP

In the page I manage, the user can upload an image of any in dimension, being no more than 1 MB of space. I want to resize the image relative to 240x180 px but without breaking the aspect ratio of the image (or at least that it will not be greatly distorted). My current code only changes the image forcefully:

$img = imagecreatetruecolor ($width, $height);
imagecopyresampled ($img, $original_img, 0,0,0,0, $width, $height, $wimg, $h_img);

I want to generate an image (when it is the case) with the same aspect of relation that is loaded, but less than $width and $height target, and what remains fill with black margo.

"It's like I have the black background and place the image centered on the"

Upvotes: 0

Views: 394

Answers (1)

nithinTa
nithinTa

Reputation: 1642

If my understanding is correct, this will give the values for imagecopyresampled

<?php

$x = 1000 ; //sample width
$y = 768 ;  //sample height

$ratio = 4/3;
$newRatio = $x/$y ; //ratio of given sample.

$decision = $y * $ratio ;

//height need to be adjusted
if( $decision < $x ) {

    $width = 240 ;
    $height = 240 / $newRatio ;
}
//width must be adjusted
else if( $decision > $x ) {

    $width = 180 * $newRatio;
    $height = 180  ;
}
//already in proportion
else {
    $width = 240 ;
    $height = 180 ;
}

$dst_w = floor($width) ;
$dst_h = floor($height) ;

//give half of the total margin to left and top.
$dst_x = floor( (240 - $dst_w) / 2 ) ;
$dst_y = floor( (180 - $dst_h) / 2 ) ;

echo "Width & Height:" . $dst_w . ' x ' . $dst_h ;
echo "<br/>";
echo "Dst X & Y :" .$dst_x . ' x ' . $dst_y ;

Upvotes: 1

Related Questions