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>
Related
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>
I have the following php script to create thumbnail after uploading an image. It is working properly, but it creates a black background and does not center the image if it is not the size you want, does anyone know how to leave the white background and center it?
How to fix it
https://imgur.com/a/uTrPadZ
if($_SERVER['REQUEST_METHOD']=='POST')
{
$filetmp = $_FILES["image"]["tmp_name"];
$filename = $_FILES["image"]["name"];
$filetype = $_FILES["image"]["type"];
$filesize = $_FILES["image"]["size"];
$fileinfo = getimagesize($_FILES["image"]["tmp_name"]);
$filewidth = $fileinfo[0];
$fileheight = $fileinfo[1];
$filepath = "../uploads/";
$filepath_thumb = "../thumbnail/";
if($filetmp == "")
{
echo "please select a photo";
}
else
{
if($filesize > 2097152)
{
echo "photo > 2mb";
}
else
{
if($filetype != "image/jpeg" && $filetype != "image/png" && $filetype != "image/gif")
{
echo "Please upload jpg / png / gif";
}
else
{
$final_image = rand(1000,1000000).$filename;
$filepath = $filepath.strtolower($final_image);
move_uploaded_file($filetmp,$filepath);
if($filetype == "image/jpeg")
{
$imagecreate = "imagecreatefromjpeg";
$imageformat = "imagejpeg";
}
if($filetype == "image/png")
{
$imagecreate = "imagecreatefrompng";
$imageformat = "imagepng";
}
if($filetype == "image/gif")
{
$imagecreate= "imagecreatefromgif";
$imageformat = "imagegif";
}
$new_width = "200";
$new_height = "200";
$filepath_thumb = $filepath_thumb.strtolower($final_image);
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = $imagecreate($filepath); //photo folder
if($filewidth > $fileheight)
{
$thumb_w = $new_width;
$thumb_h = $fileheight*($new_height/$filewidth);
}
if($filewidth < $fileheight)
{
$thumb_w = $filewidth*($new_width/$fileheight);
$thumb_h = $new_height;
}
if($filewidth == $fileheight)
{
$thumb_w = $new_width;
$thumb_h = $new_height;
}
$dst_img = ImageCreateTrueColor($thumb_w,$thumb_h);
imagecopyresampled($image_p,$image,0,0,0,0,$thumb_w,$thumb_h,$filewidth,$fileheight);
$imageformat($image_p, $filepath_thumb);//thumb folder
}
}
}
}
Black is the default background, you just have to set the background colour of the new image to white first.
//set background colour white before copying
$white = imagecolorallocate($image_p, 255, 255, 255);
imagefill($image_p, 0, 0, $white);
imagecopyresampled($image_p,$image,0,0,0,0,$thumb_w,$thumb_h,$filewidth,$fileheight);
$imageformat($image_p, $filepath_thumb);//thumb folder
Also, $dst_img doesn't appear to be used.
Centering (untested, but simple enough math):
$xOffset = (imagesx($p_image)-$thumb_w) / 2;
$yOffset = (imagesy($p_image)-$thumb_h) / 2;
imagecopyresampled($image_p,$image,$offsetX,$offsetY,0,0,$thumb_w,$thumb_h,$filewidth,$fileheight);
If you know which dimension does not match the new thumbnail dimension this could be simplified.
so i have this script to upload files, and yes i know it's not secure. Howe ever, My problem right now is that i can upload files named filename.php.jpg. So how can i prevent files like theese to upload? I have used other stuff to stop php files from being executed.
<?php
$maindir = "../alla_bilder/images/";
$maindir_th = "../alla_bilder/images/thumbs/";
$uploaddir = "images/";
$uploaddir_th = "images/thumbs/";
$allowed = array('jpg','jpeg','png');
$notallowed = array('php');
$uploadOk = 1;
$max_size = 5048 * 1024;
while (list ($key, $val) = each ($_FILES))
{
if ($_FILES[$key]['size'] <= $max_size)
{
$file_ext = pathinfo($_FILES[$key]['name'],PATHINFO_EXTENSION);
$file_name = basename($_FILES[$key]['name'],'.'.$file_ext);
if (in_array(strtolower($file_ext),$allowed))
{
$name = $_FILES[$key]['name'];
$x = 1;
while (file_exists($uploaddir.'/'.$name))
{
$name = $file_name.'['.$x.'].'.$file_ext;
$x++;
}
$name = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 22)), 0, 22). '.' .mb_strtolower ($file_ext);
if (move_uploaded_file($_FILES[$key]['tmp_name'],$uploaddir.'/'.$name))
{
chmod($uploaddir.'/'.$name, 0644);
}
else
{
die(error_get_last());
}
}
else
{
die("Invalid file type");
}
}
else
{
die("File size too big");
}
copy($uploaddir.'/'.$name, $maindir.'/'.$name);
$images = glob("images/thumbs/*.*");
foreach($images as $image)
{
$output .= '<div class="col-md-2" align="center" ><img src="' . $image .'" width="200px" height="140px" style="border:1px solid #ccc;" /></div>';
}
//thumbnail image making part
$modwidth = 200;
$modheight = 140;
list($width, $height) = getimagesize($uploaddir.'/'.$name);
$ratio_orig = $width/$height;
if ($width/$height > $ratio_orig)
{
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
$tn = imagecreatetruecolor($modwidth, $modheight);
//$image = imagecreatefromjpeg($uploaddir.'/'.$name);
$image = imagecreatefromstring(file_get_contents($uploaddir.'/'.$name));
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
imagejpeg($tn, $uploaddir_th.'/'.$name);
imagejpeg($tn, $maindir_th.'/'.$name);
}
echo "STOP!";
?>
Take a look at the finfo extension, this allows you to determine the true file type as it sniffs the file type at the OS level.
http://php.net/manual/en/function.finfo-file.php
As finfo is an extension it will need to be installed and enabled.
http://php.net/manual/en/fileinfo.installation.php
Example
$path = $_FILES[$key]['tmp_name'],$uploaddir.'/'.$name;
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$whitelist = array('image/jpg');
if (in_array(finfo_file($finfo, $path), $whitelist) && move_uploaded_file($path))
{
chmod($uploaddir.'/'.$name, 0644);
}
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
<?php
$newname = md5(rand() * time());
$file1 = isset($_FILES['files']['name'][0]) ? $_FILES['files']['name'][0] : null;
$file2 = isset($_FILES['files']['name'][1]) ? $_FILES['files']['name'][1] : null;
$file3 = isset($_FILES['files']['name'][2]) ? $_FILES['files']['name'][2] : null;
$file4 = isset($_FILES['files']['name'][3]) ? $_FILES['files']['name'][3] : null;
$file5 = isset($_FILES['files']['name'][4]) ? $_FILES['files']['name'][4] : null;
if (isset($_FILES['files'])) {
$errors = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$file_name = $key . $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if ($file_size > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
$desired_dir = "user_data/";
if (empty($errors) == true) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if (is_dir("$desired_dir/" . $file_name) == false) {
move_uploaded_file($file_tmp, "$desired_dir/" . $newname . $file_name);
} else { // rename the file if another one exist
$new_dir = "$desired_dir/" . $newname . $file_name;
rename($file_tmp, $new_dir);
}
} else {
print_r($errors);
}
}
if (empty($error)) {
echo "FILE : $file1<br>";
echo "FILE : $file2<br>";
echo "FILE : $file3<br>";
echo "FILE : $file4<br>";
echo "FILE : $file5<br>";
}
}
$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);
}
?>
When i run code this how am getting out put file, don't know whats going on can some one help me find the error
Black thumb is created for all type image formate
When i remove the following code from above code it works what does this code does
if($w> $h) {
$adjusted_width = $w / $hm;
$half_width = $adjusted_width / 2;
$int_width = $w / $hm;
imagecopyresampled($dimg,$simg,-$int_width,0,0,0,0,$adjusted_width,$nw,$nh,$w,$h);
} else
Problem
The problem is located in the following line:
imagecopyresampled($dimg, $simg, -$int_width, 0, 0, 0, $adjusted_width, $nh, $w, $h);
Why are you using a negative value as destination's x? Your source image is actually put at the left of your target image, so your target image appears empty.
Solution
I invite you to use the following function to resize your image:
function resizePreservingAspectRatio($img, $targetWidth, $targetHeight)
{
$srcWidth = imagesx($img);
$srcHeight = imagesy($img);
// Determine new width / height preserving aspect ratio
$srcRatio = $srcWidth / $srcHeight;
$targetRatio = $targetWidth / $targetHeight;
if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight))
{
$imgTargetWidth = $srcWidth;
$imgTargetHeight = $srcHeight;
}
else if ($targetRatio > $srcRatio)
{
$imgTargetWidth = (int) ($targetHeight * $srcRatio);
$imgTargetHeight = $targetHeight;
}
else
{
$imgTargetWidth = $targetWidth;
$imgTargetHeight = (int) ($targetWidth / $srcRatio);
}
// Creating new image with desired size
$targetImg = imagecreatetruecolor($targetWidth, $targetHeight);
// Add transparency if your reduced image does not fit with the new size
$targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
imagefill($targetImg, 0, 0, $targetTransparent);
imagecolortransparent($targetImg, $targetTransparent);
// Copies image, centered to the new one (if it does not fit to it)
imagecopyresampled(
$targetImg, $img, ($targetWidth - $imgTargetWidth) / 2, // centered
($targetHeight - $imgTargetHeight) / 2, // centered
0, 0, $imgTargetWidth, $imgTargetHeight, $srcWidth, $srcHeight
);
return $targetImg;
}
Implementation
<?php
$newname = md5(rand() * time());
$file1 = isset($_FILES['files']['name'][0]) ? $_FILES['files']['name'][0] : null;
$file2 = isset($_FILES['files']['name'][1]) ? $_FILES['files']['name'][1] : null;
$file3 = isset($_FILES['files']['name'][2]) ? $_FILES['files']['name'][2] : null;
$file4 = isset($_FILES['files']['name'][3]) ? $_FILES['files']['name'][3] : null;
$file5 = isset($_FILES['files']['name'][4]) ? $_FILES['files']['name'][4] : null;
if (isset($_FILES['files']))
{
$errors = array ();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name)
{
$file_name = $key . $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if ($file_size > 2097152000)
{
$errors[] = 'File size must be less than 2 MB';
}
$desired_dir = "user_data/";
if (empty($errors) == true)
{
if (is_dir($desired_dir) == false)
{
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if (is_dir("$desired_dir/" . $file_name) == false)
{
move_uploaded_file($file_tmp, "$desired_dir/" . $newname . $file_name);
}
else
{ // rename the file if another one exist
$new_dir = "$desired_dir/" . $newname . $file_name;
rename($file_tmp, $new_dir);
}
}
else
{
print_r($errors);
}
}
if (empty($error))
{
echo "FILE : $file1<br>";
echo "FILE : $file2<br>";
echo "FILE : $file3<br>";
echo "FILE : $file4<br>";
echo "FILE : $file5<br>";
}
$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 = resizePreservingAspectRatio($simg, $nw, $nh);
imagepng($dimg, $dest);
}
}
/* Closing the directory */
#closedir($dir_handle);
}
}
function resizePreservingAspectRatio($img, $targetWidth, $targetHeight)
{
$srcWidth = imagesx($img);
$srcHeight = imagesy($img);
// Determine new width / height preserving aspect ratio
$srcRatio = $srcWidth / $srcHeight;
$targetRatio = $targetWidth / $targetHeight;
if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight))
{
$imgTargetWidth = $srcWidth;
$imgTargetHeight = $srcHeight;
}
else if ($targetRatio > $srcRatio)
{
$imgTargetWidth = (int) ($targetHeight * $srcRatio);
$imgTargetHeight = $targetHeight;
}
else
{
$imgTargetWidth = $targetWidth;
$imgTargetHeight = (int) ($targetWidth / $srcRatio);
}
// Creating new image with desired size
$targetImg = imagecreatetruecolor($targetWidth, $targetHeight);
// Add transparency if your reduced image does not fit with the new size
$targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
imagefill($targetImg, 0, 0, $targetTransparent);
imagecolortransparent($targetImg, $targetTransparent);
// Copies image, centered to the new one (if it does not fit to it)
imagecopyresampled(
$targetImg, $img, ($targetWidth - $imgTargetWidth) / 2, // centered
($targetHeight - $imgTargetHeight) / 2, // centered
0, 0, $imgTargetWidth, $imgTargetHeight, $srcWidth, $srcHeight
);
return $targetImg;
}
?>
<form method="post" enctype="multipart/form-data">
<input name="files[]" type="file"/><br/>
<input name="files[]" type="file"/><br/>
<input name="files[]" type="file"/><br/>
<input name="files[]" type="file"/><br/>
<input name="files[]" type="file"/><br/>
<input type="submit"/>
</form>
Note: I am saving as PNG, as if you want a 100x100 image using a non-square image (such as 800x600), and without breaking its aspect ratio, we should put transparency behind the unused space and JPEG do not support it.
This is my code for uploading multiple files and cropping and cropping them.
It uploads the image to a folder, then picks the image, crops it , re-uploads the cropped image and deletes the original image.
Am sure you can play around with this
This is the php code
if(isset($_POST['upload_gal']))
{
$fk_id = $_POST['fk_id'];
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_type=='image/jpeg'||$type=='image/gif'||$type=='image/bmp'||$type=='image/png')
{
$image_info = getimagesize($_FILES["files"]["tmp_name"][$key]);
$image_width = $image_info[0];
$image_height = $image_info[1];
$desired_dir="brand_images/";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0755); // Create directory if it does not exist
}
$locationing="brand_images/$file_name";
move_uploaded_file($file_tmp,$locationing);
$image = imagecreatefromstring(file_get_contents("brand_images/$file_name"));
$rand = rand(111,43943749739349343);
$filename = "brand_images/$rand-33$file_name";
if($image_width >= 840 && $image_height >= 680)
{
$thumb_width = 1200;
$thumb_height = 700;
}else{
$thumb_width = 800;
$thumb_height = 533;
}
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect )
{
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}
else
{
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 2, // Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
imagejpeg($thumb, $filename, 80);
move_uploaded_file($tmp_name, $filename);
mysql_query("INSERT INTO gallery VALUES('','brand_images/$rand-33$file_name','$fk_id')");
echo"<script>
window.location = document.URL.replace(/#$/, '');
</script>";
}
This is the html
<form action="" enctype="multipart/form-data" method="POST">
<h3 class="no_margin-top">Upload a new image</h3>
<hr>
<input type="hidden" name="fk_id" value="<?php echo $brand->brand_id ?>">
<input name="upload_gal" type="submit" class="btn btn-sm pull-right btn-success" value="Upload">
Upload image: <input type="file" name="files[]" multiple>
<p class="text-danger top-buffer">If image is larger than 800x533, the image would be cropped</p>
</form>
The following code will solve the problem by mapping to the correct imagecreatefrom* function or throw an exception with the invalid image type.
switch(strtolower($stype)) {
case 'gif':
$simg = imagecreatefromgif($source);
break;
case 'jpg':
case 'jpeg':
$simg = imagecreatefromjpeg($source);
break;
case 'png':
$simg = imagecreatefrompng($source);
break;
default:
throw new \Exception('invalid image type :'.$stype);
break;
}
I think it's better to go for the mime type than the extension.
You'll do this:
function check_supported_type($type)
{
switch($type)
{
case "image/jpeg":
case "image/gif":
case "image/png":
return true;
default:
return false;
}
}
function GetMimeType($file)
{
//$type = mime_content_type($file); //deprecated
/* //file info -> normal method, but returns wrong values for ics files..
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
$type = $filename.":".finfo_file($finfo, $filename);
finfo_close($finfo);
*/
$forbiddenChars = array('?', '*', ':', '|', ';', '<', '>');
if(strlen(str_replace($forbiddenChars, '', $file)) < strlen($file))
throw new \ArgumentException("Forbidden characters!");
$file = escapeshellarg($file);
ob_start();
$type = system("file --mime-type -b ".$file);
ob_clean();
return $type;
}
use it like this:
$file = "someimage.jpg";
$mime = GetMimeType($file);
if(check_supported_type($mime))
{
//do your image processing
}
hope this helps
EDIT:
Maybe you can take a look at my other answer: https://stackoverflow.com/a/26981319/3641016 there you'll see how to generate thumbs.
EDIT:
added the answer to your editet question:
replace:
$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);
}
with:
if($w > $h)
{
imagecopyresampled($dimg, $simg, 0,0, ($nw / $h * $w / 2 - $nw / 2),0, $nw,$nw, $h,$h);
}
else
{
imagecopyresampled($dimg, $simg, 0,0, 0,($nw / $w * $h / 2 - $nw / 2), $nw,$nw, $w,$w);
}
and everything should be ok. (if the thumb is quadratic)
I created a form to upload into a MySQL table text data and images' paths. The images are uploaded and stored in folders of the server. It worked perfect till i used php session. I used PHP session_start at the begining of the code (for access through username and password) and then it does not import data to the database. It displays an error of "Fatal error: Call to undefined function resizeImage()" on line 84.
Any recomendations to find out why the function resizeImage() doesn't work when I add session_start?
file: eis-post2.php
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<title>Upload form</title>
</head>
<body>
<form name='newad' method='post' enctype='multipart/form-data' action=".$_SERVER['PHP_SELF'].">
<table>
<tr><td>title:</td><td><input type='text' name='title'></td></tr>
<tr><td>date</td><td><input type='date' name='date'></td></tr>
<tr><td>descriptionΠεριγραφή:</td><td><input type='text' name='desc'></td></tr>
<tr><td>sourse</td><td><input type='text' name='author'></td></tr>
<tr><td>Main text</td><td><textarea name='maintext' id='maintext' required=''></textarea></td></tr>
<tr><td>Image</td><td><input type='file' name='image'></td></tr>
<tr><td> </td><td><input name='Submit' type='submit' value='Upload image'></td> </tr>
</table>
</form>
</body>
</html>";
define ("MAX_SIZE","500");
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$errors=0;
if(isset($_POST['Submit']))
{
$image=$_FILES['image']['name'];
$image=uniqid() . '.jpg';
if ($image)
{
$filename = stripslashes($_FILES['image']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
$size=filesize($_FILES['image']['tmp_name']);
if ($size > MAX_SIZE*2048)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}
else {
$temp=resizeImage($_FILES['image']['tmp_name'],270,230);
$imgfile="images/small/".$image;
imagejpeg ( $temp, $imgfile );
$temp2=resizeImage($_FILES['image']['tmp_name'],480,330);
$imgfile2="images/big/".$image;
imagejpeg ( $temp2, $imgfile2 );
}
}
}
else
{
echo "<h1>Select Image File</h1>";
$errors=1;
}
}
if(isset($_POST['Submit']) && !$errors)
{
echo "<h1>File Uploaded Successfully! Try again!</h1>";
include('db.php');
mysql_query("SET NAMES 'utf8'");
$title=$_POST['title'];
$date=$_POST['date'];
$desc=$_POST['desc'];
$author=$_POST['author'];
$maintext=$_POST['maintext'];
$query="insert into post( small_img, big_img, title, date, description, post_text, post_author)
values( '$imgfile', '$imgfile2', '$_POST[title]', '$_POST[date]', '$_POST[desc]','$_POST[author]', '$_POST[maintext]' )";
$result=mysql_query($query);
if ($result)
{
echo "Information stored successfully";
}
else
{
echo mysql_error();
}
}
function resizeImage($imgSrc,$thumbnail_width,$thumbnail_height) {
list($width_orig, $height_orig) = getimagesize($imgSrc);
$myImage = imagecreatefromjpeg($imgSrc);
$ratio_orig = $width_orig/$height_orig;
if ($thumbnail_width/$thumbnail_height > $ratio_orig) {
$new_height = $thumbnail_width/$ratio_orig;
$new_width = $thumbnail_width;
} else {
$new_width = $thumbnail_height*$ratio_orig;
$new_height = $thumbnail_height;
}
$x_mid = $new_width/2; //horizontal middle
$y_mid = $new_height/2; //vertical middle
$process = imagecreatetruecolor(round($new_width), round($new_height));
imagecopyresampled($process, $myImage, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig);
$thumb = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imagecopyresampled($thumb, $process, 0, 0, ($x_mid-($thumbnail_width/2)), ($y_mid-($thumbnail_height/2)), $thumbnail_width, $thumbnail_height, $thumbnail_width, $thumbnail_height);
imagedestroy($process);
imagedestroy($myImage);
return $thumb;
}
}
else {
die("you must be logged in!");
}
?>