Jump to content

Recommended Posts

I know there are lots of examples out there, but I just can't get any of them to work when ever I try and implement them into my current code. I always seem to run into the same problem, which is saving the resized image into my uploads folder and also the database.

 

I am currently using the following code to upload my images and then save them both into a folder called uploads, as well as saving them to the database. What I would like to do is check the width of all images uploaded, if the width is greater than 570px then resize it to that and save both the resized image into the uploads folder and database and ignore the orginal image.

 

Can someone point me in the right direction please, as everything I have tried so far hasn't worked.

 

<?php

$upload_dir = 'uploads/';
$thumbs_dir = 'thumbs/';

// Check if the upload and thumbs directories exist.
// If they don't then we create them.

if(!file_exists($upload_dir)) {

	if(mkdir($upload_dir)) {

		if(!file_exists($upload_dir . $thumbs_dir)) {

			if(mkdir($upload_dir . $thumbs_dir)) {

			}
			else {

				exit_status($upload_dir . 'directory could not be created! Please check your folder permissions.');

			}

		}

	}
	else {

		exit_status($upload_dir . 'directory could not be created! Please check your folder permissions.');

	}

}

$allowed_ext = array('jpg','jpeg','png','gif', 'pdf');
$unique_id   = uniqid();

if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
	exit_status('Error! Wrong HTTP method!');
}


if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){

	$pic = $_FILES['pic'];

	if(!in_array(get_extension($pic['name']),$allowed_ext)){
		exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
	}	


	// Move the uploaded file from the temporary 
	// directory to the uploads folder:

	$name        = $pic['name'];
	$ext         = get_extension($pic['name']);
	$new_name    = $unique_id . "." . $ext;
	$createdby   = $_SESSION["ufullname"];

	if(move_uploaded_file($pic['tmp_name'], $upload_dir . $new_name)){

		include('functions.php');

		connect();

		$link   = get_option('admin_url');

		$sql    = " INSERT into mediaT ( name, url, link, createdon, createdby ) VALUES ( '$new_name', '$upload_dir$new_name', '$link$upload_dir$new_name', NOW(), '$createdby' ) ";
		$result = mysql_query($sql);

		exit_status('File was uploaded successfuly!');
	}

}

exit_status('Something went wrong with your upload!');


// Helper functions

function exit_status($str){
	echo json_encode(array('status'=>$str));
	exit;
}

function get_extension($file_name){
	$ext = explode('.', $file_name);
	$ext = array_pop($ext);
	return strtolower($ext);
}
?>

Link to comment
https://forums.phpfreaks.com/topic/265259-php-image-resizing/
Share on other sites

Check the below code. You can change the variables as you want.  :shy:

 

		
        list($width, $height, $type, $attr) = getimagesize($thumbName); //this function find the width, height, type of the image $thumbName

If($width >= 570){
	include("resize_function.php"); //include the below code 
	$file = $thumbName; //old name
	$save = $thumbName;  //new name. here i have the same name as the above to overwrite the old image 
	$t_w ='570';
	$t_h = ($width / $height)*$t_w; 
	$o_path = './image'; 
	$s_path = './image';

	Resize_Image($save,$file,$t_w,$t_h,$s_path,$o_path); //This Function resize the new

 

Make a php file named resize_function.php and paste the below code in there:

 

<?PHP
/* RESIZE FUNCTION */
/* the parameters */
/*
$file is the name of the original image WITHOUT the path
$save is the name of the resized image WITHOUT the path 
$t_w is the MAXIMUM width of the new image
$t_h is the MAXIMUM height of the new image
$o_path is the path to the original image INCLUDE trailing slash
$s_path is the path where you want to save the new image INCLUDE trailing slash
NOTE: to overwrite the original with the new, use the same name and path for both
*/

function Resize_Image($save,$file,$t_w,$t_h,$s_path,$o_path) {
$s_path = trim($s_path);
$o_path = trim($o_path);
$save = $s_path . $save;
$file = $o_path . $file;
$ext = strtolower(end(explode('.',$save)));
list($width, $height) = getimagesize($file) ; 
if(($width>$t_w) OR ($height>$t_h)) {
	$r1 = $t_w/$width;
	$r2 = $t_h/$height;
	if($r1<$r2) {
	  $size = $t_w/$width;
	}else{
	  $size = $t_h/$height;
	}
}else{
	$size=1;
}
$modwidth = $width * $size; 
$modheight = $height * $size; 
$tn = imagecreatetruecolor($modwidth, $modheight) ; 
switch ($ext) {
	case 'jpg':
	case 'jpeg':
				$image = imagecreatefromjpeg($file) ; 
	break;
	case 'gif':
				$image = imagecreatefromgif($file) ; 
	break;
	case 'png':
				$image = imagecreatefrompng($file) ; 
	break;
}
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ; 
imagejpeg($tn, $save, 100) ; 
return;
}
/* 		END OF RESIZE FUNCTION */
?>

Link to comment
https://forums.phpfreaks.com/topic/265259-php-image-resizing/#findComment-1359469
Share on other sites

@Isset1988

 

Slight correction

 

$t_h = ($width / $height)*$t_w;

]

