unable in creating thumb IMAGE IS BLACK [duplicate] - php

This question already has answers here:
Unable to create thumb, image is black
(4 answers)
Closed 8 years ago.
Am uploading Multiple image from single input and create thumb form all uploaded image on fly But when i run code i get only black image but orginal image is same as uploaded
$orig_directory = "$desired_dir"; //Full image folder
$thumb_directory = "thumb/"; //Thumbnail folder
/* Opening the thumbnail directory and looping through all the thumbs: */
$dir_handle = #opendir($orig_directory); //Open Full image dirrectory
if ($dir_handle > 1){ //Check to make sure the folder opened
$allowed_types=array('jpg','jpeg','gif','png');
$file_type=array();
$ext='';
$title='';
$i=0;
while ($file_name = #readdir($dir_handle)) {
/* Skipping the system files: */
if($file_name=='.' || $file_name == '..') continue;
$file_type = explode('.',$file_name); //This gets the file name of the images
$ext = strtolower(array_pop($file_type));
/* Using the file name (withouth the extension) as a image title: */
$title = implode('.',$file_type);
$title = htmlspecialchars($title);
/* If the file extension is allowed: */
if(in_array($ext,$allowed_types)) {
/* If you would like to inpute images into a database, do your mysql query here */
/* The code past here is the code at the start of the tutorial */
/* Outputting each image: */
$nw = 100;
$nh = 100;
$source = "$desired_dir{$file_name}";
$stype = explode(".", $source);
$stype = $stype[count($stype)-1];
$dest = "thumb/{$file_name}";
$size = getimagesize($source);
$w = $size[0];
$h = $size[1];
switch($stype) {
case 'gif':
$simg = imagecreatefromgif($source);
break;
case 'jpg':
$simg = imagecreatefromjpeg($source);
break;
case 'png':
$simg = imagecreatefrompng($source);
break;
}
$dimg = imagecreatetruecolor($nw, $nh);
$wm = $w/$nw;
$hm = $h/$nw;
$h_height = $nh/2;
$w_height = $nw/2;
if($w> $h) {
$adjusted_width = $w / $hm;
$half_width = $adjusted_width / 2;
$int_width = $w / $hm;
imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
} else {
imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
}
imagejpeg($dimg,$dest,100);
}
}
/* Closing the directory */
#closedir($dir_handle);
}
?>
i get only black image when i run code i don't know what happens i get ERROR in the above the thumb is black

use the following code
<html>
<body>
<pre><?
print_r($_FILES); //SHOW THE ARRAY
foreach ($_FILES as $file) {
if (!$file['error']) {
//PROCESS THE FILE HERE
echo $file['name'];
}
}
?></pre>
<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var fd = new FormData();
$(document).ready(function() {
//submit dragdropped by ajax
$("#dropsubmit").on("click", function(e) {
$.ajax({
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
//FILES POSTED OK! REDIRECT
console.log(data);
}
});
})
var dropzone = $("#dropzone");
dropzone.on('dragenter', function (e) {
$(this).css('background', 'lightgreen');
});
//dropped files, store as formdata
dropzone.on('dragover', stopPropagate);
dropzone.on('drop', function (e) {
stopPropagate(e)
$(this).css('background', 'white');
var files = e.originalEvent.dataTransfer.files;
for (var i = 0; i < files.length; i++) {
preview(files[i])
fd.append('file' + (i + 1), files[i]);
if (i >= 5) continue
}
});
function stopPropagate(e) {
e.stopPropagation();
e.preventDefault();
}
if (window.File && window.FileList && window.FileReader) {
$("input[type=file]").on("change", function(e) {
preview(e.target.files[0])
});
} else {
alert("Your browser doesn't support to File API")
}
function preview(item) {
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<img></img>", {
class: "imageThumb",
src: file.result,
title: file.name,
}).appendTo("#images");
});
fileReader.readAsDataURL(item);
}
});
</script>
<div id="dropzone" style="width:100px;height:100px;border:2px dashed gray;padding:10px">Drag & Drop Files Here</div>
<input type="button" id="dropsubmit" value="Submit dropped files" />
<hr>
<form method="post" enctype="multipart/form-data">
<input id="file1" name="file1" type="file"/><br>
<input id="file2" name="file2" type="file"/><br>
<input id="file3" name="file3" type="file"/><br>
<input id="file4" name="file3" type="file"/><br>
<input id="file5" name="file3" type="file"/><br>
<input name="submit" type="submit" value="Upload files" />
</form><div id="images"></div>
</body>
</html>

Related

php creating thumbnail on multiple file upload and saving both thumbnail and image in two different directories

