Image upload works, thumbnail is skewed? - php

When uploading to my server the regular image uploads fine but for some images when the thumbnail is being created the mage rotates and I don't know why or what's going on with my code?
Please note I'm using old syntax and I know it's ugly but I'm lazy and it works.
<? session_start(); ?>
<? include('header.inc.php'); ?>
<?
if(isset($_POST['upload_Submit'])) {
$_SESSION['success'] = 0;
$upPath = "/home/dolphina/public_html/images/";
$fileName = uniqid(time().date(mdY));
$_SESSION['upload_Error'] = 0;
$error_Log = "<ul>";
if ($_FILES['upload_Image']['size'] > 10000000) {
$error_Log .= "<li>image is greater than 10 megabyte</li>";
$_SESSION['upload_Error'] = 1;
}
if (($_FILES['upload_Image']['type'] == "image/gif") || ($_FILES['upload_Image']['type'] == "image/pjpeg") || ($_FILES['upload_Image']['type'] == "image/jpeg") || ($_FILES['upload_Image']['type'] == "image/png")) {
if($_FILES['upload_Image']['type'] == "image/gif") {
$fileExt = ".gif";
}
if($_FILES['upload_Image']['type'] == "image/pjpeg") {
$fileExt = ".jpg";
}
if($_FILES['upload_Image']['type'] == "image/jpeg") {
$fileExt = ".jpeg";
}
if($_FILES['upload_Image']['type'] == "image/png") {
$fileExt = ".png";
}
} else {
$error_Log .= "<li>invalid image type</li>";
$_SESSION['upload_Error'] = 1;
}
if(!$_POST['upload_Caption']) {
$error_Log .= "<li>no caption entered</li>";
$_SESSION['upload_Error'] = 1;
}
if(!$_POST['upload_Password']) {
$error_Log .= "<li>no password entered</li>";
$_SESSION['upload_Error'] = 1;
}
if($_POST['upload_Password'] != "3") {
$error_Log .= "<li>wrong password</li>";
$_SESSION['upload_Error'] = 1;
}
$error_Log .= "</ul>";
if($_SESSION['upload_Error'] == 1) {
echo $error_Log;
$_SESSION['upload_Error'] = 0;
} else {
//COPIES TEMP FILE TO PATH
copy($_FILES['upload_Image']['tmp_name'], $upPath."pics/".$fileName.$fileExt);
$first=ImageCreateFromJPEG($upPath."pics/".$fileName.$fileExt);
echo "GOT HERE";
//CREATES AND COPIES THUMBNAIL TO PATH
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);
}
make_thumb($upPath."pics/".$fileName.$fileExt, $upPath."thumb/thumbnail_".$fileName.$fileExt, 300);
//INSERT INTO DATABASE
$upImage = "INSERT INTO `images` (`url`, `thumb`, `date`, `time`, `ip`, `caption`) VALUES ('images/pics/".$fileName.$fileExt."', 'images/thumb/thumbnail_".$fileName.$fileExt."', CURDATE(), CURTIME(), '".$_SERVER['REMOTE_ADDR']."', '".$_POST['upload_Caption']."')";
$upFINAL = mysqli_query($mysql_conn, $upImage);
$_SESSION['success'] = 1;
}
}
if($_SESSION['success'] == 1) { echo("<div>SUCCESS</div>");}
?>
<style>
ul { padding: 0; margin: 0; margin-left: 4px; }
</style>
<form method="POST" enctype="multipart/form-data" action="upload.php">
<div>File</div>
<div><input type="file" name="upload_Image" size="40"></div>
<div>Caption</div>
<div><input type="text" name="upload_Caption" size="40"></div>
<div><input type="password" name="upload_Password" size="40"></div>
<div><input type="submit" name="upload_Submit" value="Upload Image"></div>
</form>
</div>