To maintain the image proportions

 

  $t_h        $height

------  =  --------- 

  $t_w        $width

 

therefore

 

$t_h = ($height/$width) * $t_w;

Link to comment
https://forums.phpfreaks.com/topic/265259-php-image-resizing/#findComment-1359500
Share on other sites

Hey it's just me but I always do a check to see if it's a portrait or landscape then do re-size accordingly.

<?php
//Thumbs 
if ($height>$width){
$newheight=180;
$newwidth=($width/$height)*$newheight;
}else{
$newwidth=180;
$newheight=($height/$width)*$newwidth;
}

$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
?>

Link to comment
https://forums.phpfreaks.com/topic/265259-php-image-resizing/#findComment-1359507
Share on other sites

Ok, firstly thank you for your help. However I'm sure I worded the question properly. The problem I am having if figuring out how to save the original image into the uploads folder. Then I want to save the resized image to the thumbs folder and the database with the same name as the original.

 

I have implemented the example you have suggested into my code, but again I am struggling to fogure out how to save the resized image. At current it is still saving the orginal and not the resized image.

 

Thanks.

 

 

<?php

include('functions.php');

$upload_dir = 'uploads/';
$thumbs_dir = 'thumbs/';

// Check if the upload and thumbs directories exist.
// If they don't then we create them.

if(!file_exists($upload_dir)) {

	if(mkdir($upload_dir)) {

		if(!file_exists($upload_dir . $thumbs_dir)) {

			if(mkdir($upload_dir . $thumbs_dir)) {

			}
			else {
				exit_status($upload_dir . 'directory could not be created! Please check your folder permissions.');
			}

		}

	}
	else {
		exit_status($thumbs_dir . 'directory could not be created! Please check your folder permissions.');
	}

}

$allowed_ext = array('jpg','jpeg','png','gif', 'pdf');
$unique_id   = uniqid();

if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
	exit_status('Error! Wrong HTTP method!');
}


if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){

	$pic = $_FILES['pic'];

	if(!in_array(get_extension($pic['name']),$allowed_ext)){
		exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
	}	


	// Move the uploaded file from the temporary 
	// directory to the uploads folder:

	$name        = $pic['name'];
	$ext         = get_extension($pic['name']);
	$new_name    = $unique_id . "." . $ext;
	$createdby   = $_SESSION["ufullname"];

	list($width, $height, $type, $attr) = getimagesize($pic); //this function find the width, height, type of the image $thumbName

	if($width >= 570){
		$t_w ='570';
		$t_h = ($height/$width) * $t_w; 

		resize_image($new_name,$name,$t_w,$t_h,$thumbs_dir,$upload_dir); //This Function resize the new	
	}

	if(move_uploaded_file($pic['tmp_name'], $upload_dir . $new_name)){

		connect();

		$link   = get_option('admin_url');

		$sql    = " INSERT into mediaT ( name, url, link, createdon, createdby ) VALUES ( '$new_name', '$upload_dir$new_name', '$link$upload_dir$new_name', NOW(), '$createdby' ) ";
		$result = mysql_query($sql);

		exit_status('File was uploaded successfuly!');
	}

}

