I'm trying to upload an image taken using the image picker package to my localhost server using a PHP API.
When the picture is taken, a message in the debug console appears saying "scanned (some path) to null" and the image path isn't saved.
I'd be very grateful if anyone who knows anything about this fills me in on how I can fix it. thank you in advance!
Here's my Relevant code:
-(PHP Backend)inserting an image to the database:
include_once "../../api/patients/create_image.php";
if (
isset($_POST["id"])
) {
if (!empty($_FILES["file"]['name']) )
{
$image = uploadImage("file", '../images/', 200,600);
$img_image = $image["image"];
}
else{
$img_image = "";
}
$id = $_POST["id"];
$insertArray = array();
array_push($insertArray, htmlspecialchars(strip_tags($img_image)));
array_push($insertArray, htmlspecialchars(strip_tags($id)));
$sql = "insert into patient_images (image, file_id) values (?,?)";
$result = dbExec($sql, $insertArray);
$resJson = array("result" => "success", "code" => 200, "body" => $insertArray);
echo json_encode($resJson, JSON_UNESCAPED_UNICODE);
} else {
//bad request
$resJson = array("result" => "fail", "code" => "400");
echo json_encode($resJson, JSON_UNESCAPED_UNICODE);
}
unction uploadImage($inputName, $uploadDir , $thumbnail_width , $image_width)
{
$image = $_FILES[$inputName];
//echo "error " . $image['name'] . $image['tmp_name'] . "end;";
$imagePath = '';
$thumbnailPath = '';
// echo "before";
// if a file is given
if (trim($image['tmp_name']) != '') {
$ext = substr(strrchr($image['name'], "."), 1); //$extensions[$image['type']];
// generate a random new file name to avoid name conflict
$imagePath = md5(rand() * time()) . ".$ext";
list($width, $height, $type, $attr) = getimagesize($image['tmp_name']);
// make sure the image width does not exceed the
// maximum allowed width
if ($width > $image_width) {
// echo "after";
$result = createThumbnail($image['tmp_name'], $uploadDir . $imagePath, $image_width);
$imagePath = $result;
} else {
$result = move_uploaded_file($image['tmp_name'], $uploadDir . $imagePath);
}
if ($result) {
// create thumbnail
$thumbnailPath = md5(rand() * time()) . ".$ext";
$result = createThumbnail($uploadDir . $imagePath, $uploadDir . $thumbnailPath, $thumbnail_width);
// create thumbnail failed, delete the image
if (!$result) {
unlink($uploadDir . $imagePath);
$imagePath = $thumbnailPath = '';
} else {
$thumbnailPath = $result;
}
} else {
// the product cannot be upload / resized
$imagePath = $thumbnailPath = '';
}
}
return array('image' => $imagePath, 'thumbnail' => $thumbnailPath);
}
(Front-end):
Future<bool> uploadFile(File imageFile, String id) async {
var stream = http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var uri = Uri.parse(path_api + 'patients/insertImage.php');
print(uri.path);
var request = http.MultipartRequest('POST', uri);
var multiPartFile = http.MultipartFile('file', stream, length,
filename: basename(imageFile.path));
request.fields['id'] = id;
request.files.add(multiPartFile);
var response = await request.send();
if (response.statusCode == 200) {
print('ok');
} else {
print('nope');
}
}
Future getImageCamera() async {
var image = await picker.pickImage(source: ImageSource.camera);
setState(
() {
if (image != null) {
_image = File(image.path);
} else {
print('no image selected');
}
},
);
}
I use a PHP file to upload images to my server from my web application and have recently hit some memory limit issues that I was hoping someone with more experience than me could help with. Most of the images uploaded have been from mobiles so the file size is very manageable but recently there have been some uploads from an SLR camera that have been causing the issues. These images are around 7-8MB in size and I had assumed our PHP memory limit of 64MB would handle this. Upon inspection I found the imagecreatefromjpeg() function in our crop function to be the culprit although I assume the memory has been filled up before this despite using imagedestroy() to clear any previously created images. Upon using ini_set('memory_limit') to up the limit to a much higher value I found the script worked as expected but I would prefer a cleaner solution. I have attached the code below and any help would be greatly appreciated.
ini_set('memory_limit', '256M');
if(isset($_POST)) {
############ Edit settings ##############
$ThumbSquareSize = 200; //Thumbnail will be 200x200
$ThumbPrefix = "thumbs/"; //Normal thumb Prefix
$DestinationDirectory = '../../../uploads/general/'; //specify upload directory ends with / (slash)
$PortfolioDirectory = '../../../images/portfolio/';
$Quality = 100; //jpeg quality
##########################################
$imID = intval($_POST['imageID']);
$image = $_POST['image'];
$data = $image['data'];
$name = $image['name']; //get image name
$width = $image['width']; // get original image width
$height = $image['height'];// orig height
$type = $image['type']; //get file type, returns "image/png", image/jpeg, text/plain etc.
$desc = $image['desc'];
$album = intval($image['album']);
$customer = intval($image['customer']);
$tags = $image['tags'];
$allTags = $_POST['allTags'];
$portType = intval($image['portType']);
$rating = intval($image['rating']);
$imData = array();
if(strlen($data) < 500) {
$dParts = explode('?', $data);
$path = $dParts[0];
$base64 = file_get_contents($path);
$data = 'data:' . $type . ';base64,' . base64_encode($base64);
}
function base64_to_jpeg($base64_string, $output_file) {
$ifp = fopen($output_file, "wb");
$data = explode(',', $base64_string);
fwrite($ifp, base64_decode($data[1]));
fclose($ifp);
return $output_file;
}
function base64_to_png($base64_string, $output_file) {
$img = str_replace('data:image/png;base64,', '', $base64_string);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$im = imagecreatefromstring($data);
if ($im !== false) {
imagepng($im, $output_file);
imagedestroy($im);
}
return $output_file;
}
if($stmt = $db -> prepare("UPDATE `images` SET name = ?, type = ?, description = ?, width = ?, height = ?, rating = ?, portType = ?, customer = ?, album = ?, dateModified = NOW() WHERE ID = ?")) {
$stmt -> bind_param("sssiiiiiii", $name, $type, $desc, $width, $height, $rating, $portType, $customer, $album, $imID);
if (!$stmt->execute()) {
echo false;
} else {
$delTags = "DELETE FROM tagLink WHERE imageID = $imID";
if(!$db->query($delTags)) {
echo $db->error;
}
if(sizeof($tags) > 0) {
foreach($tags as $tag) {
$tagQ = "INSERT INTO tagLink (imageID, tag) VALUES ($imID, '$tag')";
if(!$db->query($tagQ)) {
echo $db->error;
}
}
}
switch(strtolower($type))
{
case 'png':
$fname = $name . '(' . $imID . ').png';
$file = $DestinationDirectory . $fname;
$portfile = $PortfolioDirectory . $fname;
$thumbDest = $DestinationDirectory . $ThumbPrefix . $fname;
$CreatedImage = base64_to_png($data,$file);
break;
case 'jpeg':
case 'pjpeg':
case 'jpeg':
$fname = $name . '(' . $imID . ').jpeg';
$file = $DestinationDirectory . $fname;
$portfile = $PortfolioDirectory . $fname;
$thumbDest = $DestinationDirectory . $ThumbPrefix . $fname;
$CreatedImage = base64_to_jpeg($data,$file);
break;
default:
die('Unsupported File!'); //output error and exit
}
array_push($imData, $imID);
array_push($imData, $name);
array_push($imData, $type);
array_push($imData, $portType);
echo json_encode($imData);
if(!cropImage($width,$height,$ThumbSquareSize,$thumbDest,$CreatedImage,$Quality,$type))
{
echo 'Error Creating thumbnail';
}
}
$stmt -> close();
} else {
/* Error */
printf("Prepared Statement Error: %s\n", $db->error);
}
/* Close connection */
$db -> close();
include '../cron/updatePortfolio.php';
}
//This function corps image to create exact square images, no matter what its original size!
function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$type)
{
//Check Image size is not 0
if($CurWidth <= 0 || $CurHeight <= 0)
{
return false;
}
if($CurWidth>$CurHeight)
{
$y_offset = 0;
$x_offset = ($CurWidth - $CurHeight) / 2;
$square_size = $CurWidth - ($x_offset * 2);
}else{
$x_offset = 0;
$y_offset = ($CurHeight - $CurWidth) / 2;
$square_size = $CurHeight - ($y_offset * 2);
}
switch(strtolower($type))
{
case 'png':
$imageX = imagecreatefrompng ( $SrcImage );
break;
case 'jpeg':
case 'pjpeg':
case 'jpeg':
$imageX = imagecreatefromjpeg ( $SrcImage );
break;
default:
return false;
}
$NewCanves = imagecreatetruecolor($iSize, $iSize);
if(imagecopyresampled($NewCanves, $imageX, 0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size))
{
switch(strtolower($type))
{
case 'png':
imagepng($NewCanves,$DestFolder);
break;
case 'jpeg':
case 'pjpeg':
case 'jpeg':
imagejpeg($NewCanves,$DestFolder,$Quality);
break;
default:
return false;
}
if(is_resource($NewCanves)) {
imagedestroy($NewCanves);
}
return true;
}
}
Look in the php.ini at
upload_max_filesize = 40M
post_max_size = 40M
Change 40M to your max size
Information: I have already looked around for answers on SO, Google and other places with no avail. Please do not redirect me to other answers or websites unless it involves new information.
I am building a huge website which converts thousands of images in one go and uploads details of these images to the Database (All images are already uploaded via FTP). The process only creates thumbnails and creates image links in the tables.
The problem: The process takes on average 30 minutes to complete. After roughly 15 minutes, the site displays a 500 Internal Server Error and the website will not reload until the process has completed. The process will still complete as it should in the background? (No idea how this works, but it does). No errors are recorded on the server as I have checked.
Attempted Solutions: I have already attempted a couple things...
Adding this to the .htaccess file
<IfModule mod_php5.c>
php_value max_execution_time 0
php_value max_input_time 0
php_value memory_limit 5000M
php_value post_max_size 5000M
php_value upload_max_filesize 5000M
</IfModule>
Using set_time_limit(0); within the function and the script itself.
I have looked at the option to update the httpd.conf file to change the MaxRequestLen but I'm not sure if that would be the correct thing to do in this circumstance?
Scripts:
Batch Upload Script -
if(isset($_GET['create_all_albums'])){
$length2 = 8;
$randomString2 = substr(str_shuffle("0123456789"), 0, $length2);
setcookie('album_error_log', $randomString2, time() + (3600), "/");
$starting_folder = $_GET['create_all_albums'];
$date_time = date("Y-m-d H:i:s");
$useridnu = $_SESSION['userid'];
$useremail = $_SESSION['email_address'];
mysqli_query($conn,"INSERT INTO new_recent_batch_uses (use_id,user_id,email_address,error_ref,batched_folder,batch_started,batch_completed) VALUES ('','$useridnu','$useremail','$randomString2','$starting_folder','$date_time','$date_time')");
$i = 0;
$c = 0;
$paths = scandir($starting_folder);
foreach($paths as $path){
if($path == '.' || $path == '..'){
} else {
$path = $starting_folder.$path;
$folders = scandir($path);
$count_requests = count($folders);
$arr_content2 = array();
$com = 0;
foreach($folders as $folder){
if($folder == '.' || $folder == '..'){
} else {
++$i;
$file_name = $path.'/'.$folder;
if (substr($file_name, -1, 1) == '/')
{
$file_name = substr($file_name, 0, -1);
}
$string_1 = $file_name;
$string_1 = substr($string_1, 0, strrpos( $string_1, '/'));
$club_name = substr(strrchr($file_name, "/"), 1);
if($club_name == 'xots'){
$club_name = 'ots';
} else {
$club_name = $club_name;
}
$club_date = substr(strrchr($string_1, "/"), 1);
$club_date = chunk_split($club_date, 2, '/');
$club_date = rtrim($club_date, "/");
$club_date = substr_replace($club_date, '20', 6, 0);
$club_date = str_replace('/', '-', $club_date);
$club_date = date('Y-m-d', strtotime($club_date));
$cutyear = substr($string_1, 0, strrpos( $string_1, '/'));
$year = substr(strrchr($cutyear, "/"), 1);
$club_area = substr($cutyear, 0, strrpos( $cutyear, '/'));
$club_area = substr(strrchr($club_area, "/"), 1);
$getvenueinfo = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM `new_categories` WHERE `short_code` = '$club_name' AND `cat_city` = '$club_area' AND `allow_albums` = '1'"));
$cat_id_2 = $getvenueinfo['cat_id'];
$cat_name_2 = $getvenueinfo['cat_name'];
$cat_down_lvl_2 = $getvenueinfo['cat_down_lvl'];
$album_name = date("D dS M Y", strtotime($club_date));
$album_date = date("Y-m-d", strtotime($club_date));
$todays_date = date("Y-m-d");
if(!$cat_id_2 == '' || !$cat_name_2 == '' || !$cat_down_lvl_2 == ''){
$length = 25;
$randomString = substr(str_shuffle("0123456789"), 0, $length);
if($album_date == '1970-01-01'){
$date_time = date("Y-m-d H:i:s");
mysqli_query($conn,"INSERT INTO new_upload_error_log (error_id,error_ref,error_type,error_image,error_album,error_date,success) VALUES ('','$randomString2','Album Creation was unsuccessful (Album date does not seem correct)...','$file_name','','$date_time','4')");
} else {
$search_ID = true;
while($search_ID == true) {
$sqla = "SELECT * FROM `new_albums` WHERE `album_ref` = '$randomString'";
$resulta = $conn->query($sqla);
if (!$resulta->num_rows > 0) {
$sqlc = "SELECT * FROM `new_albums` WHERE `album_name` = '$album_name' AND `venue_name` = '$cat_name_2' AND `city_name` = '$club_area'";
$resultc = $conn->query($sqlc);
if (!$resultc->num_rows > 0) {
mysqli_query($conn,"INSERT INTO new_albums (album_id,album_name,album_desc,album_password,album_date,venue_name,venue_short_code,city_name,cat_id,album_ref,date_added,amount_of_files,viewed_count)
VALUES ('','$album_name','','','$album_date','$cat_name_2','$club_name','$club_area','$cat_down_lvl_2','$randomString','$todays_date','0','0')");
mysqli_query($conn, "UPDATE new_categories SET `last_updated` = '$todays_date' WHERE `cat_down_lvl` = '$cat_id'");
++$c;
if($image_convert_on_album_create == 1){
$com++;
$percent = intval($com/$count_requests * 100);
$arr_content2['percent'] = $percent;
$arr_content2['message'] = $com . " folders(s) processed.";
create_thumbs($conn, $randomString, $file_name, $randomString2);
file_put_contents("tmp2/" . session_id() . ".txt", json_encode($arr_content2));
} else {
}
} else {
$date_time = date("Y-m-d H:i:s");
mysqli_query($conn,"INSERT INTO new_upload_error_log (error_id,error_ref,error_type,error_image,error_album,error_date,success) VALUES ('','$randomString2','Album Creation was unsuccessful (Album already exists)...','$file_name','','$date_time','4')");
}
$search_ID = false;
}
}
}
} else {
$date_time = date("Y-m-d H:i:s");
mysqli_query($conn,"INSERT INTO new_upload_error_log (error_id,error_ref,error_type,error_image,error_album,error_date,success) VALUES ('','$randomString2','Album Creation was unsuccessful (Category could not be located)...','$file_name','','$date_time','3')");
}
}
} // 2nd foreach
}
} // 1st foreach
$date_time = date("Y-m-d H:i:s");
mysqli_query($conn,"UPDATE new_recent_batch_uses SET `batch_completed` = '$date_time' WHERE `error_ref` = '$randomString2'");
header("Location: admin_batch_upload.php?album_create_completed=1&completed=".$c."&folders=".$i."#images");
}
create_thumbs function -
function create_thumbs($conn, $albums_to_add, $choosen_files, $error_ref) {
set_time_limit(0);
$get_quality = mysqli_fetch_assoc(mysqli_query($conn, "SELECT `value` FROM `new_system_settings` WHERE `setting_id` = '31'"));
$img_quality = $get_quality['value'];
$get_resize = mysqli_fetch_assoc(mysqli_query($conn, "SELECT `value` FROM `new_system_settings` WHERE `setting_id` = '32'"));
$img_resize = $get_resize['value'];
session_start();
$dirname = $choosen_files;
chmod($dirname, 0777);
$todays_date = date("Y-m-d");
$date_time = date("Y-m-d H:i:s");
if($albums_to_add == ''){
mysqli_query($conn,"INSERT INTO new_upload_error_log (error_id,error_ref,error_type,error_image,error_album,error_date,success) VALUES ('','$error_ref','There was no album selected for this file','$choosen_files','$albums_to_add','$date_time','3')");
} else {
$check_end = substr($dirname, -1);
if($check_end == '/'){
$dirname = $choosen_files;
} else {
$dirname = $choosen_files.'/';
}
$images = glob($dirname."*.{JPG,jpg,PNG,png,gif}", GLOB_BRACE);
$filecount = count($images);
$arr_content = array();
$counti = 0;
foreach($images as $image) {
$counti++;
$percent = intval($counti/$filecount * 100);
$arr_content['percent'] = $percent;
$arr_content['message'] = $counti . " image(s) processed.";
$file = $image;
$data = $image;
$cut_name = substr($data, strpos($data, "/") + 1);
$cut_name = explode('/',$cut_name);
$cut_name = end($cut_name);
if (0 === strpos($cut_name, 'thb_')) {
mysqli_query($conn,"INSERT INTO new_upload_error_log (error_id,error_ref,error_type,error_image,error_album,error_date,success) VALUES ('','$error_ref','Compressed Image already exists in this file...','$newfile','$albums_to_add','$date_time','4')");
} else {
if (strpos($cut_name, 'thumb_') == false && strpos($cut_name, 'normal_') == false) {
if (strpos($cut_name, 'mini_') == false) {
$newfile = $dirname.'thb_'.$cut_name;
///unlink($newfile);
if (file_exists($newfile)) {
mysqli_query($conn,"INSERT INTO new_upload_error_log (error_id,error_ref,error_type,error_image,error_album,error_date,success) VALUES ('','$error_ref','Compressed Image already exists in this file...','$newfile','$albums_to_add','$date_time','4')");
} else {
$info = getimagesize($file);
list($width, $height) = getimagesize($file);
$new_width = $width * $img_resize / 100;
$new_height = $height * $img_resize / 100;
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, $img_quality);
$origional_image = $file;
$compressed_image = $newfile;
if (file_exists($compressed_image)) {
$query = mysqli_query($conn, "SELECT * FROM new_images WHERE alb_ref = '".$albums_to_add."' AND full_link = '".$origional_image."'");
if(mysqli_num_rows($query) > 0){
mysqli_query($conn,"INSERT INTO new_upload_error_log (error_id,error_ref,error_type,error_image,error_album,error_date,success) VALUES ('','$error_ref','This image already exists within this Album...','$compressed_image','$albums_to_add','$date_time','4')");
} else {
mysqli_query($conn,"INSERT INTO new_images (img_id,alb_ref,thumb_link,full_link,viewed_count,date_added) VALUES ('','$albums_to_add','$compressed_image','$origional_image','0','$todays_date')");
mysqli_query($conn,"UPDATE new_albums SET amount_of_files = amount_of_files + 1 WHERE album_ref = '$albums_to_add'");
}
} else {
mysqli_query($conn,"INSERT INTO new_upload_error_log (error_id,error_ref,error_type,error_image,error_album,error_date,success) VALUES ('','$error_ref','This image failed to compress...','$origional_image','$albums_to_add','$date_time','3')");
}
file_put_contents("tmp/" . session_id() . ".txt", json_encode($arr_content));
}
} else {
}
} else {
}
}
}
}
}
If anybody has any other solutions for me, that would be great? Even some advice on how I can work out the actual type of error I am getting. I am pretty sure it is a timeout error, because it happens on every attempt although on smaller folder structures with less files, the system works flawlessly.
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.