upload multiple images with jquery ajax and process them with php - 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>';
}

Related

PHP create thumbnail sizes and save in folder [duplicate]

I'm wanting to create a thumbnail from a user uploaded image so the image doesn't look squashed. But also would like a copy of the original image.. So I would like the original image to send the original image to my server and also create a thumb version and send it to my server so I can call each of them for each user that uploads their own image.
My user table has 2 tables
`user_pic` longblob NOT NULL,
`user_pic_small` longblob NOT NULL,
I'm not crash hot with the image side of coding but this is what I have so far.
Imageupload.php
> <form id="myForm" action="include/media.profileimage.upload.php"
> method="POST" enctype="multipart/form-data" target="ifr1">
> <input type = "file" name = "image_data" class = "input_text" style="width:800px;" >
> <input type = "submit" name = "submit" class = "btn_login" value = "Upload">
> </form>
media.profileimage.upload.php
if(isset($_FILES['image_data'])){
if(is_uploaded_file($_FILES['image_data']['tmp_name'])) {
// prepare the image for insertion
$imgData =addslashes (file_get_contents($_FILES['image_data']['tmp_name']));
// get the image info..
$size = getimagesize($_FILES['image_data']['tmp_name']);
// our sql query
$creator_id = $_SESSION['id'];
$sql = "UPDATE users SET user_pic='".$imgData."' WHERE id=$creator_id";
$sql2 = "INSERT INTO userphotos(photo_ownerid,photo_ispublic, photo_name, photo_caption, photo_imagedata) VALUES ($creator_id,1,'Profile Picture','Profile Picture','$imgData')";
// insert the image
if(!mysql_query($sql)) {
echo "Fail. It broke.";
}else{
$c=mysql_query($sql2);
echo "<script> parent.alert('Image Uploaded','',1000);</script>";
}
}
}
Would appreciate any help or guidence. Thankyou
UPDATE:
If you want to take advantage of Imagick (if it is installed on your server). Note: I didn't use Imagick's nature writeFile because I was having issues with it on my server. File put contents works just as well.
<?php
/**
*
* Generate Thumbnail using Imagick class
*
* #param string $img
* #param string $width
* #param string $height
* #param int $quality
* #return boolean on true
* #throws Exception
* #throws ImagickException
*/
function generateThumbnail($img, $width, $height, $quality = 90)
{
if (is_file($img)) {
$imagick = new Imagick(realpath($img));
$imagick->setImageFormat('jpeg');
$imagick->setImageCompression(Imagick::COMPRESSION_JPEG);
$imagick->setImageCompressionQuality($quality);
$imagick->thumbnailImage($width, $height, false, false);
$filename_no_ext = reset(explode('.', $img));
if (file_put_contents($filename_no_ext . '_thumb' . '.jpg', $imagick) === false) {
throw new Exception("Could not put contents.");
}
return true;
}
else {
throw new Exception("No valid image provided with {$img}.");
}
}
// example usage
try {
generateThumbnail('test.jpg', 100, 50, 65);
}
catch (ImagickException $e) {
echo $e->getMessage();
}
catch (Exception $e) {
echo $e->getMessage();
}
?>
I have been using this, just execute the function after you store the original image and use that location to create the thumbnail. Edit it to your liking...
function makeThumbnails($updir, $img, $id)
{
$thumbnail_width = 134;
$thumbnail_height = 189;
$thumb_beforeword = "thumb";
$arr_image_details = getimagesize("$updir" . $id . '_' . "$img"); // pass id to thumb name
$original_width = $arr_image_details[0];
$original_height = $arr_image_details[1];
if ($original_width > $original_height) {
$new_width = $thumbnail_width;
$new_height = intval($original_height * $new_width / $original_width);
} else {
$new_height = $thumbnail_height;
$new_width = intval($original_width * $new_height / $original_height);
}
$dest_x = intval(($thumbnail_width - $new_width) / 2);
$dest_y = intval(($thumbnail_height - $new_height) / 2);
if ($arr_image_details[2] == IMAGETYPE_GIF) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
}
if ($arr_image_details[2] == IMAGETYPE_JPEG) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
}
if ($arr_image_details[2] == IMAGETYPE_PNG) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
}
if ($imgt) {
$old_image = $imgcreatefrom("$updir" . $id . '_' . "$img");
$new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imagecopyresized($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
$imgt($new_image, "$updir" . $id . '_' . "$thumb_beforeword" . "$img");
}
}
The above function creates images with a uniform thumbnail size. If the image doesn't have the same dimensions as the specified thumbnail size (proportionally), it just has blackspace on the top and bottom.
You Can Use The Simplest Method
<?php
function make_thumb($src, $dest, $desired_width) {
/* read the source image */
$source_image = imagecreatefromjpeg($src);
$width = imagesx($source_image);
$height = imagesy($source_image);
/* find the "desired height" of this thumbnail, relative to the desired width */
$desired_height = floor($height * ($desired_width / $width));
/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
/* copy source image at a resized size */
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
/* create the physical thumbnail image to its destination */
imagejpeg($virtual_image, $dest);
}
$src="1494684586337H.jpg";
$dest="new.jpg";
$desired_width="200";
make_thumb($src, $dest, $desired_width);
?>
I'm guessing you have already figured this one out. But I see that you are storing the images as "longblobs" leading me to think you are storing the entire binary content of the pic.
I hope you have realized that it makes much more sense to simply store the file names in your DB and then use that info to grab the pics out of an "upload" folder or similar.
TIP - dont save a file path.. just the file name .. add the path info in your code as needed. That way you have the most freedom down the line. If you need to change folder structure, you can do it in your code rather than changing DB records.
I know this is an old question, but I stumbled upon the same problem and tried to use the function given in Alex's answer.
But the quality in the jpeg result was too low. So I changed the function a little bit to become more usable in my project and changed the "imagecopyresized" to "imagecopyresampled" (according to this recomendation).
If you are having questions about how to use this function, then try taking a look at the well documented version here.
function createThumbnail($filepath, $thumbpath, $thumbnail_width, $thumbnail_height, $background=false) {
list($original_width, $original_height, $original_type) = getimagesize($filepath);
if ($original_width > $original_height) {
$new_width = $thumbnail_width;
$new_height = intval($original_height * $new_width / $original_width);
} else {
$new_height = $thumbnail_height;
$new_width = intval($original_width * $new_height / $original_height);
}
$dest_x = intval(($thumbnail_width - $new_width) / 2);
$dest_y = intval(($thumbnail_height - $new_height) / 2);
if ($original_type === 1) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
} else if ($original_type === 2) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
} else if ($original_type === 3) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
} else {
return false;
}
$old_image = $imgcreatefrom($filepath);
$new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height); // creates new image, but with a black background
// figuring out the color for the background
if(is_array($background) && count($background) === 3) {
list($red, $green, $blue) = $background;
$color = imagecolorallocate($new_image, $red, $green, $blue);
imagefill($new_image, 0, 0, $color);
// apply transparent background only if is a png image
} else if($background === 'transparent' && $original_type === 3) {
imagesavealpha($new_image, TRUE);
$color = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
imagefill($new_image, 0, 0, $color);
}
imagecopyresampled($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
$imgt($new_image, $thumbpath);
return file_exists($thumbpath);
}
just in case you need to create thumb with a max width and a max height ...
function makeThumbnails($updir, $img, $id,$MaxWe=100,$MaxHe=150){
$arr_image_details = getimagesize($img);
$width = $arr_image_details[0];
$height = $arr_image_details[1];
$percent = 100;
if($width > $MaxWe) $percent = floor(($MaxWe * 100) / $width);
if(floor(($height * $percent)/100)>$MaxHe)
$percent = (($MaxHe * 100) / $height);
if($width > $height) {
$newWidth=$MaxWe;
$newHeight=round(($height*$percent)/100);
}else{
$newWidth=round(($width*$percent)/100);
$newHeight=$MaxHe;
}
if ($arr_image_details[2] == 1) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
}
if ($arr_image_details[2] == 2) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
}
if ($arr_image_details[2] == 3) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
}
if ($imgt) {
$old_image = $imgcreatefrom($img);
$new_image = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresized($new_image, $old_image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
$imgt($new_image, $updir."".$id."_t.jpg");
return;
}
}
Hope this code helps for creating Thumbnail for JPG, PNG & GIF formats.
<?php
$file = "D:/server/sites/Sourcefol/high/bucket/kath23.png"; /*Your Original Source Image */
$pathToSave = "D:/server/sites/Sourcefol/high/bucket/New/"; /*Your Destination Folder */
$sourceWidth =60;
$sourceHeight = 60;
$what = getimagesize($file);
$file_name = basename($file);/* Name of the Image File*/
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
/* Adding image name _thumb for thumbnail image */
$file_name = basename($file_name, ".$ext") . '_thumb.' . $ext;
switch(strtolower($what['mime']))
{
case 'image/png':
$img = imagecreatefrompng($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/png');
break;
case 'image/jpeg':
$img = imagecreatefromjpeg($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/jpeg');
break;
case 'image/gif':
$img = imagecreatefromgif($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/gif');
break;
default: die();
}
imagejpeg($new,$pathToSave.$file_name);
imagedestroy($new);
?>
Image Upload with thumbnail generate
upload.php
<?php
function generate_thumb_now($field_name = '',$target_folder ='',$file_name = '', $thumb = FALSE, $thumb_folder = '', $thumb_width = '',$thumb_height = ''){
//folder path setup
$target_path = $target_folder;
$thumb_path = $thumb_folder;
//file name setup
$filename_err = explode(".",$_FILES[$field_name]['name']);
$filename_err_count = count($filename_err);
$file_ext = $filename_err[$filename_err_count-1];
if($file_name != '')
{
$fileName = $file_name.'.'.$file_ext;
}
else
{
$fileName = $_FILES[$field_name]['name'];
}
//upload image path
$upload_image = $target_path.basename($fileName);
//upload image
if(move_uploaded_file($_FILES[$field_name]['tmp_name'],$upload_image))
{
//thumbnail creation
if($thumb == TRUE)
{
$thumbnail = $thumb_path.$fileName;
list($width,$height) = getimagesize($upload_image);
$thumb_create = imagecreatetruecolor($thumb_width,$thumb_height);
switch($file_ext){
case 'jpg':
$source = imagecreatefromjpeg($upload_image);
break;
case 'jpeg':
$source = imagecreatefromjpeg($upload_image);
break;
case 'png':
$source = imagecreatefrompng($upload_image);
break;
case 'gif':
$source = imagecreatefromgif($upload_image);
break;
default:
$source = imagecreatefromjpeg($upload_image);
}
imagecopyresized($thumb_create, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width,$height);
switch($file_ext){
case 'jpg' || 'jpeg':
imagejpeg($thumb_create,$thumbnail,100);
break;
case 'png':
imagepng($thumb_create,$thumbnail,100);
break;
case 'gif':
imagegif($thumb_create,$thumbnail,100);
break;
default:
imagejpeg($thumb_create,$thumbnail,100);
}
}
return $fileName;
}
else
{
return false;
}
}
if(!empty($_FILES['image']['name'])){
$upload_img = generate_thumb_now('image','uploads/','',TRUE,'uploads /thumbs/','400','320');
//full path of the thumbnail image
$thumb_src = 'uploads/thumbs/'.$upload_img;
//set success and error messages
$message = $upload_img?"<span style='color:#008000;'>Image thumbnail created successfully.</span>":"<span style='color:#F00000;'>Some error occurred, please try again.</span>";
}else{
//if form is not submitted, below variable should be blank
$thumb_src = '';
$message = '';
}
?>
<html>
<head>Image upload and generate thumbnail</head>
<body>
<div class="messages"><?php echo $message; ?></div>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="submit" value="Upload"/>
</form>
<?php if($thumb_src != ''){ ?>
<div class="gallery">
<ul>
<li><img src="<?php echo $thumb_src; ?>" alt=""></li>
</ul>
</div>
<?php } ?>
</body>
</html>
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysql_query("INSERT INTO users (uid, profile_image) VALUES ('$session_id' , '$actual_image_name')");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "Fail upload folder with read access.";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
<?php
error_reporting(0);
$change="";
$abc="";
define ("MAX_SIZE","4000");
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$errors=0;
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$image =$_FILES["file"]["name"];
$uploadedfile = $_FILES['file']['tmp_name'];
if ($image)
{
$filename = stripslashes($_FILES['file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
$change='<div class="msgdiv">Unknown Image extension </div> ';
$errors=1;
}
else
{
$size=filesize($_FILES['file']['tmp_name']);
if ($size > MAX_SIZE*1024)
{
$change='<div class="msgdiv">You have exceeded the size limit!</div> ';
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
echo $scr;
list($width,$height)=getimagesize($uploadedfile);
$newwidth=45;
$newheight=45;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=90;
$newheight1=90;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
$tmp2=imagecreatetruecolor($width,$height);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
imagecopyresampled($tmp2,$src,0,0,0,0,$width,$height,$width,$height);
$filename = "images/1-". $_FILES['file']['name']=time();
$filename1 = "images/2-". $_FILES['file']['name']=time();
$filename2 = "images/3-". $_FILES['file']['name']=time();
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
imagejpeg($tmp2,$filename2,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}
}
if(isset($_POST['Submit']) && !$errors)
{
// mysql_query("update {$prefix}users set img='$big',img_small='$small' where user_id='$user'");
$change=' <div class="msgdiv">Image Uploaded Successfully!</div>';
}
?>
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>
<title>picture demo</title>
<link href=".css" media="screen, projection" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery_002.js"></script>
<script type="text/javascript" src="js/displaymsg.js"></script>
<script type="text/javascript" src="js/ajaxdelete.js"></script>
<style type="text/css">
.help
{
font-size:11px; color:#006600;
}
body {
color: #000000;
background-color:#999999 ;
background:#999999 url(<?php echo $user_row['img_src']; ?>) fixed repeat top left;
font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
}
.msgdiv{
width:759px;
padding-top:8px;
padding-bottom:8px;
background-color: #fff;
font-weight:bold;
font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px;
}
#container{width:763px;margin:0 auto;padding:3px 0;text-align:left;position:relative; -moz-border-radius: 6px;-webkit-border-radius: 6px; background-color:#FFFFFF }
</style>
</head><body>
<div align="center" id="err">
<?php echo $change; ?> </div>
<div id="space"></div>
<div id="container" >
<div id="con">
<table width="502" cellpadding="0" cellspacing="0" id="main">
<tbody>
<tr>
<td width="500" height="238" valign="top" id="main_right">
<div id="posts">
<img src="<?php// echo $filename; ?>" /> <img src="<?php// echo $filename1; ?>" />
<form method="post" action="" enctype="multipart/form-data" name="form1">
<table width="500" border="0" align="center" cellpadding="0" cellspacing="0">
<tr><Td style="height:25px"> </Td></tr>
<tr>
<td width="150"><div align="right" class="titles">Picture
: </div></td>
<td width="350" align="left">
<div align="left">
<input size="25" name="file" type="file" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10pt" class="box"/>
</div></td>
</tr>
<tr><Td></Td>
<Td valign="top" height="35px" class="help">Image maximum size <b>4000 </b>kb</span></Td>
</tr>
<tr><Td></Td><Td valign="top" height="35px"><input type="submit" id="mybut" value=" Upload " name="Submit"/></Td></tr>
<tr>
<td width="200"> </td>
<td width="200"><table width="200" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="200" align="center"><div align="left"></div></td>
<td width="100"> </td>
</tr>
</table></td>
</tr>
</table>
</form>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body></html>

how to move an image from folder and resize before saving to another folder?

I am working on a project which multiple pages validation. My main issue is with the upload part of the code. What i am doing is when a user upload his images; i save them in a tempfolder then once form filled complete, i move the images from temp to mainfolder but before i want to resize the images before saving them in mainfolder.
How can i achieve that ?
I have tried myself but could not get it right.here is my code
i got this error : getimagesize(174349.jpg): failed to open stream: No such file or directory
imageuploaded.php
<?php
define('MAX_FILE_SIZE', 952070);
define('UPLOAD_DIR_TEMP', BASE_URI.'html/temp/');
$max = number_format(MAX_FILE_SIZE/1024, 1).'KB';
// create an array of permitted MIME types
$permitted = array('image/gif', 'image/jpeg', 'image/pjpeg','image/png');
if (array_key_exists('upload', $_POST)) {
foreach ($_FILES['image']['name'] as $number => $file) {
// replace any spaces in the filename with underscores
$file = str_replace(' ','_',$file);
$fileNom = pathinfo($_FILES['image']["name"][$number], PATHINFO_FILENAME);
$ext = pathinfo($_FILES['image']["name"][$number],PATHINFO_EXTENSION);
//$soruceimg = $_FILES['image']['tmp_name'];
//echo $file;
// begin by assuming the file is unacceptable
$sizeOK = false;
$typeOK = false;
// check that file is within the permitted size
if ($_FILES['image']['size'][$number] > 0 || $_FILES['image']['size'][$number] <= MAX_FILE_SIZE) {
$sizeOK = true;
}
// check that file is of a permitted MIME type
foreach ($permitted as $type) {
if ($type == $_FILES['image']['type'][$number]) {
$typeOK = true;
break;
}
}
if ($sizeOK && $typeOK) {
switch($_FILES['image']['error'][$number]) {
case 0:
// get the date and time
ini_set('date.timezone', 'Africa/Abidjan');
$now = date('Y-m-d-His');
//$Nfilename = basename(substr($file,0,6).$now).".".$ext ." ";
$successes = move_uploaded_file($_FILES['image']['tmp_name'][$number], UPLOAD_DIR_TEMP.$file);
if ($successes) {
$_SESSION['imgname']= $_FILES['image']['name'];
header('Location: test.php');
//echo $file;
}
else {
$resultfile[] = "Error uploading $file. Please try again.";
}
break;
case 3:
$resultfile[] = "Error uploading $file. Please try again.";
default:
$resultfile[] = "System error uploading $file. Contact webmaster.";
}
}
elseif ($_FILES['image']['error'][$number] == 4) {
$errNofile[] = 1;
}
else {
$resultfile[] = "$file cannot be uploaded. Maximum size: $max.Acceptable file types: gif, jpg, png.";
}
}
}
imageresize.php
$source = BASE_URI.'html/temp/';
define('THUMBS_DIR', BASE_URI.'html/products/thumbs/');
define('MAX_WIDTH', 200);
define('MAX_HEIGHT', 200);
define('UPLOAD_DIR', BASE_URI.'html/products/');
ini_set('date.timezone', 'Africa/Abidjan');
$now = date('Y-m-d-His');
if (isset($_SESSION['imgname']) && is_array($_SESSION['imgname']) ) {
foreach ($_SESSION['imgname'] as $files) {
echo $files;
$img = str_replace(" ", "_", $files);
$ext = pathinfo($img,PATHINFO_EXTENSION);
if (file_exists($source.$img)) {
$ext = pathinfo($img,PATHINFO_EXTENSION);
// strip the extension off the image filename
$imagetypes = array('/\.gif$/', '/\.jpg$/', '/\.jpeg$/', '/\.png$/');
$name = preg_replace($imagetypes, '', basename(substr($img,0,6).$now));
list($width, $height, $type) = getimagesize($img);
if ($width != $height) {
echo "file width and height must be same";
break;
}
elseif ( $width < 300 && $height < 300) {
echo "File must be at least 400 x 400";
break;
}
else{
$ratio = 1;
$ratio = MAX_WIDTH/$width;
}
$Nfilename = $name.'.'.$ext;
$moved = rename($source.$img, UPLOAD_DIR.$Nfilename);
if (!$moved) {
echo "Problem moving file".$img;
}
else{
// create an image resource for the original
switch($type) {
case 1:
$source = # imagecreatefromgif($original);
if (!$source) {
$result = 'Cannot process GIF files. Please use JPEG or PNG.';
}
break;
case 2:
$source = imagecreatefromjpeg($original);
break;
case 3:
$source = imagecreatefrompng($original);
break;
default:
$source = NULL;
$result = 'Cannot identify file type.';
}
// make sure the image resource is OK
if (!$source) {
$result = 'Problem copying original';
}
else {
// calculate the dimensions of the thumbnail
$thumb_width = round($width * $ratio);
$thumb_height = round($height * $ratio);
// create an image resource for the thumbnail
$thumb = imagecreatetruecolor($thumb_width, $thumb_height);
// create the resized copy
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height);
// save the resized copy
switch($type) {
case 1:
if (function_exists('imagegif')) {
$success = imagegif($thumb, THUMBS_DIR.$name.'_thb.gif');
$thumb_name = $name.'_thb.gif';
}
else {
$success = imagejpeg($thumb, THUMBS_DIR.$name.'_thb.jpg', 50);
$thumb_name = $name.'_thb.jpg';
}
break;
case 2:
$success = imagejpeg($thumb, THUMBS_DIR.$name.'_thb.jpg', 100);
$thumb_name = $name.'_thb.jpg';
break;
case 3:
$success = imagepng($thumb, THUMBS_DIR.$name.'_thb.png');
$thumb_name = $name.'_thb.png';
}
if ($success) {
$result = "$thumb_name created";
}
else {
$result = 'Problem creating thumbnail';
}
if ($success) {
echo $thumb_name;
}
// remove the image resources from memory
imagedestroy($source);
imagedestroy($thumb);
}
}
}
else{
echo "No file exist";
}
}
}
Convert the image to bitmap first and use bitmap compression with defined ratio to compress the size.
you can compress the image by declaring specific height and width also.
I had this code before, very easy to use, it works for me
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=null) {
if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image,$filename,$compression); }
elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image,$filename); }
elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image,$filename); }
if( $permissions != null) { chmod($filename,$permissions); }
}
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 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);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image; }
}
Use it as prev image, and save new image
$imageRes = new SimpleImage();
$imageRes->load($_SERVER['DOCUMENT_ROOT'] . '/upload/' . $image . '.jpg');//prev image
$imageRes->resizeToWidth(120);
$imageRes->save($_SERVER['DOCUMENT_ROOT'] . '/upload/' . $image . '.jpg');//new image

