I'm trying to crop an image when it has been uploaded. So far I've only managed to resize it but if an image is a rectangular shape then the image is squashed which doesn't look nice. I'm trying to get coding that I can use with the function that I currently have to resize. The ones that I'm seeing I have to change my function and I'm hoping not to do that.
Here is my function
function createThumbnail($filename) {
global $_SITE_FOLDER;
//require 'config.php';
$final_width_of_image = 82;
$height = 85;
$path_to_image_directory = $_SITE_FOLDER.'portfolio_images/';
$path_to_thumbs_directory = $_SITE_FOLDER.'portfolio_images/thumbs/';
if(preg_match('/[.](jpg)$/', $filename)) {
$im = imagecreatefromjpeg($path_to_image_directory . $filename);
} else if (preg_match('/[.](gif)$/', $filename)) {
$im = imagecreatefromgif($path_to_image_directory . $filename);
} else if (preg_match('/[.](png)$/', $filename)) {
$im = imagecreatefrompng($path_to_image_directory . $filename);
}
$ox = imagesx($im);
$oy = imagesy($im);
$nx = $final_width_of_image;
$ny = floor($oy * ($final_width_of_image / $ox));
//$ny = $height;
$nm = imagecreatetruecolor($nx, $ny);
imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);
if(!file_exists($path_to_thumbs_directory)) {
if(!mkdir($path_to_thumbs_directory)) {
die("There was a problem. Please try again!");
}
}
imagejpeg($nm, $path_to_thumbs_directory . $filename);
$tn = '<img src="' . $path_to_thumbs_directory . $filename . '" alt="image" />';
$tn .= '<br />Congratulations. Your file has been successfully uploaded, and a thumbnail has been created.';
echo $tn;
}
Here is my function.
<?php
function crop($file_input, $file_output, $crop = 'square',$percent = false) {
list($w_i, $h_i, $type) = getimagesize($file_input);
if (!$w_i || !$h_i) {
echo 'Unable to get the length and width of the image';
return;
}
$types = array('','gif','jpeg','png');
$ext = $types[$type];
if ($ext) {
$func = 'imagecreatefrom'.$ext;
$img = $func($file_input);
} else {
echo 'Incorrect file format';
return;
}
if ($crop == 'square') {
$min = $w_i;
if ($w_i > $h_i) $min = $h_i;
$w_o = $h_o = $min;
} else {
list($x_o, $y_o, $w_o, $h_o) = $crop;
if ($percent) {
$w_o *= $w_i / 100;
$h_o *= $h_i / 100;
$x_o *= $w_i / 100;
$y_o *= $h_i / 100;
}
if ($w_o < 0) $w_o += $w_i;
$w_o -= $x_o;
if ($h_o < 0) $h_o += $h_i;
$h_o -= $y_o;
}
$img_o = imagecreatetruecolor($w_o, $h_o);
imagecopy($img_o, $img, 0, 0, $x_o, $y_o, $w_o, $h_o);
if ($type == 2) {
return imagejpeg($img_o,$file_output,100);
} else {
$func = 'image'.$ext;
return $func($img_o,$file_output);
}
}
?>
And you can call like this
crop($file_input, $file_output, $crop = 'square',$percent = false);
And also resize function if you need.
<?php
function resize($file_input, $file_output, $w_o, $h_o, $percent = false) {
list($w_i, $h_i, $type) = getimagesize($file_input);
if (!$w_i || !$h_i) {
return;
}
$types = array('','gif','jpeg','png');
$ext = $types[$type];
if ($ext) {
$func = 'imagecreatefrom'.$ext;
$img = $func($file_input);
} else {
return;
}
if ($percent) {
$w_o *= $w_i / 100;
$h_o *= $h_i / 100;
}
if (!$h_o) $h_o = $w_o/($w_i/$h_i);
if (!$w_o) $w_o = $h_o/($h_i/$w_i);
$img_o = imagecreatetruecolor($w_o, $h_o);
imagecopyresampled($img_o, $img, 0, 0, 0, 0, $w_o, $h_o, $w_i, $h_i);
if ($type == 2) {
return imagejpeg($img_o,$file_output,100);
} else {
$func = 'image'.$ext;
return $func($img_o,$file_output);
}
}
?>
resize($file_input, $file_output, $w_o, $h_o, $percent = false);
You can use SimpleImage class found here SimpleImage
[edit] Updated version with many more features here SimleImage Updated
I use this when resizing various images to a smaller thumbnail size while maintaining aspect ratio and exact image size output. I fill the blank area with a colour that suits the background for where the image will be placed, this class supports cropping. Explore the methods cutFromCenter and maxareafill.
For example in your code you would not need to imagecreatefromjpeg() you would simply;
Include the class include('SimpleImage.php');
then;
$im = new SimpleImage();
$im->load($path_to_image_directory . $filename);
$im->maxareafill($output_width,$output_height, 0,0,0); // rgb
$im->save($path_to_image_directory . $filename);
I use this class daily and find it very versatile.
Related
so i have this script to upload files, and yes i know it's not secure. Howe ever, My problem right now is that i can upload files named filename.php.jpg. So how can i prevent files like theese to upload? I have used other stuff to stop php files from being executed.
<?php
$maindir = "../alla_bilder/images/";
$maindir_th = "../alla_bilder/images/thumbs/";
$uploaddir = "images/";
$uploaddir_th = "images/thumbs/";
$allowed = array('jpg','jpeg','png');
$notallowed = array('php');
$uploadOk = 1;
$max_size = 5048 * 1024;
while (list ($key, $val) = each ($_FILES))
{
if ($_FILES[$key]['size'] <= $max_size)
{
$file_ext = pathinfo($_FILES[$key]['name'],PATHINFO_EXTENSION);
$file_name = basename($_FILES[$key]['name'],'.'.$file_ext);
if (in_array(strtolower($file_ext),$allowed))
{
$name = $_FILES[$key]['name'];
$x = 1;
while (file_exists($uploaddir.'/'.$name))
{
$name = $file_name.'['.$x.'].'.$file_ext;
$x++;
}
$name = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 22)), 0, 22). '.' .mb_strtolower ($file_ext);
if (move_uploaded_file($_FILES[$key]['tmp_name'],$uploaddir.'/'.$name))
{
chmod($uploaddir.'/'.$name, 0644);
}
else
{
die(error_get_last());
}
}
else
{
die("Invalid file type");
}
}
else
{
die("File size too big");
}
copy($uploaddir.'/'.$name, $maindir.'/'.$name);
$images = glob("images/thumbs/*.*");
foreach($images as $image)
{
$output .= '<div class="col-md-2" align="center" ><img src="' . $image .'" width="200px" height="140px" style="border:1px solid #ccc;" /></div>';
}
//thumbnail image making part
$modwidth = 200;
$modheight = 140;
list($width, $height) = getimagesize($uploaddir.'/'.$name);
$ratio_orig = $width/$height;
if ($width/$height > $ratio_orig)
{
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
$tn = imagecreatetruecolor($modwidth, $modheight);
//$image = imagecreatefromjpeg($uploaddir.'/'.$name);
$image = imagecreatefromstring(file_get_contents($uploaddir.'/'.$name));
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
imagejpeg($tn, $uploaddir_th.'/'.$name);
imagejpeg($tn, $maindir_th.'/'.$name);
}
echo "STOP!";
?>
Take a look at the finfo extension, this allows you to determine the true file type as it sniffs the file type at the OS level.
http://php.net/manual/en/function.finfo-file.php
As finfo is an extension it will need to be installed and enabled.
http://php.net/manual/en/fileinfo.installation.php
Example
$path = $_FILES[$key]['tmp_name'],$uploaddir.'/'.$name;
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$whitelist = array('image/jpg');
if (in_array(finfo_file($finfo, $path), $whitelist) && move_uploaded_file($path))
{
chmod($uploaddir.'/'.$name, 0644);
}
I have set up a simple "Facebook" like timeline system for my friend to be able to upload statuses with images for his users to see. It seemed to all be working well although the file which stores the images keeps being deleted, and I can't seem to purposely cause the problem myself so I have no idea what is removing this directory?
I have added the upload/remove scripts below to see if anybody might be able to assist me here? I can't seem to find any part of the script which would delete the main image directory on its own?
PLEASE BARE IN MIND - This is still unfinished, and is nowhere near secure just yet, we are in testing phase and need to fix this problem before I can work on perfecting the system.
The main folder for storage of the images is post_images, this is the directory which is being deleted.
REMOVE DIR FUNCTION -
function rrmdir($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file)) rrmdir($file); else unlink($file);
}
rmdir($dir);
}
DECLINE POSTS -
if(isset($_GET['decline_post'])){
$post_id = $conn->real_escape_string($_GET['decline_post']);
$getimagefolder = mysqli_fetch_assoc(mysqli_query($conn, "SELECT `post_image_folder` FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'"));
$image_folder = $getimagefolder['post_image_folder'];
mysqli_query($conn,"DELETE FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'");
$direc = 'post_images/'.$image_folder;
if (file_exists($direc)) {
rrmdir($direc);
} else {
}
header("Location: members_area.php");
}
DELETE POST -
if(isset($_GET['delete_post'])){
$post_id = $conn->real_escape_string($_GET['delete_post']);
$getimagefolder = mysqli_fetch_assoc(mysqli_query($conn, "SELECT `post_image_folder` FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'"));
$image_folder = $getimagefolder['post_image_folder'];
mysqli_query($conn,"DELETE FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'");
$direc = 'post_images/'.$image_folder;
if (file_exists($direc)) {
rrmdir($direc);
} else {
}
header("Location: members_area.php");
}
UPLOAD POST -
if(isset($_POST['new_post'])){
$post_status = $conn->real_escape_string($_POST['status']);
$user_id = $_SESSION['user_id'];
if(!empty($_FILES['images']['tmp_name'])){
$length = 9;
$search = true; // allow the loop to begin
while($search == true) {
$rand_image_folder = substr(str_shuffle("0123456789"), 0, $length);
if (!file_exists('../post_images/'.$rand_image_folder)) {
$search = false;
}
}
mkdir("../post_images/".$rand_image_folder);
foreach($_FILES['images']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['images']['name'][$key];
$file_size = $_FILES['images']['size'][$key];
$file_tmp = $_FILES['images']['tmp_name'][$key];
$file_type = $_FILES['images']['type'][$key];
$check_file_type = substr($file_type, 0, strrpos( $file_type, '/'));
if($check_file_type !== 'image'){
header('Location: ../members_area.php?posterror=1');
}
$extensions = array("jpeg","jpg","png","JPEG","JPG","PNG");
$format = trim(substr($file_type, strrpos($file_type, '/') + 1));
if(in_array($format,$extensions) === false){
header('Location: ../members_area.php?posterror=1');
} else {
move_uploaded_file($file_tmp,"../post_images/".$rand_image_folder."/".$file_name);
$file = "../post_images/".$rand_image_folder."/".$file_name;
$cut_name = substr($file, strpos($file, "/") + 1);
$cut_name = explode('/',$cut_name);
$cut_name = end($cut_name);
$newfile = "../post_images/".$rand_image_folder."/thb_".$cut_name;
$info = getimagesize($file);
list($width, $height) = getimagesize($file);
$max_width = '350';
$max_height = '250';
//try max width first...
$ratio = $max_width / $width;
$new_width = $max_width;
$new_height = $height * $ratio;
//if that didn't work
if ($new_height > $max_height) {
$ratio = $max_height / $height;
$new_height = $max_height;
$new_width = $width * $ratio;
}
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($file);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($file);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($file);
$image = imagecreatetruecolor($new_width, $new_height);
$photo = imagecreatefromjpeg($file);
imagecopyresampled($image, $photo, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image, $newfile, 70);
}
}
if($account_type < 4){
$post_public = 1;
} else {
$post_public = 0;
}
mysqli_query($conn,"INSERT INTO `Pto6LsuQ_posts`
(post_id,post_user_id,post_date_time,post_status,post_image_folder,post_likes,post_public_status)
VALUES ('','$user_id',NOW(),'$post_status','$rand_image_folder','0','$post_public')");
} else {
if($account_type < 4){
$post_public = 1;
} else {
$post_public = 0;
}
mysqli_query($conn,"INSERT INTO `Pto6LsuQ_posts`
(post_id,post_user_id,post_date_time,post_status,post_image_folder,post_likes,post_public_status)
VALUES ('','$user_id',NOW(),'$post_status','','0','$post_public')");
}
header('Location: ../members_area.php?posterror=2');
}
I am trying to upload an image in a folder using the move_uploaded_file() function. The image usually is a JPG.
The problem is that the moving process somehow affects the image quality. To me mor eprecises, the colors are not the same between the file that i want to upload and the uploaded file.
So far i think the problem lies withing the move_uploaded_file() function, as the colors of the temp file are correct.
Here is my code and the images before and after the upload(the top one is before uploading and the bottom one ois after upload).
This kind of behaviour isn't accepted as the results need to be print ready.
if ($this->request->is('post')) {
if (!$this->request->data['TplElement']['file']) {
$tplElementImage['TplElementImage']['original_id'] = 0;
$tplElementImage['TplElementImage']['filepath'] = NULL;
$tplElementImage['TplElementImage']['filepath_hires'] = NULL;
$this->TplElementImage->save($tplElementImage);
}
else {
//create the directory
$path = APP.WEBROOT_DIR.DS.'uploads'.DS.'templates'.DS.$tplElement['TplElement']['tpl_asset_page_id'].DS.$tplElementImage['TplElementImage']['tpl_element_id'].DS.$elementID;
if ($this->make_path($path.DS.'dummy.txt')) {
$tplElementImage['TplElementImage']['original_file_name'] = $this->request->data['TplElement']['file']['name'];
$filename = session_id().'_'.time().'_'.$tplElementImage['TplElementImage']['original_file_name'];
if ($this->request->data['TplElement']['file']['size'] > 0) {
if(move_uploaded_file($this->request->data['TplElement']['file']['tmp_name'], $path.DS.$filename)) {
$tplElementImage['TplElementImage']['filepath'] = '/uploads' . '/' . 'templates' . '/' . $tplElement['TplElement']['tpl_asset_page_id'] . '/' . $tplElementImage['TplElementImage']['tpl_element_id'] . '/' . $elementID . '/' . $filename;
$imageSize = getimagesize($path . DS . $filename);
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];
$zoom = 1;
$imageWidthMm = $imageWidth * 25.4 / 200;
$imageHeightMm = $imageHeight * 25.4 / 200;
$inBlockImageHeight = $imageHeight * $blockWidth / $imageWidth;
$inBlockImageWidth = $imageWidth * $blockHeight / $imageHeight;
if ($inBlockImageHeight < $blockHeight || $inBlockImageWidth < $blockWidth) {
$zoom = max($blockHeight / $imageHeightMm, $blockWidth / $imageWidthMm);
}
if ($zoom > 1) {
$this->Session->setFlash(__('Image too small'));
$this->redirect('/tpl_asset_pages/edit/' . $tplElement['TplElement']['tpl_asset_page_id']);
return;
}
$tplElementImage['TplElementImage']['zoom'] = $zoom;
$tplElementImage['TplElementImage']['original_width'] = $imageWidth;
$tplElementImage['TplElementImage']['original_height'] = $imageHeight;
$tplElementImage['TplElementImage']['top'] = 0;
$tplElementImage['TplElementImage']['left'] = 0;
$tplElementImage['TplElementImage']['original_id'] = 0;
$tplElementImage['TplElementImage']['filepath_hires'] = NULL;
$tplElementImage['TplElementImage']['max_zoom_value'] = $this->ElementImage->GetMaxZoom($imageWidth, $imageHeight, $blockWidth, $blockHeight);
if ($this->TplElementImage->save($tplElementImage)) {
$this->Session->setFlash(__('File successfully saved'));
} else {
$this->Session->setFlash("Unable to save data");
}
}else{
$this->Session->setFlash("Unable to move file");
}
}
else {
if ($this->request->data['TplElement']['file']['size'] > 0) {
$this->Session->setFlash("Unable to save uploaded file");
}
else {
$tplElementImage['TplElementImage']['filepath'] = NULL;
$this->TplElementImage->save($tplElementImage);
$this->Session->setFlash("Unable to save uploaded file");
}
}
}
else {
$this->Session->setFlash('Unable to create folder');
}
}
$this->redirect('/tpl_asset_pages/edit/'.$tplElement['TplElement']['tpl_asset_page_id']);
}
The problem has been fixed using Imagick to write the file.
$img = new Imagick($this->request->data['TplElement']['file']['tmp_name']);
$img->setImageFormat(substr(strrchr($tplElementImage['TplElementImage']['original_file_name'],'.'),1));
//stuff
if($img->writeImage($path.DS.$filename)) {
//stuff
}
//stuff
i am trying to re size the uploading image and moving to a folder, i try with the blow code, but it is not work. i created a function for re sizing the photo, calling that function from another function, but image is not re sized, and photo is not moved to folder.
$final_save_dir = 'techpic';
$thumbname = $_FILES['tpic']['name'];
$imgName = $final_save_dir . '/' . $_FILES['tpic']['name'];
if(#move_uploaded_file($_FILES['tpic']['tmp_name'], $final_save_dir . '/' . $_FILES['tpic']['name']))
{
$this->createThumbnail($thumbname,"600","600",$final_save_dir,$final_save_dir);
}
function createThumbnail($image_name,$new_width,$new_height,$uploadDir,$moveToDir)
{
$path = $uploadDir . '/' . $image_name;
$mime = getimagesize($path);
if($mime['mime']=='image/png'){ $src_img = imagecreatefrompng($path); }
if($mime['mime']=='image/jpg'){ $src_img = imagecreatefromjpeg($path); }
if($mime['mime']=='image/jpeg'){ $src_img = imagecreatefromjpeg($path); }
if($mime['mime']=='image/pjpeg'){ $src_img = imagecreatefromjpeg($path); }
$old_x = imageSX($src_img);
$old_y = imageSY($src_img);
if($old_x > $old_y)
{
$thumb_w = $new_width;
$thumb_h = $old_y*($new_height/$old_x);
}
if($old_x < $old_y)
{
$thumb_w = $old_x*($new_width/$old_y);
$thumb_h = $new_height;
}
if($old_x == $old_y)
{
$thumb_w = $new_width;
$thumb_h = $new_height;
}
$dst_img = ImageCreateTrueColor($thumb_w,$thumb_h);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
// New save location
$new_thumb_loc = $moveToDir . $image_name;
if($mime['mime']=='image/png'){ $result = imagepng($dst_img,$new_thumb_loc,8); }
if($mime['mime']=='image/jpg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
if($mime['mime']=='image/jpeg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
if($mime['mime']=='image/pjpeg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
imagedestroy($dst_img);
imagedestroy($src_img);
return $result;
}
function img($field = 'image', $width = null, $height = null, $crop = false, $alt = null, $turl = null) {
global $editormode;
$val = $field;
if (!$val)
$val = 'no-image.png';
$alt = ($alt) ? $alt : stem(basename($val));
if ($width == null && $height == null)
$imgf = get_dir() . $val;
else
$imgf = gen_img($val, $width, $height, $crop);
if (!$imgf)
return "";
$url = $imgf;
if (!$turl)
return "<img src='$url' alt='$alt'/>\n";
else
return "<a href='$turl'><img src='$url' alt='$alt'/></a>";
}
function get_dir() {
return "upload/";
}
function gen_img($fileval, $width, $height, $crop) {
if (!$fileval)
return null;
$fname = get_dir() . $fileval;
if (!is_readable($fname))
return null;
$stem = stem(basename($fname));
if ($width != null && $height != null) {
$sz = getimagesize($fname);
if ($sz[0] == $width && $sz[1] == $height) {
return substr($fname, strlen(UPLOADROOT));
}
$sep = ($crop) ? '__' : '_';
$outname = thumb_dir($fname) . $stem . $sep . $width . "x" . $height . "." . suffix($fname);
if (!is_readable($outname) || filemtime($outname) < filemtime($fname))
createthumb($fname, $outname, $width, $height, $crop);
}
else if ($width != null && $height == null) {
$outname = thumb_dir($fname) . $stem . "_" . $width . "." . suffix($fname);
if (!is_readable($outname) || filemtime($outname) < filemtime($fname))
createthumb($fname, $outname, $width, $crop);
} else
$outname = $fname;
//echo $outname; die();
return $outname;
}
function thumb_dir($path) {
$enddir = strrpos($path, "/");
$dir = substr($path, 0, $enddir) . "/.thumbnails/";
if (!file_exists($dir))
mkdir($dir, 0777, true);
return $dir;
}
function createthumb($source, $dest, $new_w, $new_h = null, $crop = false) {
if (!file_exists($source))
return null;
$src_img = 0;
$src_img = image_create($source);
$old_w = imageSX($src_img);
$old_h = imageSY($src_img);
$x = $y = 0;
if ($new_h == null) { // we want a square thumb, cropped if necessary
if ($old_w > $old_h) {
$x = ceil(($old_w - $old_h) / 2);
$old_w = $old_h;
} else if ($old_h > $old_w) {
$y = ceil(($old_h - $old_w) / 2);
$old_h = $old_w;
}
$thumb_w = $thumb_h = $new_w;
} else if ($crop) {
$thumb_w = $new_w;
$thumb_h = $new_h;
$oar = $old_w / $old_h;
$nar = $new_w / $new_h;
if ($oar < $nar) {
$y = ($old_h - $old_h * $oar / $nar) / 2;
$old_h = ($old_h * $oar / $nar);
} else {
$x = ($old_w - $old_w * $nar / $oar) / 2;
$old_w = ($old_w * $nar / $oar);
}
} else if ($new_w * $old_h / $old_w <= $new_h) { // retain aspect ratio, limit by new_w
$thumb_h = $new_w * $old_h / $old_w;
$thumb_w = $new_w;
} else { // retain aspect ratio, limit by new_h
$thumb_w = $new_h * $old_w / $old_h;
$thumb_h = $new_h;
}
$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
imagecolortransparent($dst_img, imagecolorallocatealpha($dst_img, 0, 0, 0, 127));
imagealphablending($dst_img, false);
imagesavealpha($dst_img, true);
imagecopyresampled($dst_img, $src_img, 0, 0, $x, $y, $thumb_w, $thumb_h, $old_w, $old_h);
image_save($dst_img, $dest);
imagedestroy($dst_img);
imagedestroy($src_img);
}
function image_create($source) {
$suf = strtolower(suffix($source));
if ($source == '.jpg')
mylog("wtf", "source: $source", true);
if ($suf == "png")
return imagecreatefrompng($source);
else if ($suf == "jpg" || $suf == "jpeg")
return imagecreatefromjpeg($source);
else if ($suf == "gif")
return imagecreatefromgif($source);
return null;
}
function image_save($dst_img, $dest) {
$suf = strtolower(suffix($dest));
if ($suf == "png")
imagepng($dst_img, $dest);
else if ($suf == "jpg" || $suf == "jpeg")
imagejpeg($dst_img, $dest);
else if ($suf == "gif")
imagegif($dst_img, $dest);
}
This your function which is put in your function file
that function has make Folder in the thumbnails in the image folder when you call the function file.
Following way to call the function when image display.
<?php echo img('pages/sample_image.jpg', 122, 81, TRUE) ?>
Here the first is path of the image and 122:means width and 81:height and True/false True:crop the image and false: only resize the image.
And define the Uploadroot in your config file this path for the image folder.
Hope this works.
Thanks.
For resizing an image in php you can use Imagick::resizeImage from this article or use this article
Of course we can use Gd library which has low overhead by recommendation of #CD001. You can find explanation of GD re sizing in this article
Edit for More Explanation
for using Imagick::resizeImage you should see this description
here is the prototype of the function:
bool Imagick::resizeImage ( int $columns , int $rows , int $filter , float $blur [, bool $bestfit = false ] )
Parameters
columns
Width of the image
rows
Height of the image
filter
Refer to the list of filter constants.
blur
The blur factor where > 1 is blurry, < 1 is sharp.
bestfit
Optional fit parameter.
If you want to use gd library here is simple source code
<?php
// File and new size
//the original image has 800x600
$filename = 'images/picture.jpg';
//the resize will be a percent of the original size
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output and free memory
//the resized image will be 400x300
imagejpeg($thumb);
imagedestroy($thumb);
I don't have any experience with PHP and images in general, but I have a need to resize all images into the square when they get uploaded.
Since I have multiple products and they have different pictures that comes in different sizes, I think that the best approach is to 'standardize' them during the upload by taking an image and 'fitting' it into the 800x800 white square while maintaining the aspect ratio (if longest size >800 then downsize, if longest size <800, then re-size).
My initial solution was created via JavaScript, where I tried to find the biggest picture and resize all other images according to it. Although, it is not very useful and can be faulty since if there is a delay in image load, images might not be loaded for JS to perform the operation, thus not showing images at all.
$product = getProductById($productid);
$filesArray = array();
if (isset($_GET['files']) && $productid > 0) {
$error = false;
$files = array();
$fileName = '';
$uploaddir = "../images/products/";
foreach ($_FILES as $file) {
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$random_name = $widgets->randomFileName();
$randomFullFileName = $productid .'_'. $random_name . '.' . $ext;
//copy to location
//----------------
//HERE I NEED TO CREATE A 800x800px SQUARE and fit the image into it
//----------------
if (move_uploaded_file($file['tmp_name'], $uploaddir . $randomFullFileName)) {
//save to database
$image_id = updateProduct('default_image', 'images/products/'.$randomFullFileName, $productid);
if ($image_id > 0) {
echo 'Added new image';
} else {
echo 'Error, unable to add. <br> Please try again.';
}
} else {
echo 'Error, unable to add. <br> Please try again.';
}
}
}
Before: 600x300
After: 800x800 with white borders to fill-in the space
You can try this approach (tested). It will fit your images into an 800x800 square canvas while maintaining the aspect ratio of your images.
resize_image(): This function will maintain the aspect ratio of your image.
function resize_image($img,$maxwidth,$maxheight) {
//This function will return the specified dimension(width,height)
//dimension[0] - width
//dimension[1] - height
$dimension = array();
$imginfo = getimagesize($img);
$imgwidth = $imginfo[0];
$imgheight = $imginfo[1];
if($imgwidth > $maxwidth){
$ratio = $maxwidth/$imgwidth;
$newwidth = round($imgwidth*$ratio);
$newheight = round($imgheight*$ratio);
if($newheight > $maxheight){
$ratio = $maxheight/$newheight;
$dimension[] = round($newwidth*$ratio);
$dimension[] = round($newheight*$ratio);
return $dimension;
}else{
$dimension[] = $newwidth;
$dimension[] = $newheight;
return $dimension;
}
}elseif($imgheight > $maxheight){
$ratio = $maxheight/$imgheight;
$newwidth = round($imgwidth*$ratio);
$newheight = round($imgheight*$ratio);
if($newwidth > $maxwidth){
$ratio = $maxwidth/$newwidth;
$dimension[] = round($newwidth*$ratio);
$dimension[] = round($newheight*$ratio);
return $dimension;
}else{
$dimension[] = $newwidth;
$dimension[] = $newheight;
return $dimension;
}
}else{
$dimension[] = $imgwidth;
$dimension[] = $imgheight;
return $dimension;
}
}
And now comes your code,
$product = getProductById($productid);
$filesArray = array();
if (isset($_GET['files']) && $productid > 0) {
$error = false;
$files = array();
$fileName = '';
$uploaddir = "../images/products/";
foreach ($_FILES as $file) {
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$random_name = $widgets->randomFileName();
$randomFullFileName = $productid .'_'. $random_name . '.' . $ext;
//copy to location
//----------------
//HERE I NEED TO CREATE A 800x800px SQUARE and fit the image into it
// Create image from file
$image = null;
switch(strtolower($file['type']))
{
case 'image/jpeg':
$image = imagecreatefromjpeg($file['tmp_name']);
break;
case 'image/png':
$image = imagecreatefrompng($file['tmp_name']);
break;
case 'image/gif':
$image = imagecreatefromgif($file['tmp_name']);
break;
default:
exit('Unsupported type: '.$file['type']);
}
// Get current dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);
// Get the new dimensions
$dimension = resize_image($file, 800, 800);
$new_width = $dimension[0];
$new_height = $dimension[1];
// Create new empty image
$new = imagecreatetruecolor($new_width, $new_height);
// Resize old image into new
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
// Catch and save the image
$status = false;
switch(strtolower($file['type']))
{
case 'image/jpeg':
$status = imagejpeg($new, $uploaddir . $randomFullFileName, 90);
break;
case 'image/png':
$status = imagepng($new, $uploaddir . $randomFullFileName, 0);
break;
case 'image/gif':
$status = imagegif($new, $uploaddir . $randomFullFileName);
break;
}
// Destroy resources
imagedestroy($image);
imagedestroy($new);
//save to database
if($status){
$image_id = updateProduct('default_image', 'images/products/'.$randomFullFileName, $productid);
if ($image_id > 0) {
echo 'Added new image';
} else {
echo 'Error, unable to add. <br> Please try again.';
}
}else{
echo 'Error, unable to add. <br> Please try again.';
}
//----------------
//if (move_uploaded_file($file['tmp_name'], $uploaddir . $randomFullFileName)) {
// //save to database
// $image_id = updateProduct('default_image', 'images/products/'.$randomFullFileName, $productid);
// if ($image_id > 0) {
// echo 'Added new image';
// } else {
// echo 'Error, unable to add. <br> Please try again.';
// }
//} else {
// echo 'Error, unable to add. <br> Please try again.';
//}
}
}
Original answer
How about imagine?
Insert this code before //save to database comment:
<?php
$imagine = new Imagine\Gd\Imagine();
$size = new Imagine\Image\Box(800, 800);
$mode = Imagine\Image\ImageInterface::THUMBNAIL_INSET;
$imagine
->open($uploaddir . $randomFullFileName)
->thumbnail($size, $mode)
->save($uploaddir . $randomFullFileName);
New answer
As resize is not working like expected (thanks to #Pradeep Sanjaya), I would paste solution based on snippet from link:
/**
* Image resize
* #param string $input Full path to source image
* #param string $output Full path to result image
* #param int $width Width of result image
* #param int $height Height of result image
*/
function resizeImage($input, $output, $width, $height)
{
$imagine = new Imagine\Gd\Imagine();
$size = new Imagine\Image\Box($width, $height);
$mode = Imagine\Image\ImageInterface::THUMBNAIL_INSET;
$resizeimg = $imagine
->open($input)
->thumbnail($size, $mode);
$sizeR = $resizeimg->getSize();
$widthR = $sizeR->getWidth();
$heightR = $sizeR->getHeight();
$preserve = $imagine->create($size);
$startX = $startY = 0;
if ($widthR < $width) {
$startX = ($width - $widthR) / 2;
}
if ($heightR < $height) {
$startY = ($height - $heightR) / 2;
}
$preserve
->paste($resizeimg, new Imagine\Image\Point($startX, $startY))
->save($output);
}
And usage according to original question:
<?php
// placed after `save to database` comment
resizeImage(
$uploaddir . $randomFullFileNamem,
$uploaddir . $randomFullFileName,
800, 800
);