I am trying to upload multiple images to a folder in my website. While the file upload works without a problem, I am trying to integrate creating thumbnail for all the images uploaded in the same function which is not working.
HTML Form:
<form class="navbar-form pull-left" action="fileupload.php" name="fileupload" method="post" enctype="multipart/form-data">
<label for="file" style="cursor: pointer;padding:5px 0 0 0;font-weight:normal" title="Add Images">IMAGES</label>
<input type="file" name="file[]" multiple id="file"><br>
</form>
Javascript:
function _id(e) {return document.getElementById(e)}
_id('file').onchange = function() {
var theFile = this.files;
if(theFile.length === 1) {
var uploader = new XMLHttpRequest();
var file = new FormData();
file.append("file", theFile[0]);
uploader.onreadystatechange = function() {
if(uploader.readyState === 4 && uploader.status === 200) {
show_message('Uploading Image');
console.log(uploader.responseText);
}
}
uploader.open('POST','fileupload.php',true);
uploader.send(file);
} else {
var start = 0,
setter,
buff = true;
setter = setInterval(function() {
if (buff === true) {
show_message('Uploading Images');
buff = false;
var uploader = new XMLHttpRequest();
var file = new FormData();
file.append('file', theFile[start]);
uploader.onreadystatechange = function() {
if(uploader.readyState === 4 && uploader.status === 200) {
console.log(uploader.responseText);
start++;
buff = true;
}
}
uploader.open('POST','fileupload.php',true);
uploader.send(file);
}
if(start >= theFile.length) {
clearInterval(setter);
}
}, 200)
}
}
fileupload.php
<?php
session_start();
$database = $_SESSION['folder'];
$match = $_SESSION['matchLst'];
$tardir = "/var/www/html/projects/" . $database . "/" . $match . "/";
$thumb = $match . "_thumb/";
$thumbdir = $tardir . $thumb;
function createThumbnail($filename) {
if($filename) {
$im = imagecreatefromjpeg($tardir . $filename);
}
$x = imagesx($im);
$y = imagesy($im);
$nx = 100;
$ny = 100;
$nm = imagecreatetruecolor($nx, $ny);
imagecopyresized($nm, $im, 0, 0, 0, 0, $nx, $ny, $x, $y);
if(!file_exists($thumbdir)) {
if(mkdir($thumbdir)) {
imagejpeg($nm, $thumbdir . $filename);
} else {
die("Thumbnail directory could not be created");
}
} else {
imagejpeg($nm, $thumbdir . $filename);
}
}
if(!isset($_FILES['file'])){die();}
if(isset($_FILES['file'])) {
if($_FILES['file']['name']) {
$filename = $_FILES['file']['name'];
$source = $_FILES['file']['tmp_name'];
$target = $tardir . $filename;
move_uploaded_file($source, $target);
createThumbnail($filename);
echo "Images uploaded";
}
}
?>
I am facing 2-3 problems:
In the fileupload.php file if I comment out the createThumbnail($filename) then I am able to upload multiple files without a problem. When I include createThumbnail function, neither file upload nor thumbnail creation happens. I have tried various examples given here and git - however, not able to create thumbnail nor save it on to a folder.
$tardir is not set here :
function createThumbnail($filename) {
if($filename) {
$im = imagecreatefromjpeg($tardir . $filename);
}
You should replace your function call :
createThumbnail($filename);
By :
createThumbnail($tardir . $filename);
And don't use $tardir in your function.
Be careful when you set an absolute path :
$tardir = "/var/www/html/projects/" . $database . "/" . $match . "/";
Your script will be broken if the path changes. Instead you can use magic-constants like DIR and/or realpath()

PHP $_FILES same image name

I am trying to upload multiple images to php server, But for some reason it is using first image name for all the uploaded images, saving to same image name. I want it to save to their filename in the source folder. Like Banner1.jpg,Banner2.jpg and Banner3.jpg should be saved. But it is saving first image thrice.
$filesCount = count($_FILES['photos']['name']);
$success = 0;
for($i = 0; $i < $filesCount; $i++)
{
$uploadedfile = $_FILES['photos']['tmp_name'][$i];
if($uploadedfile)
{
$filename = stripcslashes($_FILES['photos']['name'][$i]);
$extension = $this->getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
$change='<div class="msgdiv">Unknown Image extension </div>';
}
else
{
$size = filesize($_FILES['photos']['tmp_name'][$i]);
}
if($size > MAX_SIZE*1024)
{
$change='<div class="msgdiv">You have exceeded the size limit!</div> ';
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['photos']['tmp_name'][$i];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['photos']['tmp_name'][$i];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=1024;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=300;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
$filenameee = "server/php/rental/". $_FILES['photos']['name'][$i];
$filenameee1 = "server/php/rental/small/". $_FILES['photos']['name'][$i];
imagejpeg($tmp,$filenameee,100);
imagejpeg($tmp1,$filenameee1,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
if(mysql_query("INSERT INTO fc_rental_photos(product_image,product_id) VALUES('$filename','$prd_id')"))
{
$success++;
}
}
Here is the input field i am using to upload images.
<form id="imageform" method="post" enctype="multipart/form-data" action="/path-to-controller-method/">
<input type="file" name="photos[]" id="photoimg" multiple onchange="imageval();">
</form>
IMageVal
function imageval(){ /*Image size validation*/
var fi = document.getElementById('photoimg');
if (fi.files.length > 0) { // FIRST CHECK IF ANY FILE IS SELECTED.
for (var i = 0; i <= fi.files.length - 1; i++) {
var fileName, fileExtension, fileSize, fileType, dateModified;
fileName = fi.files.item(i).name;
fileExtension = fileName.replace(/^.*\./, '');
if (fileExtension == 'png' || fileExtension == 'jpg' || fileExtension == 'jpeg') {
var reader = new FileReader();
//Read the contents of Image File.
reader.readAsDataURL(fi.files.item(i));
reader.onload = function (e) {
//Initiate the JavaScript Image object.
var image = new Image();
//Set the Base64 string return from FileReader as source.
image.src = e.target.result;
//Validate the File Height and Width.
image.onload = function () {
var height = this.height;
var width = this.width;
if (width < 1450 || height < 500) {
alert("Image Height and Width should be Above 1450 * 500 px.");
return false;
}
<?php if($aws == 'Yes') echo "uploadImage_aws();";else echo "uploadImage();";?>
};
}
}
else
{
alert("Photo only allows file types of PNG, JPG, JPEG. ");
}
}
}
}
UploadImage
function uploadImage()
{
$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
$("#imageloadstatus").show();
$("#imageloadbutton").hide();
},
success:function(){
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
},
error:function(){
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
}
}).submit();
}
You have to check if the data already exists, and if not to rename it.
if(file_exists($new_path)) {
$id = 1;
do {
$new_path = $upload_folder.$filename.'_'.$id.'.'.$extension;
$id++;
} while(file_exists($new_path));
}
For example
$new_path = $upload_folder.$filename.'.'.$extension;