From the PHP documentation, a quote from comment 112902 on imagecreatefromjpeg says this:
imagecreatefromjpeg()
This function does not honour EXIF orientation data. Pictures that are rotated using EXIF, will show up in the original orientation after being handled by imagecreatefromjpeg().
Your thumbnails might simply be showing their original orientation. That's assuming your image viewer actually respects that flag.
Also you should probably not use imagecreatefromjpeg() if the input is not jpeg.

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>

Php multiple image upload processing error

In the form and process file below I am trying to upload 3 sizes of multiple images upload and it is uploading 3 size perfectly fine.
But it is uploading the same image on all sizes of the last image selected.
UPDATE
What i have observed that something has to be played with $src i tried below and when i do this images saved black. $src does not accept [$Kv]
foreach($_FILES['file']['tmp_name'] as $src[$Kv]) {
if($extension[$Kv]=="jpg" || $extension[$Kv]=="jpeg" ){
$uploadedfile[$Kv] = $_FILES['file']['tmp_name'][$Kv];
$src[$Kv] = imagecreatefromjpeg($uploadedfile[$Kv]);
}
list($width,$height)=getimagesize($uploadedfile[$Kv]);
////// 1st Size of Image
$newwidth=350;
$newheight=350;
$tmp[$Kv]=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp[$Kv],$src[$Kv],0,0,0,0,$newwidth,$newheight,$width,$height);
}
.
Suppose I selected 3 images to upload.
Image A
Image B
Image C
It is converting and uploading all sizes of all images (3x3) but image shows on all sizes of all images selected is the image of Image C.
Can you please help on this issue that where I am wrong?
Thanks.
form.php
<form action="process.php" method="post" enctype="multipart/form-data">
<div class="col-lg-12 col-md-9 col-sm-12" id="thumb-output">
<div class="m-dropzone dropzone m-dropzone--primary" id="m-dropzone-two">
<h3 class="m-dropzone__msg-title">
Drop files here or click to upload.
</h3>
<input id="files" class="" type="file" name="file[]" multiple>
</div>
</div>
</form>
process.php
$change="";
$abc="";
if(count($_FILES['file']['name']) > 0){
$Kv = 0;
define ("MAX_SIZE","12000");
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"][$Kv];
if ($image) {
foreach($_FILES['file']['name'] as $filename) {
$filename = stripslashes($_FILES['file']['name'][$Kv]);
$extension = getExtension($filename);
$extension = strtolower($extension);
}
foreach($_FILES['file']['size'] as $size) {
$size=filesize($_FILES['file']['tmp_name'][$Kv]);
}
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'][$Kv];
$src = imagecreatefromjpeg($uploadedfile);
}else if($extension=="png"){
$uploadedfile = $_FILES['file']['tmp_name'][$Kv];
$src = imagecreatefrompng($uploadedfile);
}else {
$src = imagecreatefromgif($uploadedfile);
}
//echo $scr;
list($width,$height)=getimagesize($uploadedfile);
////// 1st Size of Image
$newwidth=350;
$newheight=350;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
////// 2nd Size of Image
$newwidths=400;
$newheights=400;
$tmps=imagecreatetruecolor($newwidths,$newheights);
imagecopyresampled($tmps,$src,0,0,0,0,$newwidths,$newheights,$width,$height);
////// 3rd Size of Image
$newwidthsz=92;
$newheightsz=92;
$tmpsz=imagecreatetruecolor($newwidthsz,$newheightsz);
imagecopyresampled($tmpsz,$src,0,0,0,0,$newwidthsz,$newheightsz,$width,$height);
/////////////////////////////////////////////////////
foreach($_FILES['file']['name'] as $name) {
$name = $_FILES["file"]["name"][$Kv];
$ext = end((explode(".", $name))); # extra () to prevent notice
}
$folderPath = "../images/combo2_images";
if (file_exists($folderPath)){
}else{
mkdir("$folderPath");
}
//mkdir($folderPath);
if ($execute == true) {
if ($type == 'm') {
foreach($_FILES['file']['name'] as $filenames) {
$filenames = "../images/combo2_mimages/m".$idz.'_'.$Kv++.'.'.$ext;
imagejpeg($tmps,$filenames,100);
}
//$savefilenames = 'sc1_'.$id.'.'.$ext;
foreach($_FILES['file']['name'] as $filenamesz) {
$filenamesz = "../images/combo2_mimages/small/m".$idz.'_'.$Kv++.'.'.$ext;
imagejpeg($tmpsz,$filenamesz,100);
}
//$savefilenamesz = 'sc1_'.$id.'.'.$ext;
}
$filename = "../images/combo2_images/".$idz.'.'.$ext;
imagejpeg($tmp,$filename,100);
$savefilename = $idz.'.'.$ext;
if ($_FILES['file']['size'] !== 0 && $_FILES['file']['error'] == 0) {
if ($type == 'm') {
$querys = "insert into items_images
(combo_type, combo_id, item_id, filename, status)
values (2, '$idz', '$mitem', '$savefilename', '$status')
";
$executes = $dba->query($querys);
}
$queryu = "update items_combobox2
set filename = '$savefilename'
where id = '$idz'
";
$executeu = $dba->query($queryu);
imagedestroy($src);
imagedestroy($tmp); ////// 1st Size of Image
imagedestroy($tmps); ////// 2nd Size of Image
imagedestroy($tmpsz); ////// 3rd Size of Image
}
}
}
header("location: all/items/");
echo "<script>parent.document.location.href = 'all/items/';</script>";
exit();
}
}
Finally i got i working as i want.
if(count($_FILES['file']['name']) > 0){
define ("MAX_SIZE","12000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$errors=0;
$i=1; // auto increment number
$uploaddir = "../images/combo2_images"; //a directory inside
foreach ($_FILES['file']['name'] as $name => $value) {
$filename = stripslashes($_FILES['file']['name'][$name]);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
echo "\n This is the extension: ",$extension;
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
//print error message
?>
<h4>Unknown extension!</h4>
<?php
$errors=1;
} else {
$size=filesize($_FILES['file']['tmp_name'][$name]);
if ($size > MAX_SIZE*1024) {
?>
<h4>You have exceeded the size limit!</h4>
<?php
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" && $extension!=="png"){
$uploadedfile = $_FILES['file']['tmp_name'][$name];
$src = imagecreatefromjpeg($uploadedfile);
}else if($extension=="jpg" || $extension=="jpeg" && $extension=="png"){
$uploadedfile = $_FILES['file']['tmp_name'][$name];
$src = imagecreatefromjpeg($uploadedfile);
}else if($extension!=="jpg" || $extension!=="jpeg" && $extension=="png"){
$uploadedfile = $_FILES['file']['tmp_name'][$name];
$src = imagecreatefrompng($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=350;
$newheight=350;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$newwidths=400;
$newheights=400;
$tmps=imagecreatetruecolor($newwidths,$newheights);
imagecopyresampled($tmps,$src,0,0,0,0,$newwidths,$newheights,$width,$height);
$newwidthsz=92;
$newheightsz=92;
$tmpsz=imagecreatetruecolor($newwidthsz,$newheightsz);
imagecopyresampled($tmpsz,$src,0,0,0,0,$newwidthsz,$newheightsz,$width,$height);
//$image_name=($i++).$filename.'.'.$extension;
//$newname="files/".$image_name;
//$copied = copy($_FILES['file']['tmp_name'][$name], $newname);
if ($execute == true) {
if ($type == 'm') {
$filenames = "../images/combo2_mimages/m".$idz.'.'.$extension;
//imagejpeg($tmps,$filenames,100);
$copied1 = copy(imagejpeg($tmps,$filenames,100));
$filenamesz = "../images/combo2_mimages/small/m".$idz.'_'.($i++).'.'.$extension;
//imagejpeg($tmpsz,$filenamesz,100);
$copied2 = copy(imagejpeg($tmpsz,$filenamesz,100));
}
$filename = "../images/combo2_images/".$idz.'.'.$extension;
imagejpeg($tmp,$filename,100);
$savefilename=$idz.'.'.$extension;
if ($type == 'm') {
$querys="insert into items_images
(combo_type, combo_id, item_id, filename, status)
values (2, '$idz', '$mitem', '$savefilename', '$status')
";
$executes=$dba->query($querys);
}
$queryu="update items_combobox2
set filename = '$savefilename'
where id = '$idz'
";
$executeu=$dba->query($queryu);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmps);
imagedestroy($tmpsz);
}
if (!$copied) {
?>
<h4>Copy unsuccessfull!</h4>
<?php
$errors=1;
}
}
}
header("location: all/items/");
echo "<script>parent.document.location.href = 'all/items/';</script>";
exit();
}

PHP session_start blocks resizeImage() function

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!");
}
?>

