<?php
$image = $_FILES['image'];
//name of new file selected
$imagename = $image['name'];
//name of file in database
$filename = $row['filename'];
//folder to move image
$TARGET_PATH = "../$university/img/users/$category/$username/";
//if imagename in DB is different to image just selected
if ($filename <> $imagename) {
// *** Include the class
include("resize-class.php");
//if the filename in DB different from filename chosen
//delete old image
unlink("../$university/img/users/$oldcategory/$username/$filename");
//create random number and add that to the beginning of new imagename
$uniqueID = uniqid();
$imagetitle = $imagename;
$fileunique = $uniqueID;
$fileunique .= $imagetitle;
$filename = $fileunique;
//upload new selected file
$oldpath = $_FILES['image']['tmp_name'];
// Lets attempt to move the file from its temporary directory to its new home
if (move_uploaded_file($oldpath, $TARGET_PATH)) {
// NOTE: This is where a lot of people make mistakes.
// We are *not* putting the image into the database; we are putting a reference to the file's location on the server
$imagename = $fileunique;
$path = "../$university/img/users/$category/$usernameid/$imagename";
// *** 1) Initialise / load image
$resizeObj = new resize($path);
if (exif_imagetype($path) == IMAGETYPE_JPEG) {
$exif = exif_read_data($path);
$ort = $exif['IFD0']['Orientation'];
switch ($ort) {
case 1: // nothing
break;
case 2: // horizontal flip
$resizeObj->flipImage($public, 1);
break;
case 3: // 180 rotate left
$resizeObj->rotateImage($public, 180);
break;
case 4: // vertical flip
$resizeObj->flipImage($public, 2);
break;
case 5: // vertical flip + 90 rotate right
$resizeObj->flipImage($public, 2);
$resizeObj->rotateImage($public, -90);
break;
case 6: // 90 rotate right
$resizeObj->rotateImage($public, -90);
break;
case 7: // horizontal flip + 90 rotate right
$resizeObj->flipImage($public, 1);
$resizeObj->rotateImage($public, -90);
break;
case 8: // 90 rotate left
$resizeObj->rotateImage($public, 90);
break;
}
}
if (($resizeObj->width > 600) || ($resizeObj->height > 600)) {
// *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
$resizeObj->resizeImage(400, 400, 'crop');
// *** 3) Save image
$resizeObj->saveImage($path, 95);
}
//change filename in database
$query = "UPDATE people SET filename=? WHERE id=? AND username=?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $filename);
$stmt->bindParam(2, $id);
$stmt->bindParam(3, $username);
$stmt->execute();
}
}
?>
I am trying to create a form where users can change an image that they have previously uploaded.
I have posted my code above, it gets as far as 'unlinking' the old image but doesn't seem to do anything after that with no errors.
I am trying to get the code to:
Check the newly selected image name against the name stored in the database
if they are different delete the old image in the folder
upload the new image with random number at the beginning of image name
update the database with the new filename
Any ideas where I'm going wrong? Thanks for your help
Here are some thoughts about code:
as suggested by Aditya use something like sprintf('%s%s', uniqid(), $imagename)
check $_FILES for any error (maybe file is too big)
you are saving image ONLY if it has width or height more then 600 px(not sure if rotating will automatically save the image)
check if you have enough rights to write into directory(maybe you need to create folders first)
Related
We have a feature that lets users upload images on a website, which can be from a desktop or taken from any cellphone. But from some phones like Iphone images taken vertically end up rotated the wrong way. We need them to be displayed correctly on any device when uploaded from any device.
I found some similar questions but their solution didn't seem to work completely. I need to either rotate them correctly in php as soon as they are uploaded:
if(isset($_FILES["submit_image"])) {
$target_dir = "uploads/images/";
$name = $_FILES['submit_image']['name'];
$size = $_FILES['submit_image']['size'];
$tmp_name = $_FILES['submit_image']['tmp_name'];
//make sure the image is roated correctly? I tried this code that I found in other SO questions but then it doesn't seem to be saving it
// START ORIENTATION FIX
$info = getimagesize($tmp_name);
$image = imagecreatefrompng($tmp_name);
if($info['mime'] == 'image/jpeg') {
$exif = exif_read_data($tmp_name);
if(isset($exif['Orientation'])) {
$orientation = $exif['Orientation'];
}
}
if(isset($orientation)) { //rotate to match the orientation
switch($orientation) {
case 3:
$image = imagerotate($image, 180, 0);
break;
case 6:
$image = imagerotate($image, -90, 0);
break;
case 8:
$image = imagerotate($image, 90, 0);
break;
}
}
if(isset($image)) { //get the variables of the rotated image
$tmp_name = $image["tmp_name"];
$name = $image['name'];
$size = $image['size'];
}
// END ORIENTATION FIX
/*doing some other checks here for image name, size, and mime type
...
*/
$path = calculate_file_path($target_dir, $name);
if (move_uploaded_file($tmp_name, $path) == true) {
$query = "UPDATE {$table} SET {$column} = '{$path}' WHERE id = {$new_pro_id}";
$result = mysqli_query($db, $query);
if ($result) {
//saved
}
else{
//failed
}
}
}
Or maybe fix them later with css whenever the site needs to display them:
.profile_img
{
image-orientation: from-image;
}
But neither seemed to work. the php option broke them completely, and the css option didn't fix the orientation.
EDIT
I get a warning/error message:
exif_read_data() expects parameter 1 to be a valid path, array given in...
But there is no file path anywhere at that point. All I have is $_FILES['submit_image'] which comes from a type="file" field in an html form. I'm sure this variable has all the information which would be in the file path because I use it later to save to the server.
Any ideas?
Thanks :)
I am using a php multiple image uploader fine - the code is below. I am trying to modify it to assign incremental image names to the batch of images eg. Image1.jpg, Image2.jpg, Image3.jpg etc rather than a random name. I have tried changing the random code to a variable but no luck. Can anyone please help.
$ThumbSquareSize = 125; //Thumbnail will be 200x200
$BigImageMaxSize = 600; //Image Maximum height or width
$ThumbPrefix = "thumb_"; //Normal thumb Prefix
$Reference_No = $_POST['Reference_No'];
$DestinationDirectory = 'properties/'.$Reference_No.'/'; //Upload Directory ends with / (slash)
$Quality = 75;
//ini_set('memory_limit', '-1'); // maximum memory!
foreach($_FILES as $file)
{
// some information about image we need later.
$ImageName = $file['name'];
$ImageSize = $file['size'];
$TempSrc = $file['tmp_name'];
$ImageType = $file['type'];
if (is_array($ImageName))
{
$c = count($ImageName);
echo '<ul>';
for ($i=0; $i < $c; $i++)
{
$processImage = true;
$RandomNumber = rand(0, 9999999999); // We need same random name for both files.
if(!isset($ImageName[$i]) || !is_uploaded_file($TempSrc[$i]))
{
echo '<div class="error">Error occurred while trying to process <strong>'.$ImageName[$i].'</strong>, may be file too big!</div>'; //output error
}
else
{
//Validate file + create image from uploaded file.
switch(strtolower($ImageType[$i]))
{
case 'image/png':
$CreatedImage = imagecreatefrompng($TempSrc[$i]);
break;
case 'image/gif':
$CreatedImage = imagecreatefromgif($TempSrc[$i]);
break;
case 'image/jpeg':
case 'image/pjpeg':
$CreatedImage = imagecreatefromjpeg($TempSrc[$i]);
break;
default:
$processImage = false; //image format is not supported!
}
//get Image Size
list($CurWidth,$CurHeight)=getimagesize($TempSrc[$i]);
//Get file extension from Image name, this will be re-added after random name
$ImageExt = substr($ImageName[$i], strrpos($ImageName[$i], '.'));
$ImageExt = str_replace('.','',$ImageExt);
//Construct a new image name (with random number added) for our new image.
$NewImageName = $RandomNumber.'.'.$ImageExt;
//Set the Destination Image path with Random Name
$thumb_DestRandImageName = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumb name
$DestRandImageName = $DestinationDirectory.$NewImageName; //Name for Big Image
//Resize image to our Specified Size by calling resizeImage function.
if($processImage && resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]))
{
//Create a square Thumbnail right after, this time we are using cropImage() function
if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]))
{
echo 'Error Creating thumbnail';
}
/*
At this point we have succesfully resized and created thumbnail image
We can render image to user's browser or store information in the database
For demo, we are going to output results on browser.
*/
//Get New Image Size
list($ResizedWidth,$ResizedHeight)=getimagesize($DestRandImageName);
$DestinationDirectory = 'properties/'.$Reference_No;
echo '<li><table width="100%" border="0" cellpadding="4" cellspacing="0">';
echo '<tr>';
echo '<td align="center"><img src="'.$DestinationDirectory.$ThumbPrefix.$NewImageName.'" alt="Thumbnail" height="'.$ThumbSquareSize.'" width="'.$ThumbSquareSize.'"></td>';
echo '</tr><tr>';
echo '<td align="center"><img src="'.$DestinationDirectory.$NewImageName.'" alt="Resized Image" height="'.$ResizedHeight.'" width="'.$ResizedWidth.'"></td>';
echo '</tr>';
echo '</table></li>';
/*
// Insert info into database table!
mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath)
VALUES ($DestRandImageName, $thumb_DestRandImageName, 'uploads/')");
*/
}else{
echo '<div class="error">Error occurred while trying to process <strong>'.$ImageName[$i].'</strong>! Please check if file is supported</div>'; //output error
}
}
}
echo '</ul>';
}
}
you have 2 options
save the number to a file and read the file next time and add to it
keep a list of files in database table and get the last files index and add to it
You already have a for loop incrementing the integer variable $i, so change this:
//Construct a new image name (with random number added) for our new image.
$NewImageName = $RandomNumber.'.'.$ImageExt;
to the following code:
//Construct a new image name (with random number added) for our new image.
$NewImageName = 'Image'.$i.'.'.$ImageExt;
I am new to php and I've downloaded a free source code for image gallery. It has admin account and you can upload image on it. Now when I upload image it generates random image title like numbers '4849404'. I want it to assign a specific title per image. How can I do that? I think here is the line for the image title if I'm not mistaken:
$RandomNumber = rand(0, 9999999999); // We need same random name for both files.
// some information about image we need later.
$ImageName = strtolower($_FILES['ImageFile']['name']);
$ImageSize = $_FILES['ImageFile']['size'];
$TempSrc = $_FILES['ImageFile']['tmp_name'];
$ImageType = $_FILES['ImageFile']['type'];
$process = true;
//Validate file + create image from uploaded file.
switch(strtolower($ImageType))
{
case 'image/png':
$CreatedImage = imagecreatefrompng($_FILES['ImageFile']['tmp_name']);
break;
case 'image/gif':
$CreatedImage = imagecreatefromgif($_FILES['ImageFile']['tmp_name']);
break;
case 'image/jpeg':
$CreatedImage = imagecreatefromjpeg($_FILES['ImageFile']['tmp_name']);
break;
default:
die('Unsupported File!'); //output error
}
//get Image Size
list($CurWidth,$CurHeight)=getimagesize($TempSrc);
//get file extension, this will be added after random name
$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.','',$ImageExt);
$BigImageMaxWidth = $CurWidth;
$BigImageMaxHeight = $CurHeight;
//Set the Destination Image path with Random Name
$thumb_DestRandImageName = $Thumb.$RandomNumber.'.'.$ImageExt; //Thumb name
$DestRandImageName = $DestinationDirectory.$RandomNumber.'.'.$ImageExt; //Name for Big Image
//Resize image to our Specified Size by calling our resizeImage function.
if(resizeImage($CurWidth,$CurHeight,$BigImageMaxWidth,$BigImageMaxHeight,$DestRandImageName,$CreatedImage))
{
//Create Thumbnail for the Image
resizeImage($CurWidth,$CurHeight,$ThumbMaxWidth,$ThumbMaxHeight,$thumb_DestRandImageName,$CreatedImage);
//respond with our images
echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">
<tr><td align="center"><img src="gallery/'.$RandomNumber.'.'.$ImageExt.'" alt="Resized Image"></td></tr></table>';
}else{
die('Resize Error'); //output error
}
}
It is adding a random number for the title on the following lines:
$DestRandImageName = $DestinationDirectory.$RandomNumber.'.'.$ImageExt;
and
$DestRandImageName = $DestinationDirectory.$RandomNumber.'.'.$ImageExt;
Were it says $RandomNumber you could add the ability to set a name here e.g. put the above code into a method and pass through a variable that sets the name or you could retrieve the existing image name from the following variable:
$ImageName
The code snippet you've posted seems to be creating and naming thumbnails, as we can notice from the comments and variable names:
//Set the Destination Image path with Random Name
$thumb_DestRandImageName = $Thumb.$RandomNumber.'.'.$ImageExt; //Thumb name
and confirmed from its usage a few lines below in:
//Create Thumbnail for the Image
resizeImage($CurWidth,$CurHeight,$ThumbMaxWidth,$ThumbMaxHeight,$thumb_DestRandImageName,$CreatedImage);
Read about the contents of $_FILES array - name, type, size, tmp_name and error to understand the details available. E.g. in the above code snippet,
$ImageName = strtolower($_FILES['ImageFile']['name']);
gets the original file name in lower case (because of strtolower) which we can use as we see fit e.g. using it as such, or after adding some random string for the primary name. Also, as you might have noticed, file extension will also have to be managed separately.
Finally, if you are looking to rename the originally uploaded files, which is possibly using move_uploaded_file, dig around the code and test in similar fashion.
$thumb_DestRandImageName = $Thumb.$RandomNumber.'.'.$ImageExt; //Thumb name
$DestRandImageName = $DestinationDirectory.$RandomNumber.'.'.$ImageExt;
this line is where you can add specific title.
$RandomNumber="title";
thanks for taking the time to read this. I have a form with 35 file input boxes as part of a CMS for my customer to upload 35 pictures of each his products. The breakdown of that is 7 pictures of the black version, 7 pictures of the blue, 7 pictures of the grey, 7 pictures of the red, and 7 pictures of the white version of each product. So that's 35 total pictures he needs to upload. Additionally, for each of those files that he uploads, a smaller "thumbnail" sized picture needs to be made. I have a file upload script that I always use that works beautifully - when there's one file to upload. I'm not sure how to apply it in this case for 35 files. Each input box has a unique name (black1, black2...black7, blue1, blue2...blue7, etc) so, technically I could repeat the upload code 35 times with the unique name of each file input box to do this, but that is obvoiusly extremely inefficient. I'm hoping someone here can help me out with a better solution.
An additional requirement is that the names of the files be stored in a database. All of the filenames of the black pictures should be put into a string, separated by commas, and stored in the blackpics column of the database. All of the filenames of the blue pictures should be put into a string, separated by commas, and stored in the bluepics columns of the database. And so on for the grey, red, and white pictures.
Here is the code that I have now to upload one file. It gets the file from input box "file", checks that it's of the right extension (an image file), checks the filesize, creates a random file name with a random number and timestamp, creates a thumbnail (448px x 298px - big thumbnail, I know), checks that the original image uploaded was of the right dimensions (873px x 581px), and if everything is okay, I end up with the big file saved in ../images/store/big/ and the thumb saved in ../images/store/small/. They both have the same filename, they're just stored in different directories. Temporary files are deleted and all that, and if there are any errors, the files are deleted. As I said, this works great for one file.
So what I need to do is modify the code so that it does all of this for input box "black1", "black2"..."black7", then saves all the filenames into a string (black1.jpg,black2.jpg,black3.jpg,black4.jpg,black5.jpg,black6.jpg,black7.jpg) which I can then store in the 'blackpics' column of the database. Same for the blue, grey, red, and white. I don't need any help with the database part. I'm thinking that I need to create a function containing the file upload script that returns the filename. Then call that function 35 times, one for each of the input boxes. But I could be wrong.
If anyone could offer me any assistance, I would greatly appreciate it. Here is the code for the upload script:
<?php
$filename = $_FILES["file"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$filesize = $_FILES["file"]["size"];
$allowed_file_types = array('.jpg','.gif','.png', '.JPG');
if (in_array($file_ext,$allowed_file_types) && ($filesize < 1024000)) {
// rename file
$rand = rand(1,100000000);
$time = time();
$newfilename = $rand . $time . $file_ext;
if (file_exists("../images/store/big/" . $newfilename)) {
// file already exists error
$err[] = "You have already uploaded this file.";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "../images/store/big/" . $newfilename);
$pathToImage = '../images/store/big/' . $newfilename;
$pathToThumb = '../images/store/small/' . $newfilename;
$last4 = substr($pathToImage, -4);
switch(strtolower($last4)) {
case '.jpeg':
$img = imagecreatefromjpeg($pathToImage);
break;
case '.jpg':
$img = imagecreatefromjpeg($pathToImage);
break;
case '.png':
$img = imagecreatefrompng($pathToImage);
break;
case '.gif':
$img = imagecreatefromgif($pathToImage);
break;
default:
exit('Unsupported type: '. $pathToImage);
}
$max_width = 448;
$max_height = 298;
// Get current dimensions
$old_width = imagesx($img);
$old_height = imagesy($img);
// Calculate the scaling we need to do to fit the image inside our frame
$scale = min($max_width/$old_width, $max_height/$old_height);
// Get the new dimensions
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
$tmp_img = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
switch(strtolower($last4)) {
case '.jpeg':
imagejpeg($tmp_img, $pathToThumb);
break;
case '.jpg':
imagejpeg($tmp_img, $pathToThumb);
break;
case '.png':
imagepng($tmp_img, $pathToThumb);
break;
case '.gif':
imagegif($tmp_img, $pathToThumb);
break;
default:
exit('Unsupported type: '. $pathToImage);
}
imagedestroy($tmp_img);
imagedestroy($img);
}
} elseif (empty($file_basename)) {
$err[] = "Select a file to upload";
} elseif ($filesize > 1024000) {
$err[] = "File size limit exceeded";
} else {
$err[] = "File type not allowed";
unlink($_FILES["file"]["tmp_name"]);
}
list($width, $height) = getimagesize("../images/store/big/$newfilename");
if ($width != "873" || $height != "581") {
$err[] = "File dimensions error";
unlink("../images/store/big/$newfilename");
unlink("../images/store/small/$newfilename");
}
?>
And in the body I have the file upload fields as so...
<input type="file" name="black1" disabled="1">
<input type="file" name="black2" disabled="1">
...
<input type="file" name="black7" disabled="1">
<input type="file" name="blue1" disabled="1">
<input type="file" name="blue2" disabled="1">
...
<input type="file" name="blue7" disabled="1">
and so on for grey, red, and white.
Like I said, if anyone can help me out, I would greatly appreciate it. And if you made it all the way down here, thanks again for taking the time to read all of this.
First don't use dimensions for images. Dimensions do not say much about the size of the image. And the size matters for displaying the image on a website, not the dimensions.
Second why not use a multipart uploading form? See here. And then your client could select the images colourwise and upload them with one selection, which would reduce the clicks from 35 to seven. Or if you trust your client to be more tech-savvy: Use only one input field and instruct him to name his files in a specific way. Like "b_[name of file].[extension]" for a black image. Then use your favourite string searching method - for example RegEx - to identify the images classes.
I had the below code that load image from DB. There are more than 600 rows of image has been inserted into the DB. I need the script that can perform these action:
Step 1) Load the image from DB
Step 2) process the image by putting the watermark
Step 3) Output the image to the browser.
I had the below code, that load and show the image. but I don't have any idea how to do the watermark.
$dbconn = #mysql_connect($mysql_server,$mysql_manager_id,$mysql_manager_pw) or exit("SERVER Unavailable");
#mysql_select_db($mysql_database,$dbconn) or exit("DB Unavailable");
$sql = "SELECT type,content FROM upload WHERE id=". $_GET["imgid"];
$result = #mysql_query($sql,$dbconn) or exit("QUERY FAILED!");
$contenttype = #mysql_result($result,0,"type");
$image = #mysql_result($result,0,"content");
header("Content-type: $contenttype");
echo $image;
mysql_close($dbconn);
?>
Please help...
You could ether learn how to manipulate images on your own from php.net or you just get a package like the one below:
http://pear.php.net/package/Image_Tools
(Tools collection of common image manipulations. Available extensions are Blend, Border, Marquee, Mask, Swap, Thumbnail and Watermark.)
How about calling your image the same way you do for the SELECT type, content?
Select the image with an imagepath from your database and then style it so it floats over your information. you could also hardcode the watermark image as it is always the same image you can have repeated. You won't see your information but if you put an opacity on the image, you can see through it:
#img.watermark {
float:left;
opacity:0.1;
z-index:1;
}
This is just one idea on how to do it, but should work quite nicely!
take a look at
imagecopymerge()
from php's graphics librabry, it should do what you're looking for.
http://www.php.net/manual/en/function.imagecopymerge.php
Finally I get the solution, here is the code:
<?php
$dbconn = #mysql_connect($mysql_server,$mysql_manager_id,$mysql_manager_pw) or exit("SERVER Unavailable");
#mysql_select_db($mysql_database,$dbconn) or exit("DB Unavailable");
$sql = "SELECT id, original_name, type, content FROM upload WHERE id=". $_GET["imgid"];
$result = #mysql_query($sql,$dbconn) or exit("QUERY FAILED!");
$fileID = #mysql_result($result,0,"id");
$contenttype = #mysql_result($result,0,"type");
$filename = #mysql_result($result,0,"original_name");
$image = #mysql_result($result,0,"content");
$fileXtension = pathinfo($filename, PATHINFO_EXTENSION);
$finalFileName = $fileID.".".$fileXtension;
// put the file on temporary folder
$filePutPath = "/your/temporary/folder/".$finalFileName;
// put the contents onto file system
file_put_contents($filePutPath, $image);
// get the watermark image
$stamp = imagecreatefrompng('../images/watermark.png');
switch($fileXtension)
{
case 'JPEG':
case 'JPG' :
case 'jpg' :
case 'jpeg':
$im = imagecreatefromjpeg($filePutPath);
break;
case 'gif' :
case 'GIF' :
$im = imagecreatefromgif($filePutPath);
break;
case 'png' :
case 'PNG' :
$im = imagecreatefromgif($filePutPath);
break;
default :
break;
}
list($width, $height) = getimagesize($filePutPath);
// set area for the watermark to be repeated
imagecreatetruecolor($width, $height);
// Set the tile (Combine the source image and the watermark image together)
imagesettile($im, $stamp);
// Make the watermark repeat the area
imagefilledrectangle($im, 0, 0, $width, $height, IMG_COLOR_TILED);
header("Content-type: $contenttype");
// free the memory
imagejpeg($im);
imagedestroy($im);
// delete the file on temporary folder
unlink($filePutPath);
mysql_close($dbconn);
?>