imagecopyresampled() my image turns black after resizing it- CakePhp3

This when I send ajax request to my controller to crop and resize it, instead it resize it but my image turns black. I even tried adding header so that my browser can understands that it is a valid image file format. Where I am missing?
**My ajax call to controller**
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#change-pic').on('click', function(e){
jQuery('#changePic').show();
jQuery('#change-pic').hide();
});
jQuery('#photoimg').on('change', function()
{
jQuery("#preview-avatar-profile").html('');
jQuery("#preview-avatar-profile").html('Uploading....');
jQuery("#cropimage").ajaxForm(
{
target: '#preview-avatar-profile',
success: function() {
jQuery('img#photo').imgAreaSelect({
aspectRatio: '1:1',
onSelectEnd: getSizes,
});
jQuery('#image_name').val(jQuery('#photo').attr('file-name'));
}
}).submit();
});
jQuery('#btn-crop').on('click', function(e){
e.preventDefault();
params = {
//targetUrl: 'profile.php?action=save',
targetUrl: 'http://172.16.0.60/cakephp/users/croppedimage',
//action: 'save',
x_axis: jQuery('#hdn-x1-axis').val(),
y_axis : jQuery('#hdn-y1-axis').val(),
x2_axis: jQuery('#hdn-x2-axis').val(),
y2_axis : jQuery('#hdn-y2-axis').val(),
thumb_width : jQuery('#hdn-thumb-width').val(),
thumb_height:jQuery('#hdn-thumb-height').val()
};
saveCropImage(params);
});
function getSizes(img, obj)
{
var x_axis = obj.x1;
var x2_axis = obj.x2;
var y_axis = obj.y1;
var y2_axis = obj.y2;
var thumb_width = obj.width;
var thumb_height = obj.height;
if(thumb_width > 0)
{
jQuery('#hdn-x1-axis').val(x_axis);
jQuery('#hdn-y1-axis').val(y_axis);
jQuery('#hdn-x2-axis').val(x2_axis);
jQuery('#hdn-y2-axis').val(y2_axis);
jQuery('#hdn-thumb-width').val(thumb_width);
jQuery('#hdn-thumb-height').val(thumb_height);
}
else
alert("Please select portion..!");
}
function saveCropImage(params) {
jQuery.ajax({
url: params['targetUrl'],
cache: false,
dataType: "html",
data: {
action: params['action'],
id: jQuery('#hdn-profile-id').val(),
t: 'ajax',
w1:params['thumb_width'],
x1:params['x_axis'],
h1:params['thumb_height'],
y1:params['y_axis'],
x2:params['x2_axis'],
y2:params['y2_axis'],
image_name :jQuery('#image_name').val()
},
type: 'Post',
// async:false,
success: function (response) {
jQuery('#changePic').hide();
jQuery('#change-pic').show();
jQuery(".imgareaselect-border1,.imgareaselect-border2,.imgareaselect-border3,.imgareaselect-border4,.imgareaselect-border2,.imgareaselect-outer").css('display', 'none');
jQuery("#avatar-edit-img").attr('src', response);
jQuery("#preview-avatar-profile").html('');
jQuery("#photoimg").val('');
},
error: function (xhr, ajaxOptions, thrownError) {
alert('status Code:' + xhr.status + 'Error Message :' + thrownError);
}
});
}
});
</script>
This is one first when I upload the image and preview it.
public function wall()
{
$post = isset($_POST) ? $_POST: array();
$max_width = "500";
$userId = isset($post['hdn-profile-id']) ? intval($post['hdn-profile-id']) : 0;
// $path = 'http://172.16.0.60/cakephp/webroot/img/tmp';
$path = WWW_ROOT.'img/tmp/' ;
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024)) // Image size max 1 MB
{
$actual_image_name = 'avatar' .'_'.$userId .'.'.$ext;
$filePath = $path .'/'.$actual_image_name;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $filePath))
{
// /$this->setPassword($this->request->data['password']);
$width = $this->getWidth($filePath);
$height = $this->getHeight($filePath);
//Scale the image if it is greater than the width set above
if ($width > $max_width)
{
$scale = $max_width/$width;
$uploaded = $this->resizeImage($filePath,$width,$height,$scale);
}
else
{
$scale = 1;
$uploaded = $this->resizeImage($filePath,$width,$height,$scale);
}
/*
echo "<img id='photo' file-name='".$actual_image_name."' class='' src='".'file://'.$filePath.'?'.time()."' class='preview'/>";
*/
$mypath = '/cakephp/img/tmp/'.$actual_image_name;
echo "<img id='photo' file-name='".$actual_image_name."' class='' src='".$mypath."' class='preview'/>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
My Controller code where I use the function imagecopyresampled() but idk where I am going wrong.?
Any solution
public function croppedimage()
{
header('Content-Type: image/png');
$post = isset($_POST) ? $_POST: array();
$userId = isset($post['id']) ? intval($post['id']) : 0;
//$path ='\images\uploads\tmp';
$path = WWW_ROOT.'img/tmp/uploads/' ;
$t_width = 300; // Maximum thumbnail width
$t_height = 300; // Maximum thumbnail height
if(isset($_POST['t']) and $_POST['t'] == "ajax")
{
extract($_POST);
//$img = get_user_meta($userId, 'user_avatar', true);
//$filePath = $path .'/'.$actual_image_name;
$imagePath = $path.$_POST['image_name'];
$ratio = ($t_width/$w1);
$nw = ceil($w1 * $ratio);
$nh = ceil($h1 * $ratio);
$nimg = imagecreatetruecolor($nw,$nh);
$im_src = imagecreatefromjpeg($imagePath);
imagecopyresampled($nimg,$im_src,0,0,$x1,$y1,$nw,$nh,$w1,$h1);
imagejpeg($nimg,$imagePath,90);
}
echo $imagePath.'?'.time();;
exit(0);
die();
}

upload multiple images with jquery ajax and process them with php

I have never done something like this before and I am asking how to do this. I can find how to do this with plain html multiform part etc. But now how to do this with ajax?
Pseudo code:
html:
<input type="text" class="imgform" name="imagename" value="name" />
<input type="file" class="imgform_image" name="image" value="C:\Users\william\Pictures\image.png" />
<input type="button" id="btn" form="imgform" />
JQUERY:
$('body').on('click', '#btn', function(){
var form = $(this).attr("form");
var string = $('.' + form).serialize();
var image = $('.imgform_image').value("form");
image = converttobase64(image);
$.post('action.php?action=uploadimg', string + {'image':image}, function (data){
datalader(data);
});
});
No clue on how to do this. Also is there a way to do this for multiple img files and chek if the the file actually is a image and of course use the filename as the image name instead of using a input textfield.
Any tip, link or code example would be useful thank you in advance!
Note: I totally reviewed my answer and made it better!
HTML
First we make a traditional form without a confirm button. Instead we make a button.
<form enctype="multipart/form-data" id="myform">
<input type="text" name="some_usual_form_data" />
<br>
<input type="file" accept="image/*" multiple name="img[]" id="image" /> <sub>note that you have to use [] behind the name or php wil only see one image</sub>
<br>
<input type="button" value="Upload images" class="upload" />
</form>
<progress value="0" max="100"></progress>
<hr>
<div id="content_here_please"></div>
Javascript/jquery upload side
than here is the Javascript.. o yes and Jquery to upload the images and the other form data:
$(document).ready(function () {
$('body').on('click', '.upload', function(){
// Get the form data. This serializes the entire form. pritty easy huh!
var form = new FormData($('#myform')[0]);
// Make the ajax call
$.ajax({
url: 'action.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progress, false);
}
return myXhr;
},
//add beforesend handler to validate or something
//beforeSend: functionname,
success: function (res) {
$('#content_here_please').html(res);
},
//add error handler for when a error occurs if you want!
//error: errorfunction,
data: form,
// this is the important stuf you need to overide the usual post behavior
cache: false,
contentType: false,
processData: false
});
});
});
// Yes outside of the .ready space becouse this is a function not an event listner!
function progress(e){
if(e.lengthComputable){
//this makes a nice fancy progress bar
$('progress').attr({value:e.loaded,max:e.total});
}
}
PHP processing side
And for those who need the php side to do something with those images here is the php code to loop trough:
<?php
$succeed = 0;
$error = 0;
$thegoodstuf = '';
foreach($_FILES["img"]["error"] as $key => $value) {
if ($value == UPLOAD_ERR_OK){
$succeed++;
// get the image original name
$name = $_FILES["img"]["name"][$key];
// get some specs of the images
$arr_image_details = getimagesize($_FILES["img"]["tmp_name"][$key]);
$width = $arr_image_details[0];
$height = $arr_image_details[1];
$mime = $arr_image_details['mime'];
// Replace the images to a new nice location. Note the use of copy() instead of move_uploaded_file(). I did this becouse the copy function will replace with the good file rights and move_uploaded_file will not shame on you move_uploaded_file.
copy($_FILES['img']['tmp_name'][$key], './upload/'.$name);
// make some nice html to send back
$thegoodstuf .= "
<br>
<hr>
<br>
<h2>Image $succeed - $name</h2>
<br>
specs,
<br>
width: $width <br>
height: $height <br>
mime type: $mime <br>
<br>
<br>
<img src='./upload/$name' title='$name' />
";
}
else{
$error++;
}
}
echo 'Good lord vader '.$succeed.' images where uploaded with success!<br>';
if($error){
echo 'shameful display! '.$error.' images where not properly uploaded!<br>';
}
echo 'O jeah there was a field containing some usual form data: '. $_REQUEST['some_usual_form_data'];
echo $thegoodstuf;
?>
live demo at my dev web server which is not always online!
If you want to compress and resize
You need this class:
class SimpleImage{
var $image;
var $image_type;
function load($filename){
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if($this->image_type == IMAGETYPE_JPEG)
{
$this->image = imagecreatefromjpeg($filename);
}
elseif($this->image_type == IMAGETYPE_GIF)
{
$this->image = imagecreatefromgif($filename);
}
elseif($this->image_type == IMAGETYPE_PNG)
{
$this->image = imagecreatefrompng($filename);
}
}
function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=0777){
if($image_type == IMAGETYPE_JPEG)
{
$gelukt = imagejpeg($this->image,$filename,$compression);
}
elseif($image_type == IMAGETYPE_GIF)
{
$gelukt = imagegif($this->image,$filename);
}
elseif($image_type == IMAGETYPE_PNG)
{
$gelukt = imagepng($this->image,$filename);
}
if($permissions != false)
{
chmod($filename,$permissions);
}
return $gelukt;
}
function output($image_type=IMAGETYPE_JPEG) {
if($image_type == IMAGETYPE_JPEG)
{
imagejpeg($this->image);
}
elseif($image_type == IMAGETYPE_GIF)
{
imagegif($this->image);
}
elseif($image_type == IMAGETYPE_PNG)
{
imagepng($this->image);
}
}
function getWidth(){
return imagesx($this->image);
}
function getHeight(){
return imagesy($this->image);
}
function maxSize($width = 1920, $height = 1080){
if(($this->getHeight() > $height) && ($this->getWidth() > $width)){
$ratio = $height / $this->getHeight();
$newwidth = $this->getWidth() * $ratio;
if($newwidth > $width){
$ratio = $width / $newwidth;
$height = $height * $ratio;
$newwidth = $width;
}
$this->resize($newwidth,$height);
return true;
}
elseif($this->getHeight() > $height){
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
return true;
}
elseif($this->getWidth() > $width){
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
return true;
}
return false;
}
function resizeToHeight($height){
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
}
function resizeToWidth($width){
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
}
function scale($scale){
$width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100;
$this->resize($width,$height);
}
function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
if( $this->image_type == IMAGETYPE_GIF || $this->image_type == IMAGETYPE_PNG )
{
$current_transparent = imagecolortransparent($this->image);
if($current_transparent != -1) {
$transparent_color = imagecolorsforindex($this->image, $current_transparent);
$current_transparent = imagecolorallocate($new_image, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
imagefill($new_image, 0, 0, $current_transparent);
imagecolortransparent($new_image, $current_transparent);
}
elseif($this->image_type == IMAGETYPE_PNG)
{
imagealphablending($new_image, false);
$color = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
imagefill($new_image, 0, 0, $color);
imagesavealpha($new_image, true);
}
}
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
}
you can use it like this:
$succeed = 0;
$error = 0;
$thegoodstuf = '';
foreach($_FILES["img"]["error"] as $key => $value) {
if ($value == UPLOAD_ERR_OK){
$succeed++;
$name = $_FILES["img"]["name"][$key];
$image = new SimpleImage();
$image->load($_FILES['img']['tmp_name'][$key]);
$chek = $image->maxSize();
if($chek){
$move = $image->save('./upload/'.$name);
$message= 'Afbeelding verkleind naar beter formaat!<br>';
}
else{
$move = copy($_FILES['img']['tmp_name'][$key], './upload/'.$name);
#$move = move_uploaded_file($_FILES['img']['tmp_name'][$key], './upload/'.$name);
$message= '';
}
if($move){
$arr_image_details = getimagesize('./upload/'.$name);
$width = $arr_image_details[0];
$height = $arr_image_details[1];
$mime = $arr_image_details['mime'];
$thegoodstuf .= "
<br>
<hr>
<br>
<h2>Image $succeed - $name</h2>
<br>
specs,
<br>
$message
width: $width <br>
height: $height <br>
mime type: $mime <br>
<br>
<br>
<img src='./upload/$name' title='$name' />
";
}
else{
$error++;
}
}
else{
$error++;
}
}
echo 'Good lord vader '.$succeed.' images where uploaded with success!<br>';
if($error){
echo 'shameful display! '.$error.' images where not properly uploaded!<br>';
}
echo 'O jeah there was a field containing some usual form data: '. $_REQUEST['some_usual_form_data'];
echo $thegoodstuf;
I've got an updated version with resizer:
$succeed = 0;
$error = 0;
$thegoodstuf = '';
foreach($_FILES["file"]["error"] as $key => $value) {
if ($value == UPLOAD_ERR_OK){
$succeed++;
// get the image original name
$name = $_FILES["file"]["name"][$key];
$ext = pathinfo($name, PATHINFO_EXTENSION);
$img_name=md5($name.rand(00000,99999)).".".$ext;//rename filename
if($ext=="jpg" || $ext=="jpeg" ){
$uploadedfile = $_FILES['file']['tmp_name'][$key];
$src = imagecreatefromjpeg($uploadedfile);
}else if($ext=="png"){
$uploadedfile = $_FILES['file']['tmp_name'][$key];
$src = imagecreatefrompng($uploadedfile);
}else {
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$new_width=800;
$new_height=($height/$width)*$new_width;
$tmp=imagecreatetruecolor($new_width,$new_height);
$new_width1=140;
$new_height1=($height/$width)*$new_width1;
$tmp1=imagecreatetruecolor($new_width1,$new_height1);
imagecopyresampled($tmp,$src,0,0,0,0,$new_width,$new_height,
$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$new_width1,$new_height1,
$width,$height);
$filename = "../../photos/".$img_name;
$filename1 = "../../photos/tn/".$img_name;
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
//insert to DB here
// make some nice html to send back
$thegoodstuf .= "
<br>
<hr>
<div class='thumbnail'>
<b class='alert alert-info'>Image $succeed - $img_name</b>
<br>
width: $new_width <br>
height: $new_height <br>
mime type: $mime <br>
<br>
<br>
<img src='../../photos/$img_name' title='$img_name' class='thumbnail'/>
</div>
";
}
else{
$error++;
}
}
echo $thegoodstuf;
echo $succeed.' images where uploaded with success!<br>';
if($error){
echo $error.' images where not properly uploaded!<br>';
}

jQuery + PHP Multi-File Drag-Drop Upload Can't Create Thumbnails - WEIRD

Been working on this annoying son of a gun for 3 days. Hoping someone will be able to offer some assistance. Basically I'm using http://tutorialzine.com/2011/09/html5-file-upload-jquery-php/ to allow multiple file uploads along side with a regular file upload input. The first part of this code is the copying of the original image that was uploaded. That works fine for both. The second part is for thumbnails and it won't work when using the drag-drop script, however it works perfectly using the standard upload. I'm assuming my problem isn't with this code, but I'm including it just to show you. I'll also include almost all the other code in case you find it pertinent and helpful in diagnosing.
// copying original image to new location with new name
$prev = file_get_contents($pic['tmp_name']);
$new = fopen($file, "w");
fwrite($new, $prev);
fclose($new);
//create image for thumbnail
switch(strtolower($pic['type']))
{
case 'image/jpeg':
$image = imagecreatefromjpeg($pic['tmp_name']);
break;
case 'image/png':
$image = imagecreatefrompng($pic['tmp_name']);
imagealphablending($image, true); // setting alpha blending on
imagesavealpha($image, true);
break;
case 'image/gif':
$image = imagecreatefromgif($pic['tmp_name']);
break;
default:
exit('Unsupported type: '.$pic['type']);
}
// Target dimensions
$max_width = 150;
$max_height = 150;
// 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);
// Catch the imagedata
ob_start();
//create image for thumbnail
switch(strtolower($pic['type']))
{
case 'image/jpeg':
imagejpeg($new, $_SERVER['DOCUMENT_ROOT']."/".$thumbnail, 90);
break;
case 'image/png';
imagepng($new, $_SERVER['DOCUMENT_ROOT']."/".$thumbnail, 9);
break;
case 'image/gif':
imagegif($new, $_SERVER['DOCUMENT_ROOT']."/".$thumbnail, 9);
break;
default:
exit('Unsupported type: '.$pic['type']);
}
chmod($_SERVER['DOCUMENT_ROOT']."/".$thumbnail,0755);
$data = ob_get_clean();
// Destroy resources
imagedestroy($image);
imagedestroy($new);
The HTML
<h1>Upload Image(s)</h1>
<form action='ajax/post_file.php' method='post' enctype="multipart/form-data">
<input type='file' name='file'><input type='hidden' name='drag_drop' value='yes'><input type='submit' value='go'>
</form>
<!-- Our CSS stylesheet file -->
<link rel="stylesheet" href="ajax/drag_drop_uploads/css/styles.css" />
<div id="dropbox" style='height: 400px; overflow: auto;'>
<span class="message">Drop images here to upload. <br /><i>(they will be automatically uploaded to your account)</i></span>
</div>
The JQuery plugin that handles the drag-drop upload
(function(jQuery){
jQuery.event.props.push("dataTransfer");
var opts = {},
default_opts = {
url: '',
refresh: 1000,
paramname: 'userfile',
maxfiles: 25,
maxfilesize: 5, // MBs
data: {},
drop: empty,
dragEnter: empty,
dragOver: empty,
dragLeave: empty,
docEnter: empty,
docOver: empty,
docLeave: empty,
beforeEach: empty,
afterAll: empty,
rename: empty,
error: function(err, file, i){alert(err);},
uploadStarted: empty,
uploadFinished: empty,
progressUpdated: empty,
speedUpdated: empty
},
errors = ["BrowserNotSupported", "TooManyFiles", "FileTooLarge"],
doc_leave_timer,
stop_loop = false,
files_count = 0,
files;
jQuery.fn.filedrop = function(options) {
opts = jQuery.extend( {}, default_opts, options );
this.bind('drop', drop).bind('dragenter', dragEnter).bind('dragover', dragOver).bind('dragleave', dragLeave);
jQuery(document).bind('drop', docDrop).bind('dragenter', docEnter).bind('dragover', docOver).bind('dragleave', docLeave);
};
function drop(e) {
opts.drop(e);
files = e.dataTransfer.files;
if (files === null || files === undefined) {
opts.error(errors[0]);
return false;
}
files_count = files.length;
upload();
e.preventDefault();
return false;
}
function getBuilder(filename, filedata, boundary) {
var dashdash = '--',
crlf = '\r\n',
builder = '';
jQuery.each(opts.data, function(i, val) {
if (typeof val === 'function') val = val();
builder += dashdash;
builder += boundary;
builder += crlf;
builder += 'Content-Disposition: form-data; name="'+i+'"';
builder += crlf;
builder += crlf;
builder += val;
builder += crlf;
});
builder += dashdash;
builder += boundary;
builder += crlf;
builder += 'Content-Disposition: form-data; name="'+opts.paramname+'"';
builder += '; filename="' + filename + '"';
builder += crlf;
builder += 'Content-Type: application/octet-stream';
builder += crlf;
builder += crlf;
builder += filedata;
builder += crlf;
builder += dashdash;
builder += boundary;
builder += dashdash;
builder += crlf;
return builder;
}
function progress(e) {
if (e.lengthComputable) {
var percentage = Math.round((e.loaded * 100) / e.total);
if (this.currentProgress != percentage) {
this.currentProgress = percentage;
opts.progressUpdated(this.index, this.file, this.currentProgress);
var elapsed = new Date().getTime();
var diffTime = elapsed - this.currentStart;
if (diffTime >= opts.refresh) {
var diffData = e.loaded - this.startData;
var speed = diffData / diffTime; // KB per second
opts.speedUpdated(this.index, this.file, speed);
this.startData = e.loaded;
this.currentStart = elapsed;
}
}
}
}
function upload() {
stop_loop = false;
if (!files) {
opts.error(errors[0]);
return false;
}
var filesDone = 0,
filesRejected = 0;
if (files_count > opts.maxfiles) {
opts.error(errors[1]);
return false;
}
for (var i=0; i<files_count; i++) {
if (stop_loop) return false;
try {
if (beforeEach(files[i]) != false) {
if (i === files_count) return;
var reader = new FileReader(),
max_file_size = 1048576 * opts.maxfilesize;
reader.index = i;
if (files[i].size > max_file_size) {
opts.error(errors[2], files[i], i);
filesRejected++;
continue;
}
reader.onloadend = send;
reader.readAsBinaryString(files[i]);
} else {
filesRejected++;
}
} catch(err) {
opts.error(errors[0]);
return false;
}
}
function send(e) {
// Sometimes the index is not attached to the
// event object. Find it by size. Hack for sure.
if (e.target.index == undefined) {
e.target.index = getIndexBySize(e.total);
}
var xhr = new XMLHttpRequest(),
upload = xhr.upload,
file = files[e.target.index],
index = e.target.index,
start_time = new Date().getTime(),
boundary = '------multipartformboundary' + (new Date).getTime(),
builder;
newName = rename(file.name);
if (typeof newName === "string") {
builder = getBuilder(newName, e.target.result, boundary);
} else {
builder = getBuilder(file.name, e.target.result, boundary);
}
upload.index = index;
upload.file = file;
upload.downloadStartTime = start_time;
upload.currentStart = start_time;
upload.currentProgress = 0;
upload.startData = 0;
upload.addEventListener("progress", progress, false);
xhr.open("POST", opts.url, true);
xhr.setRequestHeader('content-type', 'multipart/form-data; boundary='
+ boundary);
xhr.sendAsBinary(builder);
opts.uploadStarted(index, file, files_count);
xhr.onload = function() {
if (xhr.responseText) {
var now = new Date().getTime(),
timeDiff = now - start_time,
result = opts.uploadFinished(index, file, jQuery.parseJSON(xhr.responseText), timeDiff);
filesDone++;
if (filesDone == files_count - filesRejected) {
afterAll();
}
if (result === false) stop_loop = true;
}
};
}
}
function getIndexBySize(size) {
for (var i=0; i < files_count; i++) {
if (files[i].size == size) {
return i;
}
}
return undefined;
}
function rename(name) {
return opts.rename(name);
}
function beforeEach(file) {
return opts.beforeEach(file);
}
function afterAll() {
return opts.afterAll();
}
function dragEnter(e) {
clearTimeout(doc_leave_timer);
e.preventDefault();
opts.dragEnter(e);
}
function dragOver(e) {
clearTimeout(doc_leave_timer);
e.preventDefault();
opts.docOver(e);
opts.dragOver(e);
}
function dragLeave(e) {
clearTimeout(doc_leave_timer);
opts.dragLeave(e);
e.stopPropagation();
}
function docDrop(e) {
e.preventDefault();
opts.docLeave(e);
return false;
}
function docEnter(e) {
clearTimeout(doc_leave_timer);
e.preventDefault();
opts.docEnter(e);
return false;
}
function docOver(e) {
clearTimeout(doc_leave_timer);
e.preventDefault();
opts.docOver(e);
return false;
}
function docLeave(e) {
doc_leave_timer = setTimeout(function(){
opts.docLeave(e);
}, 200);
}
function empty(){}
try {
if (XMLHttpRequest.prototype.sendAsBinary) return;
XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
function byteValue(x) {
return x.charCodeAt(0) & 0xff;
}
var ords = Array.prototype.map.call(datastr, byteValue);
var ui8a = new Uint8Array(ords);
this.send(ui8a.buffer);
}
} catch(e) {}
})(jQuery);
The JQuery that is called to and from the plugin
jQuery(function(){
var dropbox = jQuery('#dropbox'),
message = jQuery('.message', dropbox);
dropbox.filedrop({
// The name of the jQuery_FILES entry:
paramname:'file',
maxfiles: 25,
maxfilesize: 5,
url: 'ajax/post_file.php',
uploadFinished:function(i,file,response){
jQuery.data(file).addClass('done');
// response is the JSON object that post_file.php returns
},
error: function(err, file) {
switch(err) {
case 'BrowserNotSupported':
showMessage('Your browser does not support HTML5 file uploads!');
break;
case 'TooManyFiles':
alert('Too many files! Please select 5 at most! (configurable)');
break;
case 'FileTooLarge':
alert(file.name+' is too large! Please upload files up to 2mb (configurable).');
break;
default:
break;
}
},
// Called before each upload is started
beforeEach: function(file){
if(!file.type.match(/^image\//)){
alert('Only images are allowed!');
// Returning false will cause the
// file to be rejected
return false;
}
},
uploadStarted:function(i, file, len){
createImage(file);
},
progressUpdated: function(i, file, progress) {
jQuery.data(file).find('.progress').width(progress);
}
});
var template = '<div class="preview">'+
'<span class="imageHolder">'+
'<img />'+
'<span class="uploaded"></span>'+
'</span>'+
'<div class="progressHolder">'+
'<div class="progress"></div>'+
'</div>'+
'</div>';
function createImage(file){
var preview = jQuery(template),
image = jQuery('img', preview);
var reader = new FileReader();
image.width = 100;
image.height = 100;
reader.onload = function(e){
// e.target.result holds the DataURL which
// can be used as a source of the image:
image.attr('src',e.target.result);
};
// Reading the file as a DataURL. When finished,
// this will trigger the onload function above:
reader.readAsDataURL(file);
message.hide();
preview.appendTo(dropbox);
// Associating a preview container
// with the file, using jQuery's jQuery.data():
jQuery.data(file,preview);
}
function showMessage(msg){
message.html(msg);
}
});
The sample PHP they gave me
$demo_mode = false;
$upload_dir = 'ajax/uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');
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!');
}
if($demo_mode){
// File uploads are ignored. We only log them.
$line = implode(' ', array( date('r'), $_SERVER['REMOTE_ADDR'],
$pic['size'], $pic['name']));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Uploads are ignored in demo mode.');
}
// Move the uploaded file from the temporary
// directory to the uploads folder:
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
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);
}
As discussed in the OPs comments;
It seems the file upload example isn't correctly populating the filetype resulting in hitting the switch's default block (an exit)
Incidentally, you may want to swap this to throwing an exception so you'll see something useful in the logs in future

Categories