Extend variable from one function to another

I'm having an image upload function I did create for few weeks ago - it has an variable called $newname, which contains the path and file.
I'm then using the imageupload() function in another function called EditFrontPage(), which is used to 'update' some content.
If I update the image, it runs the imageupload function, which is great, it resize and optimize the image, and it moves it to the folder I specified.
What I then want, is within' my EditFrontPage() function, is to echo out the $newname variable from the imageUpload function.
is there a way to do this? in a smart way? :D
Here is my code:
<?php
function EditFrontPage($db)
{
$stmt = $db->prepare("SELECT `id`, `heading`, `content`, `image` FROM `content` WHERE `page` = 'forside';");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(isset($_POST['EditFrontpageSubmit']))
{
imageUpload(10000, 100, 100, '', 5);
global $newname;
echo $newname;
}
?>
<form class="adminForm" enctype="multipart/form-data" action="" method="post">
<h2>Overskrift</h2>
<input type="text" value="<?=$row['heading']?>" />
<input type="file" name="image[]" />
<h2>Tekst</h2>
<textarea><?=br2nl($row['content'])?></textarea>
<input type="submit" name="EditFrontpageSubmit" value="Opdater nyhed" />
</form>
<?php
}
function imageUpload($maxsize = 2000, $quality = 95, $imgwidth = 400, $imgheight = '', $numOfImages = 5, $path = '/lucas/images/')
{
// Turn on error reporting
error_reporting(-1);
//Set the max upload size in kilobytes
define("MAX_SIZE", "$maxsize");
if(empty($imgheight) && empty($imgwidth))
{
echo "<h1>Fejl: Definer bredde eller højde</h1>";
die();
}
//Makes a function that check the extension
function getExtension($str){
$i = strrpos($str, ".");
if(!$i){return "";}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//Set errors to 0 from standard
$errors = 0;
//Define the size as a variable
$size = '';
//foreach image selected
foreach($_FILES['image']['error'] as $key => $error)
{
//If no errors, return true
if($error == UPLOAD_ERR_OK)
{
//Gets the filename
$filename = stripslashes($_FILES['image']['name'][$key]);
//Gets the extension
$extension = getExtension($filename);
//convert the extension to lowercase
$extension = strtolower($extension);
//if the file extension doesn't match, return error
if(($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
echo "<h1>Unknown Extension!</h1>";
$errors = 1;
}
//This check if the amount of images is over 5.
elseif(count($_FILES['image']['name']) > $numOfImages)
{
//If it's over 5 images, return error and exit
echo "Too many images";
exit();
}
else
{
//Get the filesize of the image (total amount if multiple images).
$size += filesize($_FILES['image']['tmp_name'][$key]);
//if the filesize is over the defined amount
if($size > MAX_SIZE*1024)
{
echo "<h1>Du har overskredet maksimum fil-upload størrelse!</h1>";
$errors = 1;
}
//This renames the image, to contain, the microtime, and a unique ID + extension
$image_name = microtime(true) . uniqid('',true) . '.' . $extension;
//This sets the path of the image.
$newname = $_SERVER['DOCUMENT_ROOT'] . $path . $image_name;
//It moves the file(s) to the path defined above!
$copied = move_uploaded_file($_FILES['image']['tmp_name'][$key], $newname);
//Check if the extension is png
//if($extension == "png")
//{
//converts the quality from 'jpeg/gif' quality to png compression method
//$pngquality = round($quality/100 * 9);
//Executes a shell command optimizing the png
//shell_exec("gm mogrify -quality $pngquality -thumbnail ". $imgwidth ."x". $imgheight ."\> $newname $newname");
//}
//else
//Executes a shell command optimizing the jpeg/gif
//shell_exec("gm mogrify -quality $quality -thumbnail ". $imgwidth ."x". $imgheight ."\> $newname $newname");
//If the image isn't copied, return an error
if(!$copied)
{
echo "<h1>Der skete en fejl!</h1>";
$errors = 1;
}
//Creates an array of the images
$array[] = $newname;
}
}
}
//If the submit is set, and errors = 0 return true
if(isset($_POST['Submit']) && $errors != 1)
{
echo "<h1>Fil blev uploaded som den skulle!</h1>";
//Makes a for loop, that echo's out all uploaded images
for($i = 0; $i < count($array); $i++)
{
echo "<img src='{$array[$i]}' /><p>".preg_replace("/.*\//i", '', $array[$i])."</p>";
}
}
}
?>
Thank you a lot guys!
Have the imageupload() function return the $newname variable, and then set it like so on the EditFrontPage() function:
$newName = imageUpload(10000, 100, 100, '', 5);
just return $newname at the end of imageUpload function and modify this part:
if(isset($_POST['EditFrontpageSubmit']))
{
echo imageUpload(10000, 100, 100, '', 5);
}

How to upload images to folder

Can you please help me and tell me how I can get the images to be uploaded to a certain folder using the below script.
I want the full images to be saved to imagefolder and the thumbnails to be saved to inside the imagefolder.
The code is below.
<?php
$upload_image_limit = 5; // How many images you want to upload at once?
$upload_dir = ""; // default script location, use relative or absolute path
$enable_thumbnails = 1 ; // set 0 to disable thumbnail creation
$max_image_size = 1024000 ; // max image size in bytes, default 1MB
##################### THUMBNAIL CREATER FROM GIF / JPG / PNG
function make_thumbnails($updir, $img){
$thumbnail_width = 80;
$thumbnail_height = 60;
$thumb_preword = "thumb_";
$arr_image_details = GetImageSize("$updir"."$img");
$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]==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("$updir"."$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"."$thumb_preword"."$img");
}
}
################################# UPLOAD IMAGES
foreach($_FILES as $k => $v){
$img_type = "";
### $htmo .= "$k => $v<hr />"; ### print_r($_FILES);
if( !$_FILES[$k]['error'] && preg_match("#^image/#i", $_FILES[$k]['type']) && $_FILES[$k]['size'] < $max_image_size ){
$img_type = ($_FILES[$k]['type'] == "image/jpeg") ? ".jpg" : $img_type ;
$img_type = ($_FILES[$k]['type'] == "image/gif") ? ".gif" : $img_type ;
$img_type = ($_FILES[$k]['type'] == "image/png") ? ".png" : $img_type ;
$img_rname = $_FILES[$k]['name'];
$img_path = $upload_dir.$img_rname;
copy( $_FILES[$k]['tmp_name'], $img_path );
if($enable_thumbnails) make_thumbnails($upload_dir, $img_rname);
$feedback .= "Image and thumbnail created $img_rname<br />";
}
}
############################### HTML FORM
while($i++ < $upload_image_limit){
$form_img .= '<label>Image '.$i.': </label> <input type="file" name="uplimg'.$i.'"><br />';
}
$htmo .= '
<p>'.$feedback.'</p>
<form method="post" enctype="multipart/form-data">
'.$form_img.' <br />
<input type="submit" value="Upload Images!" style="margin-left: 50px;" />
</form>
';
echo $htmo;
?>
Thank you.
the code works fine, to change to a different folder change this $upload_dir = "imagefolder";
if the code is ok, you need to change the variable $upload_dir, to a folder path with a 777 permissions (chmod) It will give permissions to the folder for the public, group and owner for execute, rewrite and read.
example
$upload_dir="./imagefolder";

Categories