Reputation: 473
I'm uploading images with HTML and PHP.
<form action="" method="post">
<input type="file" name="image" id="image">
</form>
How would I use imagemagick to resize the image if it is larger than 1500(width)x700(height) whichever is larger comes first, then reside the image.
As far as I looked for, imagemagick can only resize images after upload. Is it possible to resize images while upload and then store into directory/folder?
Upvotes: 1
Views: 349
Reputation: 81
You can resize the temp file then save the file after it is completed.
Here is how I typically handle it.. PLEASE NOTE YOU NEED TO DO A LOT MORE WITH SECURING THIS UP! Make sure you are checking the upload allowed type, size ect..
I use this function to resize..
function img_resize($target, $newcopy, $w, $h, $ext) {
list($w_orig, $h_orig) = getimagesize($target);
$scale_ratio = $w_orig / $h_orig;
if (($w / $h) > $scale_ratio) {
$w = $h * $scale_ratio;
} else {
$h = $w / $scale_ratio;
}
$img = "";
$ext = strtolower($ext);
if ($ext == "gif"){
$img = imagecreatefromgif($target);
} else if($ext =="png"){
$img = imagecreatefrompng($target);
} else {
$img = imagecreatefromjpeg($target);
}
$tci = imagecreatetruecolor($w, $h);
// imagecopyresampled(dst_img, src_img, dst_x, dst_y, src_x, src_y, dst_w,
dst_h, src_w, src_h)
imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig);
imagejpeg($tci, $newcopy, 80);
}
Then I call the function with the temp file..
$fileName = $_FILES["image"]["name"]; // The file name
$target_file = $_FILES["image"]["tmp_name"];
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
$fname = $kaboom[0];
$exten = strtolower($fileExt);
$resized_file = "uploads/newimagename.ext"; //need to change this make sure you set the extension and file name correct.. you will want to secure things up way more than this too..
$wmax = 1500;
$hmax = 700;
img_resize($target_file, $resized_file, $wmax, $hmax, $exten);
Upvotes: 1