exit_status('Something went wrong with your upload!');


// Helper functions

function exit_status($str){
	echo json_encode(array('status'=>$str));
	exit;
}

function get_extension($file_name){
	$ext = explode('.', $file_name);
	$ext = array_pop($ext);
	return strtolower($ext);
}
?>

 

 

Link to comment
https://forums.phpfreaks.com/topic/265259-php-image-resizing/#findComment-1359605
Share on other sites

I have managed to write some code which now saves the image and resized image to the folders and database. However the images that are getting resized are just a back square. Any idea what is causing this?

 

<?php
session_start();

$path_thumbs = "uploads/thumbs";
$path_big    = "uploads";
$createdby   = $_SESSION["ufullname"];		

//the new width of the resized image, in pixels.

$img_thumb_width = 570; // 

$extlimit = "yes"; //Limit allowed extensions? (no for all extensions allowed)

//List of allowed extensions if extlimit = yes

$limitedext = array(".gif",".jpg",".png",".jpeg",".bmp");		

//the image -> variables

$file_type = $_FILES['pic']['type'];
$file_name = $_FILES['pic']['name'];
$file_size = $_FILES['pic']['size'];
$file_tmp = $_FILES['pic']['tmp_name'];

//check if you have selected a file.

if(!is_uploaded_file($file_tmp)){

	exit_status('Error: Please select a file to upload!');
	exit(); //exit the script and don't process the rest of it!

}

//check the file's extension

$ext = strrchr($file_name,'.');

$ext = strtolower($ext);

//uh-oh! the file extension is not allowed!

if (($extlimit == "yes") && (!in_array($ext,$limitedext))) {

	exit_status('Wrong file extension.');
	exit();

}

//so, whats the file's extension?

$getExt = explode ('.', $file_name);

$file_ext = $getExt[count($getExt)-1];

//create a random file name

$rand_name = md5(time());

$rand_name= rand(0,999999999);

//the new width variable

$ThumbWidth = $img_thumb_width;



/////////////////////////////////

// CREATE THE THUMBNAIL //

////////////////////////////////



//keep image type

if($file_size){

	if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){

		$new_img = imagecreatefromjpeg($file_tmp);

	}elseif($file_type == "image/x-png" || $file_type == "image/png"){

		$new_img = imagecreatefrompng($file_tmp);

	}elseif($file_type == "image/gif"){

		$new_img = imagecreatefromgif($file_tmp);

	}

	//list the width and height and keep the height ratio.

	list($width, $height) = getimagesize($file_tmp);

	//calculate the image ratio

	$imgratio=$width/$height;

	if ($imgratio>1){

		$newwidth = $ThumbWidth;

		$newheight = $ThumbWidth/$imgratio;

	}else{

		$newheight = $ThumbWidth;

		$newwidth = $ThumbWidth*$imgratio;

	}

	//function for resize image.

	if (function_exists(imagecreatetruecolor)){

		$resized_img = imagecreatetruecolor($newwidth,$newheight);

	}else{

		die("Error: Please make sure you have GD library ver 2+");

	}

	//the resizing is going on here!

	imagecopyresized($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

	//finally, save the image

	ImageJpeg ($resized_img,"$path_thumbs/$rand_name.$file_ext");

	ImageDestroy ($resized_img);

	ImageDestroy ($new_img);

}



//ok copy the finished file to the thumbnail directory

if(move_uploaded_file ($file_tmp, "$path_big/$rand_name.$file_ext")){

	include('functions.php');

	connect();

	$link   = get_option('admin_url');

	$sql    = " INSERT into mediaT ( name, url, link, createdon, createdby ) VALUES ( '$file_name', '$path_big/$rand_name.$file_ext', '$link$path_big/$rand_name.$file_ext', NOW(), '$createdby' ) ";
	$result = mysql_query($sql);

}

exit_status('Something went wrong with your upload!');


// Helper functions

function exit_status($str){
	echo json_encode(array('status'=>$str));
	exit;
}

function get_extension($file_name){
	$ext = explode('.', $file_name);
	$ext = array_pop($ext);
	return strtolower($ext);
}
?>