How to upload image in php

I'm new in php and I'd just like to create a simple website, for that I'd like to resize and upload an image to a server. I'm able to resize it but I don't know how to upload it. Here is my code:
<td><form action="uploadpic.php" method="POST" enctype="multipart/form-data" />
<input type="file" name="user_image" id="user_image" />
<input name = "button" type = "button" id = "button"
value = "Küldés" onclick="subm(this.form,'_blank');">
</form>
</td>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function subm(f,newtarget){
f.submit();
}
</script>
And uploadpic.php:
$target_path = "images/clients/";
$target_path = $target_path . basename( $_FILES['user_image']['name']);
function resize_image($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($_FILES['user_image']['tmp_name']);
echo "original width ". $width." height ". $height;
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*abs($r-$w/$h)));
} else {
$height = ceil($height-($height*abs($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
echo "new width ". $newwidth." height ". $newheight;
//$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newwidth, $newheight);
//imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
function print_var_name($var) {
foreach($GLOBALS as $var_name => $value) {
if ($value === $var) {
return $var_name;
}
}
return false;
}
$img = resize_image($target_path, 50, 50);
if(move_uploaded_file(print_var_name($img), $target_path)) {
echo "The file ". basename( $_FILES['user_image']['name']).
"Image has been uploaded";
} else{
echo "Not uploaded because of error ".print_var_name($img)['error'];
}
After I did a var_dump($_FILES); I got this:
array(1) { ["user_image"]=> array(5) { ["name"]=> string(10) "000oks.jpg"
["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(14) "/tmp/phpt7HaO1"
["error"]=> int(0) ["size"]=> int(606917) } }
The resize funciton is works fine after that I have created a new variable and another funciton to get name of the variable. In move_uploaded_file the first parameter has to be a string: the name of the file which is now img and the second parameter is the path. What am I doing wrong?

How to re size image using PHP, how to remove the error 500 Internal Server Error 817ms

I am doing one file upload in PHP. From here user uploads the large image means, I want to re size the image. I am writing like this but i can't get an answer. I am getting an error like this 500 Internal Server Error x
817ms. After the resizing occurs on the image I want to encode that value, how can I do this?
$.ajax({
formData.append('file', $('input[type=file]')[0].files[0]);
url: 'file_check.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
var res=jQuery.parseJSON(data);// convert the json
console.log(res);
},
});
file_check.php
<?php
/*$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$path = $_FILES['file']['tmp_name'];
$filename = file_get_contents($path);*/
/*
$imgdata = base64_encode($im); // here we got base64 encode value
$idproof = array("encode" => $imgdata,
"path" =>$path,
"extension" =>$extension,
);
echo json_encode($idproof);*/
$image;
$image_type;
//-----------------------------------------------
// Load Image file
//-----------------------------------------------
function load($filename)
{
global $image;
global $image_type;
$image_info = getimagesize($filename);
$image_type = $image_info[2];
if($image_type == IMAGETYPE_JPEG)
{
$image = imagecreatefromjpeg($filename);
}
elseif($image_type == IMAGETYPE_GIF)
{
$image = imagecreatefromgif($filename);
}
elseif($image_type == IMAGETYPE_PNG)
{
$image = imagecreatefrompng($filename);
}
}
//-----------------------------------------------
// Save Image file
//-----------------------------------------------
function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null)
{
global $image;
global $image_type;
if( $image_type == IMAGETYPE_JPEG )
{
imagejpeg($image,$filename,$compression);
}
elseif( $image_type == IMAGETYPE_GIF )
{
imagegif($image,$filename);
}
elseif( $image_type == IMAGETYPE_PNG )
{
imagepng($image,$filename);
}
if( $permissions != null )
{
chmod($filename,$permissions);
}
}
//-----------------------------------------------
// View Image file
//-----------------------------------------------
function output($image_type=IMAGETYPE_JPEG)
{
global $image;
global $image_type;
if( $image_type == IMAGETYPE_JPEG )
{
imagejpeg($image);
}
elseif( $image_type == IMAGETYPE_GIF )
{
imagegif($image);
} elseif( $image_type == IMAGETYPE_PNG )
{
imagepng($image);
}
}
function getWidth()
{
global $image;
return imagesx($image);
}
function getHeight()
{
global $image;
return imagesy($image);
}
//=============================================================================
// Resize Images
//=============================================================================
//-----------------------------------------------
// Resize Images 01 - Resize to Height
//-----------------------------------------------
function resizeToHeight($height)
{
$ratio = $height / getHeight();
$width = getWidth() * $ratio;
resize($width,$height);
}
//-----------------------------------------------
// Resize Images 02 - Resize to Width
//-----------------------------------------------
function resizeToWidth($width)
{
$ratio = $width / getWidth();
$height = getheight() * $ratio;
resize($width,$height);
}
//-----------------------------------------------
// Resize Images 03 - Scale in %
//-----------------------------------------------
function scale($scale)
{
$width = getWidth() * $scale/100;
$height = getheight() * $scale/100;
resize($width,$height);
}
//-----------------------------------------------
// Resize Images 04 - Scale in %
//-----------------------------------------------
function resize($width,$height)
{
global $image;
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $width, $height, getWidth(), getHeight());
$image = $new_image;
}
echo load($_FILES['IMAGE_FILE']['tmp_name']);
// To resize based on image width
echo resizeToWidth($width);
// To resize based on image height
echo resizeToHeight($height);
// To resize to specific size
echo resize($width, $height)
echo output();
$filename = base64_encode(output());
$idproof = array("encode" => $filename,
);
echo json_encode($idproof);
?>
<form method="post" enctype="multipart/form-data" class="form-horizontal" id="idproof" name="myForm">
<div class="input-group heading1">
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input type="file" id="myFile" name="file" >
</span>
</span>
<input type="text" class="form-control" readonly="">
</div>
</div>
</div>
<div class="row">
<div class="col-md-5 col-md-offset-2">
<div class="input-group heading1">
<span class="input-group-btn">
<button type="submit" class="btn btn-primary btn-md horoscope">Upload ID Proof</button>
</div>
</div>
</div>
</form

Creating a thumbnail from an uploaded image

I'm wanting to create a thumbnail from a user uploaded image so the image doesn't look squashed. But also would like a copy of the original image.. So I would like the original image to send the original image to my server and also create a thumb version and send it to my server so I can call each of them for each user that uploads their own image.
My user table has 2 tables
`user_pic` longblob NOT NULL,
`user_pic_small` longblob NOT NULL,
I'm not crash hot with the image side of coding but this is what I have so far.
Imageupload.php
> <form id="myForm" action="include/media.profileimage.upload.php"
> method="POST" enctype="multipart/form-data" target="ifr1">
> <input type = "file" name = "image_data" class = "input_text" style="width:800px;" >
> <input type = "submit" name = "submit" class = "btn_login" value = "Upload">
> </form>
media.profileimage.upload.php
if(isset($_FILES['image_data'])){
if(is_uploaded_file($_FILES['image_data']['tmp_name'])) {
// prepare the image for insertion
$imgData =addslashes (file_get_contents($_FILES['image_data']['tmp_name']));
// get the image info..
$size = getimagesize($_FILES['image_data']['tmp_name']);
// our sql query
$creator_id = $_SESSION['id'];
$sql = "UPDATE users SET user_pic='".$imgData."' WHERE id=$creator_id";
$sql2 = "INSERT INTO userphotos(photo_ownerid,photo_ispublic, photo_name, photo_caption, photo_imagedata) VALUES ($creator_id,1,'Profile Picture','Profile Picture','$imgData')";
// insert the image
if(!mysql_query($sql)) {
echo "Fail. It broke.";
}else{
$c=mysql_query($sql2);
echo "<script> parent.alert('Image Uploaded','',1000);</script>";
}
}
}
Would appreciate any help or guidence. Thankyou
UPDATE:
If you want to take advantage of Imagick (if it is installed on your server). Note: I didn't use Imagick's nature writeFile because I was having issues with it on my server. File put contents works just as well.
<?php
/**
*
* Generate Thumbnail using Imagick class
*
* #param string $img
* #param string $width
* #param string $height
* #param int $quality
* #return boolean on true
* #throws Exception
* #throws ImagickException
*/
function generateThumbnail($img, $width, $height, $quality = 90)
{
if (is_file($img)) {
$imagick = new Imagick(realpath($img));
$imagick->setImageFormat('jpeg');
$imagick->setImageCompression(Imagick::COMPRESSION_JPEG);
$imagick->setImageCompressionQuality($quality);
$imagick->thumbnailImage($width, $height, false, false);
$filename_no_ext = reset(explode('.', $img));
if (file_put_contents($filename_no_ext . '_thumb' . '.jpg', $imagick) === false) {
throw new Exception("Could not put contents.");
}
return true;
}
else {
throw new Exception("No valid image provided with {$img}.");
}
}
// example usage
try {
generateThumbnail('test.jpg', 100, 50, 65);
}
catch (ImagickException $e) {
echo $e->getMessage();
}
catch (Exception $e) {
echo $e->getMessage();
}
?>
I have been using this, just execute the function after you store the original image and use that location to create the thumbnail. Edit it to your liking...
function makeThumbnails($updir, $img, $id)
{
$thumbnail_width = 134;
$thumbnail_height = 189;
$thumb_beforeword = "thumb";
$arr_image_details = getimagesize("$updir" . $id . '_' . "$img"); // pass id to thumb name
$original_width = $arr_image_details[0];
$original_height = $arr_image_details[1];
if ($original_width > $original_height) {
$new_width = $thumbnail_width;
$new_height = intval($original_height * $new_width / $original_width);
} else {
$new_height = $thumbnail_height;
$new_width = intval($original_width * $new_height / $original_height);
}
$dest_x = intval(($thumbnail_width - $new_width) / 2);
$dest_y = intval(($thumbnail_height - $new_height) / 2);
if ($arr_image_details[2] == IMAGETYPE_GIF) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
}
if ($arr_image_details[2] == IMAGETYPE_JPEG) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
}
if ($arr_image_details[2] == IMAGETYPE_PNG) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
}
if ($imgt) {
$old_image = $imgcreatefrom("$updir" . $id . '_' . "$img");
$new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imagecopyresized($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
$imgt($new_image, "$updir" . $id . '_' . "$thumb_beforeword" . "$img");
}
}
The above function creates images with a uniform thumbnail size. If the image doesn't have the same dimensions as the specified thumbnail size (proportionally), it just has blackspace on the top and bottom.
You Can Use The Simplest Method
<?php
function make_thumb($src, $dest, $desired_width) {
/* read the source image */
$source_image = imagecreatefromjpeg($src);
$width = imagesx($source_image);
$height = imagesy($source_image);
/* find the "desired height" of this thumbnail, relative to the desired width */
$desired_height = floor($height * ($desired_width / $width));
/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
/* copy source image at a resized size */
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
/* create the physical thumbnail image to its destination */
imagejpeg($virtual_image, $dest);
}
$src="1494684586337H.jpg";
$dest="new.jpg";
$desired_width="200";
make_thumb($src, $dest, $desired_width);
?>
I'm guessing you have already figured this one out. But I see that you are storing the images as "longblobs" leading me to think you are storing the entire binary content of the pic.
I hope you have realized that it makes much more sense to simply store the file names in your DB and then use that info to grab the pics out of an "upload" folder or similar.
TIP - dont save a file path.. just the file name .. add the path info in your code as needed. That way you have the most freedom down the line. If you need to change folder structure, you can do it in your code rather than changing DB records.
I know this is an old question, but I stumbled upon the same problem and tried to use the function given in Alex's answer.
But the quality in the jpeg result was too low. So I changed the function a little bit to become more usable in my project and changed the "imagecopyresized" to "imagecopyresampled" (according to this recomendation).
If you are having questions about how to use this function, then try taking a look at the well documented version here.
function createThumbnail($filepath, $thumbpath, $thumbnail_width, $thumbnail_height, $background=false) {
list($original_width, $original_height, $original_type) = getimagesize($filepath);
if ($original_width > $original_height) {
$new_width = $thumbnail_width;
$new_height = intval($original_height * $new_width / $original_width);
} else {
$new_height = $thumbnail_height;
$new_width = intval($original_width * $new_height / $original_height);
}
$dest_x = intval(($thumbnail_width - $new_width) / 2);
$dest_y = intval(($thumbnail_height - $new_height) / 2);
if ($original_type === 1) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
} else if ($original_type === 2) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
} else if ($original_type === 3) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
} else {
return false;
}
$old_image = $imgcreatefrom($filepath);
$new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height); // creates new image, but with a black background
// figuring out the color for the background
if(is_array($background) && count($background) === 3) {
list($red, $green, $blue) = $background;
$color = imagecolorallocate($new_image, $red, $green, $blue);
imagefill($new_image, 0, 0, $color);
// apply transparent background only if is a png image
} else if($background === 'transparent' && $original_type === 3) {
imagesavealpha($new_image, TRUE);
$color = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
imagefill($new_image, 0, 0, $color);
}
imagecopyresampled($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
$imgt($new_image, $thumbpath);
return file_exists($thumbpath);
}
just in case you need to create thumb with a max width and a max height ...
function makeThumbnails($updir, $img, $id,$MaxWe=100,$MaxHe=150){
$arr_image_details = getimagesize($img);
$width = $arr_image_details[0];
$height = $arr_image_details[1];
$percent = 100;
if($width > $MaxWe) $percent = floor(($MaxWe * 100) / $width);
if(floor(($height * $percent)/100)>$MaxHe)
$percent = (($MaxHe * 100) / $height);
if($width > $height) {
$newWidth=$MaxWe;
$newHeight=round(($height*$percent)/100);
}else{
$newWidth=round(($width*$percent)/100);
$newHeight=$MaxHe;
}
if ($arr_image_details[2] == 1) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
}
if ($arr_image_details[2] == 2) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
}
if ($arr_image_details[2] == 3) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
}
if ($imgt) {
$old_image = $imgcreatefrom($img);
$new_image = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresized($new_image, $old_image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
$imgt($new_image, $updir."".$id."_t.jpg");
return;
}
}
Hope this code helps for creating Thumbnail for JPG, PNG & GIF formats.
<?php
$file = "D:/server/sites/Sourcefol/high/bucket/kath23.png"; /*Your Original Source Image */
$pathToSave = "D:/server/sites/Sourcefol/high/bucket/New/"; /*Your Destination Folder */
$sourceWidth =60;
$sourceHeight = 60;
$what = getimagesize($file);
$file_name = basename($file);/* Name of the Image File*/
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
/* Adding image name _thumb for thumbnail image */
$file_name = basename($file_name, ".$ext") . '_thumb.' . $ext;
switch(strtolower($what['mime']))
{
case 'image/png':
$img = imagecreatefrompng($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/png');
break;
case 'image/jpeg':
$img = imagecreatefromjpeg($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/jpeg');
break;
case 'image/gif':
$img = imagecreatefromgif($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/gif');
break;
default: die();
}
imagejpeg($new,$pathToSave.$file_name);
imagedestroy($new);
?>
Image Upload with thumbnail generate
upload.php
<?php
function generate_thumb_now($field_name = '',$target_folder ='',$file_name = '', $thumb = FALSE, $thumb_folder = '', $thumb_width = '',$thumb_height = ''){
//folder path setup
$target_path = $target_folder;
$thumb_path = $thumb_folder;
//file name setup
$filename_err = explode(".",$_FILES[$field_name]['name']);
$filename_err_count = count($filename_err);
$file_ext = $filename_err[$filename_err_count-1];
if($file_name != '')
{
$fileName = $file_name.'.'.$file_ext;
}
else
{
$fileName = $_FILES[$field_name]['name'];
}
//upload image path
$upload_image = $target_path.basename($fileName);
//upload image
if(move_uploaded_file($_FILES[$field_name]['tmp_name'],$upload_image))
{
//thumbnail creation
if($thumb == TRUE)
{
$thumbnail = $thumb_path.$fileName;
list($width,$height) = getimagesize($upload_image);
$thumb_create = imagecreatetruecolor($thumb_width,$thumb_height);
switch($file_ext){
case 'jpg':
$source = imagecreatefromjpeg($upload_image);
break;
case 'jpeg':
$source = imagecreatefromjpeg($upload_image);
break;
case 'png':
$source = imagecreatefrompng($upload_image);
break;
case 'gif':
$source = imagecreatefromgif($upload_image);
break;
default:
$source = imagecreatefromjpeg($upload_image);
}
imagecopyresized($thumb_create, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width,$height);
switch($file_ext){
case 'jpg' || 'jpeg':
imagejpeg($thumb_create,$thumbnail,100);
break;
case 'png':
imagepng($thumb_create,$thumbnail,100);
break;
case 'gif':
imagegif($thumb_create,$thumbnail,100);
break;
default:
imagejpeg($thumb_create,$thumbnail,100);
}
}
return $fileName;
}
else
{
return false;
}
}
if(!empty($_FILES['image']['name'])){
$upload_img = generate_thumb_now('image','uploads/','',TRUE,'uploads /thumbs/','400','320');
//full path of the thumbnail image
$thumb_src = 'uploads/thumbs/'.$upload_img;
//set success and error messages
$message = $upload_img?"<span style='color:#008000;'>Image thumbnail created successfully.</span>":"<span style='color:#F00000;'>Some error occurred, please try again.</span>";
}else{
//if form is not submitted, below variable should be blank
$thumb_src = '';
$message = '';
}
?>
<html>
<head>Image upload and generate thumbnail</head>
<body>
<div class="messages"><?php echo $message; ?></div>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="submit" value="Upload"/>
</form>
<?php if($thumb_src != ''){ ?>
<div class="gallery">
<ul>
<li><img src="<?php echo $thumb_src; ?>" alt=""></li>
</ul>
</div>
<?php } ?>
</body>
</html>
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysql_query("INSERT INTO users (uid, profile_image) VALUES ('$session_id' , '$actual_image_name')");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "Fail upload folder with read access.";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
<?php
error_reporting(0);
$change="";
$abc="";
define ("MAX_SIZE","4000");
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$errors=0;
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$image =$_FILES["file"]["name"];
$uploadedfile = $_FILES['file']['tmp_name'];
if ($image)
{
$filename = stripslashes($_FILES['file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
$change='<div class="msgdiv">Unknown Image extension </div> ';
$errors=1;
}
else
{
$size=filesize($_FILES['file']['tmp_name']);
if ($size > MAX_SIZE*1024)
{
$change='<div class="msgdiv">You have exceeded the size limit!</div> ';
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
echo $scr;
list($width,$height)=getimagesize($uploadedfile);
$newwidth=45;
$newheight=45;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=90;
$newheight1=90;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
$tmp2=imagecreatetruecolor($width,$height);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
imagecopyresampled($tmp2,$src,0,0,0,0,$width,$height,$width,$height);
$filename = "images/1-". $_FILES['file']['name']=time();
$filename1 = "images/2-". $_FILES['file']['name']=time();
$filename2 = "images/3-". $_FILES['file']['name']=time();
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
imagejpeg($tmp2,$filename2,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}
}
if(isset($_POST['Submit']) && !$errors)
{
// mysql_query("update {$prefix}users set img='$big',img_small='$small' where user_id='$user'");
$change=' <div class="msgdiv">Image Uploaded Successfully!</div>';
}
?>
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>
<title>picture demo</title>
<link href=".css" media="screen, projection" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery_002.js"></script>
<script type="text/javascript" src="js/displaymsg.js"></script>
<script type="text/javascript" src="js/ajaxdelete.js"></script>
<style type="text/css">
.help
{
font-size:11px; color:#006600;
}
body {
color: #000000;
background-color:#999999 ;
background:#999999 url(<?php echo $user_row['img_src']; ?>) fixed repeat top left;
font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
}
.msgdiv{
width:759px;
padding-top:8px;
padding-bottom:8px;
background-color: #fff;
font-weight:bold;
font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px;
}
#container{width:763px;margin:0 auto;padding:3px 0;text-align:left;position:relative; -moz-border-radius: 6px;-webkit-border-radius: 6px; background-color:#FFFFFF }
</style>
</head><body>
<div align="center" id="err">
<?php echo $change; ?> </div>
<div id="space"></div>
<div id="container" >
<div id="con">
<table width="502" cellpadding="0" cellspacing="0" id="main">
<tbody>
<tr>
<td width="500" height="238" valign="top" id="main_right">
<div id="posts">
<img src="<?php// echo $filename; ?>" /> <img src="<?php// echo $filename1; ?>" />
<form method="post" action="" enctype="multipart/form-data" name="form1">
<table width="500" border="0" align="center" cellpadding="0" cellspacing="0">
<tr><Td style="height:25px"> </Td></tr>
<tr>
<td width="150"><div align="right" class="titles">Picture
: </div></td>
<td width="350" align="left">
<div align="left">
<input size="25" name="file" type="file" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10pt" class="box"/>
</div></td>
</tr>
<tr><Td></Td>
<Td valign="top" height="35px" class="help">Image maximum size <b>4000 </b>kb</span></Td>
</tr>
<tr><Td></Td><Td valign="top" height="35px"><input type="submit" id="mybut" value=" Upload " name="Submit"/></Td></tr>
<tr>
<td width="200"> </td>
<td width="200"><table width="200" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="200" align="center"><div align="left"></div></td>
<td width="100"> </td>
</tr>
</table></td>
</tr>
</table>
</form>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body></html>

Categories