I am trying to resize an image that I have uploaded with a form. I am using the script scene here: http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/
I am also using the following code to upload the image:
upload.php:
<?php
session_start();
require_once "database.php";
db_connect();
require_once "auth.php";
$current_user = current_user();
$emailstring = $current_user['email'];
//Check to see if the type of file uploaded is a valid image type
function is_valid_type($file)
{
//This is an array that holds all the valid image MIME types
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
//Set some constants
//This variable is the path to the image folder where all the images are going to be stored
//Note that there is a trailing forward slash
$TARGET_PATH = "profile_images/";
//Get our POSTed variables
$upload_picture_fileinput = $_FILES['upload_picture_fileinput'];
//Sanitize input
$upload_picture_fileinput['name'] = mysql_real_escape_string($upload_picture_fileinput['name']);
//Build our target path full string. This is where the file will be moved to
//i.e. profile_images/picture.jpg
$TARGET_PATH .= $upload_picture_fileinput['name'];
if(!is_valid_type($upload_picture_fileinput)) {
$_SESSION['error'] = "You must upload a jpeg, gif, bmp, or png";
header("Location: account.php");
exit;
}
//attempt to move the file from its temporary directory to its new home
if (move_uploaded_file($upload_picture_fileinput['tmp_name'], $TARGET_PATH)) {
$sql = "UPDATE `users` SET `profile_image_filename`='" . $upload_picture_fileinput['name'] . "'
WHERE email='$emailstring'";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
header("Location: account.php");
exit;
}
else
{
$_SESSION['error'] = "Could not upload file. Check read/write permissions on the directory";
header("Location: account.php") ;
exit;
}
and where my form is:
<div class="pictures add_pictures">
<div class="add_picture">
<div class="upload_picture">
<form action="upload.php" method="POST" enctype="multipart/form-data" name="upload_picture_form" class="upload_picture_form">
<span class="add_picture_label">+ Add a Profile Picture</span>
<input type="file" name="upload_picture_fileinput" class="upload_picture_file_input"/>
<input type="hidden" name="MAX_FILE_SIZE" value="100000"/>
<br><br><br><br><br><br><br>
<input type="submit" id="submit" value="Upload" />
</form>
</div>
</div>
</div>
<?php
$sql = "select * FROM `users` WHERE `id`='$id'";
$result = mysql_query($sql) or die ("Could not access DB: " . mysql_error());
$row = mysql_fetch_assoc($result);
echo "<p>";
echo "<img src=\"profile_images/" . $row['profile_image_filename'] . "\" alt=\"\" /><br />";
echo "</p>";
?>
//not currently working
<img src="/imageresize.php"/>
The echo above prints the picture out fine, but when I try to use that filename to resize the image, it does not appear/work.
<?php
session_start();
require_once "database.php";
db_connect();
require_once "auth.php";
$current_user = current_user();
$resized_image = '\"profile_images/" . $row['profile_image_filename'] . "\" alt=\"\" /';
header('Content-Type: image/jpg');
include('SimpleImage.php');
$image = new SimpleImage();
$image->load($resized_image);
$image->resizeToWidth(300);
$image->output();
?>
I am connecting to the database fine and the image filename is being saved in my database. I just don't know why the file path above will print the picture, but not work in the resize script. Please help if you can. Thank you.
The code below creates a function named createThumbs that will get three parameters. The first and the second is correspondingly the path to the directory that contains original images and the path to the directory in which thumbnails will be placed. The third parameter is the width you want for the thumbnail images.
<?php
function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth )
{
// open the directory
$dir = opendir( $pathToImages );
// loop through it, looking for any/all JPG files:
while (false !== ($fname = readdir( $dir ))) {
// parse path for the extension
$info = pathinfo($pathToImages . $fname);
// continue only if this is a JPEG image
if ( strtolower($info['extension']) == 'jpg' )
{
echo "Creating thumbnail for {$fname} <br />";
// load image and get image size
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save thumbnail into a file
imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
}
}
// close the directory
closedir( $dir );
}
// call createThumb function and pass to it as parameters the path
// to the directory that contains images, the path to the directory
// in which thumbnails will be placed and the thumbnail's width.
// We are assuming that the path will be a relative path working
// both in the filesystem, and through the web for links
createThumbs("upload/","upload/thumbs/",100);
?>
Looks like in $resized_image you have added the html alt tag which should, of course, not be part of the parameter you are feeding into $image->load($resized_image);.
Try changing this to
$image->load('profile_images/' . $row['profile_image_filename']);
instead of the string that already targets the html rendering.
Related
I'm making an upload application and I have a script that once the images are uploaded they are resized but the original dimensions are stored to be used later on. the index.php should should show the images on the screen.
I've stored the image path instead of a blob on the database and using the 'path' variable to show it on the browser.
The search works but the images are not displaying and I can't find the reason why.
Im new to php/mysql so any help is appreciated on why my images are not showing up.
upload.php
<?php
require_once 'includes/config.inc.php';
require_once 'includes/functions.php';
// Add the heading to output
$output = '<h1>Gallery</h1>';
// Echo the gathered output
echo $output;
// Include the HTML header
include_once 'includes/head.html';
// Check if the form has been submitted...
if (isset($_POST['fileupload'])
&& isset($_POST['title']) && isset($_POST['description'])) {
$title = $_POST['title'];
$description = $_POST['description'];
if (is_uploaded_file($_FILES['userfile']['tmp_name'] )) {
$updir = dirname(__FILE__).'/uploads/';
//$upfilename = $_FILES['userfile']['name'];
$ext=end(explode(".", $_FILES['userfile']['name']));//gets extension
$newname = $updir.$title;
$tmpname = $_FILES['userfile']['tmp_name'];
$newimage = $newname.'.'.$ext;
$path = $newimage;
//if file is an image, upload it
if($_FILES['userfile']['type'] == 'image/jpeg'){
if (move_uploaded_file($tmpname, $newimage)) {
//print if file was uploaded
//echo 'File successfully uploaded';
list($width, $height) = getimagesize($newimage);
//Add values to the DB
$sql = "INSERT INTO Images VALUES(NULL, '$title', '$description', '$width', '$height', '$path')";
$result = mysqli_query($link, $sql);
if(!$result) die ("Database access failed: " . $link->error);
$w = $width;
$h = $height;
resize($newimage, $width, $height);
}
} else {
//print if file failed
echo 'File upload failed';
}
}
//echo debug();
}
// Include the HTML footer
?>
index.php(The sql script is here)
<?php
require_once 'includes/config.inc.php';
require_once 'includes/functions.php';
if (!isset($_GET['page'])) {
$id = 'home'; // display home page
} else {
$id = $_GET['page']; // else requested page
}
switch ($id) {
case 'home' :
include 'uploads.php';
break;
default :
include 'views/404.php';
}
$sql = 'SELECT * FROM Images';
$result = mysqli_query($link, $sql);
if(!$result){
die(mysqli_error($link));
}else{
while($row = mysqli_fetch_array($result)){
echo '<div><a href= "#">
<img src="'.$row['path'].'" width=150 height=150 alt="'.$row['title'].'" /></a></div>';
}
mysqli_free_result($result);
}
/*
Alternative way of showing the right images
$images = glob('uploads/*.jpg');
for($i = 0; $i < count($images); $i++){
list($w,$h) = getimagesize($images[$i]);
$allimages = $images[$i];
echo '<div><a href="'.$allimages.'">
<img src="'.$allimages.'" width="'.$w.'" height="'.$h.'" alt="" /></a>
</div><br/>';
}*/
include_once 'includes/footer.html';
?>
The problem is that you are using dirname(__FILE__) for the start of the path of your image and store that complete path in the database.
According to the manual dirname:
Returns the path of the parent directory.
And __FILE__:
The full path and filename of the file with symlinks resolved.
So you are storing your image using a absolute path on the local file system of the server.
However, that absolute path is not absolute relative to the root of the web-server so the browser will not find the images.
The solution is to use an absolute path when you move the uploaded image, but store a path that is absolute relative to the root of the web-server.
In your case you can probably use the /uploads/ path for that although that would depend on the exact file structure:
...
// no dirname here
$updir = '/uploads/';
//$upfilename = $_FILES['userfile']['name'];
$ext=end(explode(".", $_FILES['userfile']['name']));//gets extension
$newname = $updir.$title;
$tmpname = $_FILES['userfile']['tmp_name'];
$newimage = $newname.'.'.$ext;
$path = $newimage;
//if file is an image, upload it
if($_FILES['userfile']['type'] == 'image/jpeg'){
// only use dirname() here
if (move_uploaded_file($tmpname, dirname(__FILE__) . $newimage)) {
...
You have to add domain of your server to the src attribute of img tag so it'll became an absolute path for users to see the images:
echo '<div><a href= "#">
<img src="'$_SERVER['HTTP_HOST'].$row['path'].'" width=150 height=150 alt="'.$row['title'].'" /></a></div>';
How can i resize proportionaly image in php without "squishing" ? I need some solution, i was searching here, but i could't find anything what i need.
What i have:
<?php
if (isset($_SESSION['username'])) {
if (isset($_POST['upload'])) {
$allowed_filetypes = array('.jpg', '.jpeg', '.png', '.gif');
$max_filesize = 10485760;
$upload_path = 'gallery/';
$filename = $_FILES['userfile']['name'];
$ext = substr($filename, strpos($filename, '.'), strlen($filename) - 1);
if (!in_array($ext, $allowed_filetypes)) {
die('The file you attempted to upload is not allowed.');
}
if (filesize($_FILES['userfile']['tmp_name']) > $max_filesize) {
die('The file you attempted to upload is too large.');
}
if (!is_writable($upload_path)) {
die('You cannot upload to the specified directory, please CHMOD it to 777.');
}
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path.$filename)) {
$q = mysqli_query($connection, "UPDATE users SET avatar='".$_FILES['userfile']['name']."' WHERE username ='".$_SESSION['username']."'");
echo "<font color='#5cb85c'>Браво, успешно си качил/а профилна снимка!</font>";
} else {
echo 'There was an error during the file upload. Please try again.';
}
}
echo ' <form action="images.php" method="post" enctype="multipart/form-data"> ';
echo ' <input type="file" name="userfile"/>';
echo ' <input type="submit" name="upload" value="Качи">';
echo ' </form>';
} else {
echo "<font color='#ec3f8c'>Съжелявам! За да качиш снимка във профила си, <a href='login.php'><font color='#ec3f8c'><b> трябва да се логнеш</b> </font></a></font>";
}
?>
I want to add something like this:Click here
how i call images?
echo '<a href="profiles.php?id='.$rowtwo['id'].'">';
echo"<img src='gallery/".$rowtwo['avatar']."' width='170px' height='217px'/>";
echo'</a>';
I save my image of avatar in DB in users as avatar.
It's much easier to use JS. It also works better because you're letting the client do the slow work of manipulation vs using your finite server resources for that task.
Here's a sample:
//This is the URL to your original image
var linkUrl = "http://www.mywebsite.com/myimage.png";
//This is a div that is necessary to trick JS into letting you manipulate sizing
//Just make sure it exists and is hidden
var img = $('#HiddenDivForImg');
//This is a call to the function
image_GetResizedImage(img, linkUrl);
//This function does the magic
function image_GetResizedImage(img, linkUrl) {
//Set your max height or width dimension (either, not both)
var maxDim = 330;
//Define the equalizer to 1 to avoid errors if incorrect URL is given
var dimEq = 1;
//This determines if the larger dimension is the images height or width.
//Then, it divides that dimension by the maxDim to get a decimal number for size reduction
if (img.height() > maxDim || img.width() > maxDim) {
if (img.height() > img.width()) {
dimEq = maxDim / img.height();
} else {
dimEq = maxDim / img.width();
}
}
var imageOutput = "<a href='" + linkUrl + "' target='_blank'>View Larger</a><br /><a href='" + result +
"' target='_blank'><img src='" + linkUrl + "' style='width: " + img.width() * dimEq
+ "px; height: " + img.height() * dimEq + "px' /></a>";
//This returns a URL for the image with height and width tags of the resized (non-squished) image.
return imageOutput;
}
For image manipulation in PHP you can use Imagemagick.
http://www.imagemagick.org/
It's the scale command you are looking for.
Here I have created a function with your reference link, you can use it like this
Call it
//Resize uploaded image
resize_image($_FILES['userfile'], 100, 200);
//Or if you want to save image with diffrent name
$filename = $upload_path.$_SESSION['username'].'-avatar.jpg';
resize_image($_FILES['userfile'], 100, 200, $newfilename);
//if (move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path.$filename)) {
$q = mysqli_query($connection, "UPDATE users SET avatar='".$filename."' WHERE username ='".$_SESSION['username']."'");
echo "<font color='#5cb85c'>Браво, успешно си качил/а профилна снимка!</font>";
} else {
echo 'There was an error during the file upload. Please try again.';
}
Function
function resize_image($image_src, $w = 100, $h = 100, $save_as = null) {
// Create image from file
switch(strtolower($image_src['type']))
{
case 'image/jpeg':
$image = imagecreatefromjpeg($image_src['tmp_name']);
break;
case 'image/png':
$image = imagecreatefrompng($image_src['tmp_name']);
break;
case 'image/gif':
$image = imagecreatefromgif($image_src['tmp_name']);
break;
default:
exit('Unsupported type: '.$image_src['type']);
}
// Target dimensions
$max_width = $w;
$max_height = $h;
// Get current dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);
// Calculate the scaling we need to do to fit the image inside our frame
$scale = min($max_width/$old_width, $max_height/$old_height);
// Get the new dimensions
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
// 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);
if($save_as) {
//Save as new file
imagejpeg($new, $save_as, 90);
}else{
//Overwrite image
imagejpeg($new, $image_src['tmp_name'], 90);
}
// Destroy resources
imagedestroy($image);
imagedestroy($new);
}
I use http://image.intervention.io/. You can scale, cache, store, convert and do various image manipulation tasks.
Very easy to use.
// load the image
$img = Image::make('public/foo.jpg');
// resize the width of the image to 300 pixels and constrain proportions.
$img->resize(300, null, true);
// save file as png with 60% quality
$img->save('public/bar.png', 60);
I've written a code to upload and unzip a zip file of images to a folder. This file is upload2.php, there is also an upload1.php which I use to input the folder name.
I'm trying to add a function wherein the script will also, after unzipping the files and saving them into the target folder, convert them into thumbnails and then ALSO save those thumbnails into another folder.
The script is also INSERTing various data about all the separate files into a mysql database.
Here's the code:
<?php // actual code for upload
$dirname = trim($_POST['dirname']);
$taken = trim($_POST['taken']);
$location = trim($_POST['location']);
$subject = trim($_POST['subject']);
$rooturl = "http://example.com/test";
$dateurl = $dirname.'/';
$mainurl = $rooturl.$dateurl;
require_once 'connect.php';
$sqlselect = "SELECT * from learning2 WHERE location='test2';";
$result = mysql_query($sqlselect) or die(mysql_error());
$thumbwidth = 100;
$thumbheight = 100;
function makeThumbnail($sourcefile, $endfile, $thumbwidth, $thumbheight, $quality) {
ini_set( "memory_limit","192M");
// Takes the sourcefile (path/to/image.jpg) and makes a thumbnail from it
// and places it at endfile (path/to/thumb.jpg).
// Load image and get image size.
if (file_exists($sourcefile)) {
$img = imagecreatefromjpeg($sourcefile);
$width = imagesx( $img );
$height = imagesy( $img );
if ($width > $height) {
$newwidth = $thumbwidth;
$divisor = $width / $thumbwidth;
$newheight = floor( $height / $divisor);
} else {
$newheight = $thumbheight;
$divisor = $height / $thumbheight;
$newwidth = floor( $width / $divisor );
}
// Create a new temporary image.
$tmpimg = imagecreatetruecolor( $newwidth, $newheight );
// Copy and resize old image into new image.
imagecopyresampled( $tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
// Save thumbnail into a file.
imagejpeg( $tmpimg, $endfile, $quality);
// release the memory
imagedestroy($tmpimg);
imagedestroy($img);
} else {
echo "The file " . $sourcefile . " does not exist";
}
}
function makeDirectory($dirname) { //This function makes both the directory the photos will be unzipped into, and a directory nested within that for the thumbnails of those photos.
mkdir($dirname, 0777);
mkdir($dirname.'/thumbs', 0777);
}
if(isset($_POST['submit'])) {
if (file_exists($dirname) && is_dir($dirname)) { // determines whether or not this particular directory exists
echo "the directory exists and it is called: " . $mainurl;
echo "<br />";
} else {
makeDirectory($dirname);
}
if($_FILES["zip_file"]["name"]) { // pull the name of the zip file from the upload
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename); //format the filename for a variable
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false; // let user know if the zip file has not been uploaded
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
$target_path = $dirname."/".$name; // get the $target_path variable to for the move_uploaded_file() function.
if(move_uploaded_file($source, $target_path)) { // this block extracts the zip files and moves them to the $dirname directory
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo($dirname."/");
$images = array();
for ($i=0; $i<$zip->numFiles; $i++) {
$images[] = $zip->getNameIndex($i);
}
$zip->close();
unlink($target_path);
}
$message = "Your .zip file was uploaded and unpacked.";
}
} else {
$message = "There was a problem with the upload. Please try again.";
}
$newdir = scandir($dirname);
foreach ($newdir as $key => $value) {
if ($value!='.' && $value!='..') {
$thumburl = $rooturl.$dateurl.'thumbs/'.$value;
echo 'Key: ' . "$key;" . ' Value: ' . "$value" ."<br />\n";
$sourcefile = $value;
$endfile = 'http://example.com/test/'.$dirname.'/thumbs/'.'$value';
makeThumbnail($sourcefile, $endfile, $thumbwidth, $thumbheight, $quality);
mysql_query("INSERT INTO learning3 (taken, location, subject, rooturl, dateurl, imagename, thumburl) VALUES ('$taken', '$location', '$subject', '$rooturl', '$dateurl', '$value', '$thumburl')");
echo "<br />";
echo '<img src="'.$thumburl.'>< /img>';
echo "$value"." inserted successfully!";
} else {
echo $value." not inserted, thumbnail not created.";
echo $insert_sql . '<BR>' . mysql_error();
}
}
} else { echo 'Please input your data and select a zip file.';
}
echo '<html>';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR...nsitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
if($message) echo "<p>$message</p>";
if($taken) echo "<p>pictures taken on: " . $taken . "</br>";
if($subject) echo "<p>subject: " . $subject . "</br>";
if($location) echo "<p>location: " . $location . "</br>";
if(($rooturl) && ($dateurl)) echo "<p>directory is called: " . $rooturl.$dateurl. "</br>";
?>
<form enctype="multipart/form-data" method="post" action="upload2.php">
<label for="dirname">Directory to use?: </label> <input name="dirname" size="20" type="text" value="<?php echo $dirname; ?>" /><br />
<label for="taken">When was this taken?:</label> <input name="taken" size="20" type="text" value="<?php echo $dirname; ?>" /><br />
<label for="location">Where was this taken?</label> <input name="location" size="20" type="text" /><br />
<label for="subject">subject?</label> <input name="subject" size="20" type="text" /><br />
<!--< />-->
<input type=hidden name="mainurl" value="<?php echo "http://example.com/test/".'$dirname;' ?>" />
<label>Choose a zip file to upload: <input type="file" name="zip_file" /></label>
<br />
<input type=submit name='submit' value="Upload" />
</form>
</body>
</html>
The thing I can't figure out about the script is this: it does not create the thumbnails and put them into the new thumbnail folder, although it does create the correct folders, and the mysql inserts are successful. Rather than the thumbnails being saved, I get the simple error messsage "the file does not exist." The thing is, I know the file does exist, because the earlier part of the script creates it. Can anyone tell me what I'm doing wrong here, or even give me a hint as to where I should be looking?
So, I tested the makeThumbnail() function directly (both with files in the current directory and then with files outside of it) and in both cases, it worked fine. It's kinda hard to know exactly what's going on without being able to fully execute the code, but my guess is that it lies in the call to makeThumbnail(). Is it possible that you're forgetting to prepend the path to $sourcefile before making the call? Is it possible there are white spaces at the beginning or end of $sourcefile? The function works, so it has to be the calling code that's responsible.
Just skimming that code, shouldn't the call be: makeThumbnail($dirname.$sourcefile[...]) instead of makeThumbnail($sourcefile[...]) (or "$dirname/$sourcefile", but you get the point)?
I am trying to upload various images into a dynamically created folder on my server, then take each image and resize it while uploading it into the folder as well creating a new image and a new name.. example: image.jpg (original image) and image-resized.jpg (being the thumbnail image).
The thing I can not figure out is how to resize all images. I am not sure if I should put it in a loop. All I need is for each image I upload (could be 5 a time). It loops through and resizes them all and not just a single image. Here is my code any help would be appreciated!
Code to create folders and move picture into those folders:
// Desired folder structure
$structure = './Fotos/'.$newfolder;
// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.
if (!mkdir($structure, 0, true)) {
die('Failed to create folders...');
}else{
$placefoldername = mysql_query("INSERT INTO datefolders (FolderDate) VALUES ('$newfolder')") or die(mysql_error());
echo "<div class=\"success\">El folder fue agregado con exito.<input type=\"button\" name=\"close\" value=\"X\" class=\"close\" /></div>";
}}
// ...
}
if(isset($_POST['upload'])){
$FolderDate = $_POST['fecha-folder'];
$FolderName = $_POST['FolderName'];
$hour = $_POST['hour'];
// Desired folder structure
$structure = './Fotos/'.$FolderDate.'/'.$hour.'/'.$FolderName;
// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.
for($i=0;$i<count($_FILES['fileupload']['name']);$i++) {
$names = $_FILES['fileupload']['name'][$i];
$target_path = "Fotos/".$FolderDate."/".$hour."/".$FolderName."/";
$target_path = $target_path . basename( $_FILES['fileupload']['name'][$i]);
if(move_uploaded_file($_FILES['fileupload']['tmp_name'][$i], $target_path)) {
$success = 1;
Code to create a smaller (resized image) and also place into the already created folder:
$img = $names;
$imgPath = $structure;
function resizeImage($img, $imgPath, $suffix, $by, $quality)
{
//Create a thunbnail image by resizing the picture
// Open the original image.
$original = imagecreatefromjpeg("$imgPath/$img") or die("Error Opening original (<em>$imgPath/$img</em>)");
list($width, $height, $type, $attr) = getimagesize("$imgPath/$img");
// Determine new width and height.
$newWidth = ($width/$by);
$newHeight = ($height/$by);
// Resample the image.
$tempImg = imagecreatetruecolor($newWidth, $newHeight) or die("Cant create temp image");
imagecopyresized($tempImg, $original, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height) or die("Cant resize copy");
// Create the new file name.
$newNameE = explode(".", $img);
$newName = ''. $newNameE[0] .''. $suffix .'.'. $newNameE[1] .'';
// Save the image.
imagejpeg($tempImg, "$imgPath/$newName", $quality) or die("Cant save image");
// Clean up.
imagedestroy($original);
imagedestroy($tempImg);
return true;
}
$resize = resizeImage($img, $imgPath, "-resized", 23, 100);
Why are you defining the function resizeImage in the for loop? It is being redefined every time the loop iterates. This could be part of the problem. Define the function outside the loop and see if that works.
you can try;
when your first image proccess end use imagedestroy() then second image will proccessed.
When i made this function:
function makeThumbnail($type, $name, $size, $tmp_name, $thumbSize) {
//make sure this directory is writable!
$path_thumbs = "uploaded_files/";
//the new width of the resized image, in pixels.
$img_thumb_width = $thumbSize; //
$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 = $type;
$file_name = $name;
$file_size = $size;
$file_tmp = $tmp_name;
//check if you have selected a file.
echo $file_tmp."<br>";
echo $file_name."<br>";
echo $file_type."<br>";
echo $file_size."<br>";
if(!is_uploaded_file($file_tmp)){
echo "Error: Please select a file to upload!. <br>--back";
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))) {
echo "Wrong file extension. <br>--back";
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!
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);
ImageDestroy ($resized_img);
ImageDestroy ($new_img);
}
//ok copy the finished file to the thumbnail directory
// move_uploaded_file ($file_tmp, "$path_big/$rand_name.$file_ext");
/*
Don't want to copy it to a separate directory?
Want to just display the image to the user?
Follow the following steps:
2. Uncomment this code:
/*
/* UNCOMMENT THIS IF YOU WANT */
echo "OK THUMB " . $thumbSize;
exit();
//*/
//and you should be set!
//success message, redirect to main page.
$msg = urlencode("$title was uploaded! Upload More?");
}
Then it stopped working, but outside a function, it works good.
As you can see i added "echo $file...." because i wanted to see if they have value, and they do have the right values.
I just get the error Error: Please select a file to upload.
This function is running after an normal upload image script(full size).
When i call the function i do:
makeThumbnail($_FILES[$fieldname]['type'], $_FILES[$fieldname]['name'], $_FILES[$fieldname]['size'], $_FILES[$fieldname]['tmp_name'], 100);
At my other file where its not in a function, theres no difference only that the variables is:
$file_type = $_FILES['file']['type'];
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
But it should work, I cant find anything wrong, but it doesnt and i keep getting that error. If i remove the is_uploaded_file function, i get a bunch of another errors.
Make sure you are not using move_uploaded_file() before calling the function.
I use timthumb to process the image into a thumbnail when it outputs it to screen, instead of when it's uploaded.
It means you only have one file and not one master size and one thumb size. TimThumb reduces the size of the file on serverside so it appears nice and smooth on the browserside. Have a look at it: TimThumb Link