Link to comment
https://forums.phpfreaks.com/topic/265259-php-image-resizing/#findComment-1359627
Share on other sites

Thank you for your help isset1988. However the code you sent me was completely different to the code that I have. I would like to try and the problem with the code I currently have and use that if possible as I have put a lot of time into it. If I cannot figure out what is wrong then I will consider using a different method.

 

This is the code I currently have which is creating the resized image at the correct size, however it still creating a completely black image instead of copying the original image.

 

Can anyone spot any possible issues with the code below?

 

<?php
session_start();

$path_thumbs = "uploads/thumbs";
$path_big    = "uploads";
$createdby   = $_SESSION["ufullname"];		

//the new width of the resized image, in pixels.

$img_thumb_width = 570; // 

$extlimit = "yes"; //Limit allowed extensions? (no for all extensions allowed)

//List of allowed extensions if extlimit = yes

$limitedext = array(".gif",".jpg",".png",".jpeg",".bmp");		

//the image -> variables

$file_type = $_FILES['pic']['type'];
$file_name = $_FILES['pic']['name'];
$file_size = $_FILES['pic']['size'];
$file_tmp = $_FILES['pic']['tmp_name'];

//check if you have selected a file.

if(!is_uploaded_file($file_tmp)){

	exit_status('Error: Please select a file to upload!');
	exit(); //exit the script and don't process the rest of it!

}

//check the file's extension

$ext = strrchr($file_name,'.');

$ext = strtolower($ext);

//uh-oh! the file extension is not allowed!

if (($extlimit == "yes") && (!in_array($ext,$limitedext))) {

	exit_status('Wrong file extension.');
	exit();

}

//so, whats the file's extension?

$getExt = explode ('.', $file_name);

$file_ext = $getExt[count($getExt)-1];

//create a random file name

$rand_name = md5(time());

$rand_name = $rand_name . rand(0,999999999);

//the new width variable

$ThumbWidth = $img_thumb_width;



/////////////////////////////////

///// CREATE THE THUMBNAIL /////

///////////////////////////////



//keep image type

if($file_size){

	if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){

		$new_img = imagecreatefromjpeg($file_tmp);

	}elseif($file_type == "image/x-png" || $file_type == "image/png"){

		$new_img = imagecreatefrompng($file_tmp);

	}elseif($file_type == "image/gif"){

		$new_img = imagecreatefromgif($file_tmp);

	}

	//list the width and height and keep the height ratio.

	list($width, $height) = getimagesize($file_tmp);

	//calculate the image ratio

	$imgratio=$width/$height;

	if ($imgratio>1){

		$newwidth = $ThumbWidth;

		$newheight = $ThumbWidth/$imgratio;

	}else{

		$newheight = $ThumbWidth;

		$newwidth = $ThumbWidth*$imgratio;

	}

	//function for resize image.

	if (function_exists(imagecreatetruecolor)){

		$resized_img = imagecreatetruecolor($newwidth,$newheight);

	}else{

		die("Error: Please make sure you have GD library ver 2+");

	}

	//the resizing is going on here!

	imagecopyresampled($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

	//finally, save the image

	imagejpeg($resized_img,"$path_thumbs/$rand_name.$file_ext", 100);


}



//ok copy the finished file to the thumbnail directory

if(move_uploaded_file ($file_tmp, "$path_big/$rand_name.$file_ext")){

	include('functions.php');

	connect();

	$link   = get_option('admin_url');

	$sql    = " INSERT into mediaT ( name, url, link, createdon, createdby ) VALUES ( '$file_name', '$path_big/$rand_name.$file_ext', '$link$path_big/$rand_name.$file_ext', NOW(), '$createdby' ) ";
	$result = mysql_query($sql);

}

exit_status('Something went wrong with your upload!');


// Helper functions

function exit_status($str){
	echo json_encode(array('status'=>$str));
	exit;
}

function get_extension($file_name){
	$ext = explode('.', $file_name);
	$ext = array_pop($ext);
	return strtolower($ext);
}
?>

Link to comment
https://forums.phpfreaks.com/topic/265259-php-image-resizing/#findComment-1361066
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.