I have a script I’m using to allow a user to upload an image to a website. The upload is working fine. I need PHP to create a thumbnail of the image and save it to a folder named “thumbs”, located inside the directory where the full size image is stored. I’ve never done this before. I’ve tried various scripts that I found online and can’t seem to make any of them work with my upload script. Any suggestions? Here is the upload script I am using:
<?php
require_once ('includes/config.inc.php');
$page_title = 'Upload Photos';
include ('includes/header.html');
require_once (MYSQL);
if ( (isset($_GET['gid'])) ) {
$gid = $_GET['gid'];
} else { // No valid ID, kill the script.
echo '<p class="error">This page has been accessed in error.</p>';
include ('includes/footer.html');
exit();
}
$target_dir = "images/gallery/$gid/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$tf = basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
$q = "INSERT INTO images (gallery, file, added) VALUES ('$gid', '$tf', NOW())";
$r = @mysqli_query ($dbc, $q);
} else {
echo "Sorry, there was an error uploading your file.";
}
}
echo'
<form action="upload.php?gid=' . $gid . '" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
';
mysqli_close($dbc);
include ('includes/footer.html');
?>
Above your submit you need to create a directory for example:
$originalsFolder = "originals/"; //original photos only
$thumbsFolder = "thumbs/"; //thumbnails only -- 150
make sure these folders are named the same in your directory and the path is correct.
add under this:
$file = $originalsFolder.$_FILES['myfile']['name'];
createImageCopy($file, $thumbsFolder, 150);
after your submit is closed: You need to use function called createImageCopy
function createImageCopy($file, $folder, $newWidth){
//$file source : (original) path filename
//$folder : desired output folder
//$newWidth:the desired output width(height will scale porportionally)
//echo $file;
list($width, $height) = getimagesize($file);
$imgRatio = $width/$height;
$newHeight = $newWidth/$imgRatio;
//echo "width: $width | height : $height | ratio : $imgRatio";
//create image functions:
//$thumb = imagecreatetruecolor($newWidth, $newHeight);
//$source = imagecreatefromjpeg($file);
if($_FILES['myfile']['type'] =="image/jpeg"){
$thumb = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefromjpeg($file);
}else if($_FILES['myfile']['type'] == "image/png"){
$thumb = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefrompng($file);
}
if($newFileName = $folder.$_FILES['myfile']['name']){
imagejpeg($thumb,$newFileName,80);
}else if($newFileName = $folder.$_FILES['myfile']['name']){
imagepng($thumb,$newFileName,8);
}
imagedestroy($source);
imagedestroy($thumb);
}//end of createImageCopy
Keep in mind you are going to have change these example to suit your needs, but hopefully this helps.
Hi,
I tried this code… its working for me…
<html>
<head>
<script src="jquery-1.7.2.min"></script>
<script type="text/javascript">
/// first
function thumb1(files) {
if (files == null || files == undefined) {
document.write("This Browser has no support for HTML5 FileReader yet!");
return false;
}
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
}
var reader = new FileReader();
if (reader != null) {
reader.onload = GetThumbnail1;
reader.readAsDataURL(file);
}
}
}
function GetThumbnail1(e) {
var myCan = document.createElement('canvas');
var img = new Image();
img.src = e.target.result;
img.onload = function () {
myCan.id = "myTempCanvas";
myCan.width = Number(150);
myCan.height = Number(150);
if (myCan.getContext) {
var cntxt = myCan.getContext("2d");
cntxt.drawImage(img, 0, 0, myCan.width, myCan.height);
var dataURL = myCan.toDataURL();
if (dataURL != null && dataURL != undefined) {
var nImg = document.createElement('img');
nImg.src = dataURL;
$("#up1 img:last-child").remove();
$("#up1").append(nImg);
}
else
alert('unable to get context');
}
}
}
/// second
function thumb2(files) {
if (files == null || files == undefined) {
document.write("This Browser has no support for HTML5 FileReader yet!");
return false;
}
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
}
var reader = new FileReader();
if (reader != null) {
reader.onload = GetThumbnail2;
reader.readAsDataURL(file);
}
}
}
function GetThumbnail2(e) {
var myCan = document.createElement('canvas');
var img = new Image();
img.src = e.target.result;
img.onload = function () {
myCan.id = "myTempCanvas";
myCan.width = Number(150);
myCan.height = Number(150);
if (myCan.getContext) {
var cntxt = myCan.getContext("2d");
cntxt.drawImage(img, 0, 0, myCan.width, myCan.height);
var dataURL = myCan.toDataURL();
if (dataURL != null && dataURL != undefined) {
var nImg = document.createElement('img');
nImg.src = dataURL;
$("#up2 img:last-child").remove();
$("#up2").append(nImg);
}
else
alert('unable to get context');
}
}
}
/// third
function thumb3(files) {
if (files == null || files == undefined) {
document.write("This Browser has no support for HTML5 FileReader yet!");
return false;
}
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
}
var reader = new FileReader();
if (reader != null) {
reader.onload = GetThumbnail3;
reader.readAsDataURL(file);
}
}
}
function GetThumbnail3(e) {
var myCan = document.createElement('canvas');
var img = new Image();
img.src = e.target.result;
img.onload = function () {
myCan.id = "myTempCanvas";
myCan.width = Number(150);
myCan.height = Number(150);
if (myCan.getContext) {
var cntxt = myCan.getContext("2d");
cntxt.drawImage(img, 0, 0, myCan.width, myCan.height);
var dataURL = myCan.toDataURL();
if (dataURL != null && dataURL != undefined) {
var nImg = document.createElement('img');
nImg.src = dataURL;
$("#up3 img:last-child").remove();
$("#up3").append(nImg);
}
else
alert('unable to get context');
}
}
}
/// fourth
function thumb4(files) {
if (files == null || files == undefined) {
document.write("This Browser has no support for HTML5 FileReader yet!");
return false;
}
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
}
var reader = new FileReader();
if (reader != null) {
reader.onload = GetThumbnail4;
reader.readAsDataURL(file);
}
}
}
function GetThumbnail4(e) {
var myCan = document.createElement('canvas');
var img = new Image();
img.src = e.target.result;
img.onload = function () {
myCan.id = "myTempCanvas";
myCan.width = Number(150);
myCan.height = Number(150);
if (myCan.getContext) {
var cntxt = myCan.getContext("2d");
cntxt.drawImage(img, 0, 0, myCan.width, myCan.height);
var dataURL = myCan.toDataURL();
if (dataURL != null && dataURL != undefined) {
var nImg = document.createElement('img');
nImg.src = dataURL;
$("#up4 img:last-child").remove();
$("#up4").append(nImg);
}
else
alert('unable to get context');
}
}
}
</script>
</head>
<body>
<div class="backers_section">
<div class="sub_title"><span>upload more photos</span><a href="" class="help">?</a></div>
<div class="clearfix upload_photo_wrap">
<div class="backers">
<div class="upload_photo" id="up1">
<input id="image" type="file" name="upload-image1" multiple onchange="thumb1(this.files)">
<span>Upload</span>
</div>
</div>
<div class="backers">
<div class="upload_photo" id="up2">
<input id="image" type="file" name="upload-image2" multiple onchange="thumb2(this.files)">
<span>Upload</span>
</div>
</div>
<div class="backers">
<div class="upload_photo" id="up3">
<input id="image" type="file" name="upload-image3" multiple onchange="thumb3(this.files)">
<span>Upload</span>
</div>
</div>
<div class="backers">
<div class="upload_photo" id="up4">
<input id="image" type="file" name="upload-image4" multiple onchange="thumb4(this.files)">
<span>Upload</span>
</div>
</div>
</div>
</body>
</html>
Thanks,
Techbuddy1
I finally got a chance to get back to this. I’m still doing something wrong. I’ll post the chunk of code where I suspect the problem is, then I’ll post the entire code. I’m guessing I need to change some values here, but I’m not sure what to change them to…
//create image functions:
$thumb = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefromjpeg($file);
if($_FILES['myfile']['type'] =="image/jpeg" OR $_FILES['myfile']['type'] =="image/jpg"){
$thumb = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefromjpeg($file);
}else if($_FILES['myfile']['type'] == "image/png"){
$thumb = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefrompng($file);
}else if($_FILES['myfile']['type'] == "image/gif"){
$thumb = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefromgif($file);
}
if($newFileName = $folder.$_FILES['myfile']['name']){
imagejpeg($thumb,$newFileName,80);
}else if($newFileName = $folder.$_FILES['myfile']['name']){
imagepng($thumb,$newFileName,8);
}
imagedestroy($source);
imagedestroy($thumb);
<?php
require_once ('includes/config.inc.php');
$page_title = 'Upload Photo';
include ('includes/header.html');
if ( (isset($_GET['gid'])) ) {
$gid = $_GET['gid'];
} else { // No valid ID, kill the script.
echo '<p class="error">This page has been accessed in error.</p>';
include ('includes/footer.html');
exit();
}
require_once (MYSQL);
$originalsFolder = "images/gallery/$gid/"; //original photos only
$thumbsFolder = "images/gallery/$gid/thumbs/"; //thumbnails only -- 150
$target_dir = "images/gallery/$gid/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$tf = basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". $tf . " has been uploaded.";
$file = $target_file;
createImageCopy($file, $thumbsFolder, 150);
$q = "INSERT INTO images (gallery, file, added) VALUES ('$gid', '$tf', NOW())";
$r = @mysqli_query ($dbc, $q);
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
function createImageCopy($file, $folder, $newWidth){
$gid = $_GET['gid'];
global $target_file;
$file = $target_file;
$folder = "images/gallery/$gid/thumbs/";
$newWidth = "150px";
echo $file;
list($width, $height) = getimagesize($file);
$imgRatio = $width/$height;
$newHeight = $newWidth/$imgRatio;
echo "width: $width | height : $height | ratio : $imgRatio";
//create image functions:
$thumb = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefromjpeg($file);
if($_FILES['myfile']['type'] =="image/jpeg" OR $_FILES['myfile']['type'] =="image/jpg"){
$thumb = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefromjpeg($file);
}else if($_FILES['myfile']['type'] == "image/png"){
$thumb = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefrompng($file);
}else if($_FILES['myfile']['type'] == "image/gif"){
$thumb = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefromgif($file);
}
if($newFileName = $folder.$_FILES['myfile']['name']){
imagejpeg($thumb,$newFileName,80);
}else if($newFileName = $folder.$_FILES['myfile']['name']){
imagepng($thumb,$newFileName,8);
}
imagedestroy($source);
imagedestroy($thumb);
}//end of createImageCopy
echo'
<form action="upload.php?gid=' . $gid . '" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
';
?>
Have you created the folder structure to store the images in filezilla or where ever you’re storing these images?
See how you do with this version.
<?php
require_once "includes/config.inc.php";
$page_title = 'Upload Photos';
include "includes/header.html";
require_once "MYSQL";
if(isset($_GET['gid'])){
$gid = $_GET['gid'];
}else{ // No valid ID, kill the script.
echo '<p class="error">This page has been accessed in error.</p>';
include ('includes/footer.html');
exit();
}
if(isset($_POST['submit'])) {
$target_dir = "images/gallery/$gid/";
$target_file = $target_dir . basename($_FILES['fileToUpload']['name']);
$file = $_FILES['fileToUpload']['tmp_name'];
$tf = basename($_FILES['fileToUpload']['name']);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES['fileToUpload']['tmp_name']);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES['fileToUpload']['size'] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if(!is_dir("images/gallery/$gid/thumbs")):
mkdir("images/gallery/$gid/thumbs", 0755);
endif;
$folder = "images/gallery/$gid/thumbs/";
$newFileName = $folder . basename( $_FILES['fileToUpload']['name']);
$newWidth = "150";
list($width, $height) = getimagesize($file);
$imgRatio = $width/$height;
$newHeight = $newWidth/$imgRatio;
if($_FILES['fileToUpload']['type'] =="image/jpeg" || $_FILES['fileToUpload']['type'] == "image/jpg"){
$thumb = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefromjpeg($file);
imagecopyresampled($thumb,$source, 0,0,0,0, $newWidth, $newHeight,$width, $height);
imagejpeg($thumb,$newFileName,100);
}elseif($_FILES['fileToUpload']['type'] == "image/png"){
$thumb = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefrompng($file);
imagecopyresampled($thumb,$source, 0,0,0,0, $newWidth, $newHeight,$width, $height);
imagepng($thumb,$newFileName,9);
}elseif($_FILES['fileToUpload']['type'] == "image/gif"){
$thumb = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefromgif($file);
imagecopyresampled($thumb,$source, 0,0,0,0, $newWidth, $newHeight,$width, $height);
imagegif($thumb,$newFileName);
}
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file)) {
echo "The file ". basename( $_FILES['fileToUpload']['name']). " has been uploaded.";
$q = "INSERT INTO images (gallery, file, added) VALUES ('$gid', '$tf', NOW())";
$r = @mysqli_query ($dbc, $q);
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
echo'
<form action="upload.php?gid=' . $gid . '" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>';
mysqli_close($dbc);
include "includes/footer.html";
?>
This works. Somewhat. It creates the thumbnail-size image and uploads it to the thumbs folder. The only issue I have with it is that the thumbnail image is all black. The actual image isn’t there.
<?php
require_once ('includes/config.inc.php');
$page_title = 'Upload Photo';
include ('includes/header.html');
if ( (isset($_GET['gid'])) ) {
$gid = $_GET['gid'];
} else { // No valid ID, kill the script.
echo '<p class="error">This page has been accessed in error.</p>';
include ('includes/footer.html');
exit();
}
require_once (MYSQL);
$originalsFolder = "images/gallery/$gid/"; //original photos only
$thumbsFolder = "images/gallery/$gid/thumbs/"; //thumbnails only -- 150
$target_dir = "images/gallery/$gid/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$tf = basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". $tf . " has been uploaded.";
$file = $target_file;
createImageCopy($file, $thumbsFolder, 150);
$q = "INSERT INTO images (gallery, file, added) VALUES ('$gid', '$tf', NOW())";
$r = @mysqli_query ($dbc, $q);
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
function createImageCopy($file, $folder, $newWidth){
$gid = $_GET['gid'];
global $target_file;
$file = $target_file;
$folder = "images/gallery/$gid/thumbs/";
$newWidth = "150px";
echo $file;
list($width, $height) = getimagesize($file);
$imgRatio = $width/$height;
$newHeight = $newWidth/$imgRatio;
echo "width: $width | height : $height | ratio : $imgRatio";
//create image functions:
$thumb = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefromjpeg($file);
if($_FILES['fileToUpload']['imageFileType'] =="image/jpeg" OR $_FILES['myfile']['type'] =="image/jpg"){
$thumb = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefromjpeg($file);
}else if($_FILES['fileToUpload']['imageFileType'] == "image/png"){
$thumb = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefrompng($file);
}else if($_FILES['fileToUpload']['imageFileType'] == "image/gif"){
$thumb = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefromgif($file);
}
if($newFileName = $folder.$_FILES['fileToUpload']['name']){
imagejpeg($thumb,$newFileName,80);
}else if($newFileName = $folder.$_FILES['fileToUpload']['name']){
imagepng($thumb,$newFileName,80);
}
imagedestroy($source);
imagedestroy($thumb);
}//end of createImageCopy
echo'
<form action="upload.php?gid=' . $gid . '" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
';
mysqli_close($dbc);
include ('includes/footer.html');
?>
Yes, the folders are there beforehand.
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.