php - Scale down an image to a fixed width and Height with same aspect resolution -
i trying scale down uploaded image fixed , height example: width=200px , height 200px. tried scale down width of image fixed width , calculate new height new width. trying achieve scale down both width , height fixed size width=200px & height =200px
my html:
<form action="do_upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="upload_image"> <br/> <br/> <input type="submit" value="submit"> </form>
do_upload.php:
<?php move_uploaded_file($_files["upload_image"]["tmp_name"], "uploads/" . $_files["upload_image"]["name"]); $image_path = "uploads/" . $_files["upload_image"]["name"]; $src = imagecreatefromjpeg($image_path); list($width, $height) = getimagesize($image_path); $newwidth = 200; $newheight = ($height / $width) * $newwidth; $tmp = imagecreatetruecolor($newwidth, $newheight); imagecopyresampled($tmp, $src, 0, 0,0,0,$newwidth,$newheight, $width, $height); imagejpeg($tmp, "uploads/small.jpeg", 100); imagedestroy($src); imagedestroy($tmp); ?>
this working fine me , scaling down image. kindly guide me how can scale down image (jpeg,png,gif etc) fixed width , height. guide me in direction it. if can explain example or edit code me great. in advance
you can see comment above answer question dimension less 200 , aspect ration. being said, can go ahead , answer question on how scale on either dimension. problem pretty simple.
first determine if existing image has width or height greater dimension. based on that, determine scaling factor image , apply scaling factor both dimensions.
in code might like:
$src = imagecreatefromjpeg($image_path); list($width, $height) = getimagesize($image_path); $max_dimension = 200; if($width >= $height) { // scale on width $scaling_factor = $width / $max_dimension; } else { // scale on height $scaling_factor = $height / $max_dimension; } $new_width = $width / $scaling_factor; $new_height = $height / $scaling_factor;
a more generalized solution let specify rectangle (i.e. different max height , width) within scale might this.
$max_width = 200; $max_height = 150; // determine dimension must scaled fit target size $width_scaling_factor = $width / $max_width; $height_scaling_factor = $height / $max_height; if($width_scaling_factor >= $height_scaling_factor) { $scaling_factor = $width_scaling_factor; } else { $scaling_factor = $height_scaling factor; } $new_width = $width / $scaling_factor; $new_height = $height / $scaling_factor;
Comments
Post a Comment