Reputation: 25
I have been banging my head for hours and hours and I CAN NOT for the life of me figure out how to resize an image with same ratio on upload with a simple form. If someone upload a larger image than 2048px horizontal or vertical I want to resize it to a size of 2048px and then save it in a folder.
Since I'm basically back to scratch with only my form I got nothing to show you unfortunately but mostly been searching and reading about GD but doesn't work for me...
Any tips are very much appreciated!
EDIT:
if(isset($con, $_POST['save_button'])){
// IMAGE PROCESSING
$name = $_FILES['file_upload']['name'];
$tmp_name = $_FILES['file_upload']['tmp_name'];
$type = $_FILES['file_upload']['type'];
$size = $_FILES['file_upload']['size'];
$error = $_FILES['file_upload']['error'];
move_uploaded_file($tmp_name, "social_images/$name.jpg");
function resize_image($img, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($img);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*abs($r-$w/$h)));
} else {
$height = ceil($height-($height*abs($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
$src = imagecreatefromjpeg($img);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
$img = resize_image("social_images/$name.jpg", 780, 780);
header("location: index.php");
exit();
}
Upvotes: 0
Views: 418
Reputation: 445
Freshly retried and retested:
<?php
function shazam($file, $w, $h) {
list($width, $height) = getimagesize($file);
if ($width > $height) {
$r = ($w / $width);
$newwidth = $w;
$newheight = ceil($height * $r);
}
if ($width < $height) {
$r = ($h / $height);
$newheight = $h;
$newwidth = ceil($width * $r);
}
if ($width == $height) {
$newheight = $h;
$newwidth = $w;
}
$src = imagecreatefromjpeg($file);
$tgt = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($tgt, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $tgt;
}
$img = shazam("thepicwithpath.jpg", 850, 850);
imagejpeg($img, "theresizedpicwithpath.jpg", 75);
?>
Note that the imagejpeg() at the end is what actually produces the new file.
Upvotes: 2