When i made this function:
function makeThumbnail($type, $name, $size, $tmp_name, $thumbSize) {
//make sure this directory is writable!
$path_thumbs = "uploaded_files/";
//the new width of the resized image, in pixels.
$img_thumb_width = $thumbSize; //
$extlimit = "yes"; //Limit allowed extensions? (no for all extensions allowed)
//List of allowed extensions if extlimit = yes
$limitedext = array(".gif",".jpg",".png",".jpeg",".bmp");
//the image -> variables
$file_type = $type;
$file_name = $name;
$file_size = $size;
$file_tmp = $tmp_name;
//check if you have selected a file.
echo $file_tmp."<br>";
echo $file_name."<br>";
echo $file_type."<br>";
echo $file_size."<br>";
if(!is_uploaded_file($file_tmp)){
echo "Error: Please select a file to upload!. <br>--back";
exit(); //exit the script and don't process the rest of it!
}
//check the file's extension
$ext = strrchr($file_name,'.');
$ext = strtolower($ext);
//uh-oh! the file extension is not allowed!
if (($extlimit == "yes") && (!in_array($ext,$limitedext))) {
echo "Wrong file extension. <br>--back";
exit();
}
//so, whats the file's extension?
$getExt = explode ('.', $file_name);
$file_ext = $getExt[count($getExt)-1];
//create a random file name
$rand_name = md5(time());
$rand_name= rand(0,999999999);
//the new width variable
$ThumbWidth = $img_thumb_width;
/////////////////////////////////
// CREATE THE THUMBNAIL //
////////////////////////////////
//keep image type
if($file_size){
if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
$new_img = imagecreatefromjpeg($file_tmp);
}elseif($file_type == "image/x-png" || $file_type == "image/png"){
$new_img = imagecreatefrompng($file_tmp);
}elseif($file_type == "image/gif"){
$new_img = imagecreatefromgif($file_tmp);
}
//list the width and height and keep the height ratio.
list($width, $height) = getimagesize($file_tmp);
//calculate the image ratio
$imgratio=$width/$height;
if ($imgratio>1){
$newwidth = $ThumbWidth;
$newheight = $ThumbWidth/$imgratio;
}else{
$newheight = $ThumbWidth;
$newwidth = $ThumbWidth*$imgratio;
}
//function for resize image.
if (function_exists(imagecreatetruecolor)){
$resized_img = imagecreatetruecolor($newwidth,$newheight);
}else{
die("Error: Please make sure you have GD library ver 2+");
}
//the resizing is going on here!
imagecopyresampled($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
//finally, save the image
ImageJpeg ($resized_img,"$path_thumbs/$rand_name.$file_ext", 100);
ImageDestroy ($resized_img);
ImageDestroy ($new_img);
}
//ok copy the finished file to the thumbnail directory
// move_uploaded_file ($file_tmp, "$path_big/$rand_name.$file_ext");
/*
Don't want to copy it to a separate directory?
Want to just display the image to the user?
Follow the following steps:
2. Uncomment this code:
/*
/* UNCOMMENT THIS IF YOU WANT */
echo "OK THUMB " . $thumbSize;
exit();
//*/
//and you should be set!
//success message, redirect to main page.
$msg = urlencode("$title was uploaded! Upload More?");
}
Then it stopped working, but outside a function, it works good.
As you can see i added "echo $file...." because i wanted to see if they have value, and they do have the right values.
I just get the error Error: Please select a file to upload.
This function is running after an normal upload image script(full size).
When i call the function i do:
makeThumbnail($_FILES[$fieldname]['type'], $_FILES[$fieldname]['name'], $_FILES[$fieldname]['size'], $_FILES[$fieldname]['tmp_name'], 100);
At my other file where its not in a function, theres no difference only that the variables is:
$file_type = $_FILES['file']['type'];
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
But it should work, I cant find anything wrong, but it doesnt and i keep getting that error. If i remove the is_uploaded_file function, i get a bunch of another errors.
Make sure you are not using move_uploaded_file() before calling the function.
I use timthumb to process the image into a thumbnail when it outputs it to screen, instead of when it's uploaded.
It means you only have one file and not one master size and one thumb size. TimThumb reduces the size of the file on serverside so it appears nice and smooth on the browserside. Have a look at it: TimThumb Link
Related
I have the following image upload script, that uploads an image, renames and resizes a thumbnail too. When uploading image (all JPG) some upload and display fine, yet others upload the main image fine but the thumbnail is just a black square.
Does anyone have any idea as to what the problem is?
[edit] I have added PNG to the filetypes, and it uploads correctly, however 'real' JPG files now upload the black thumbnail. I am thinking that I need to somehow check the file extension and apply imagecreatefromjpeg/imagecreatefrompng based on what is returned?
if this is the case, i am thinking an if/else statement where highlighted will do? - not sure what to check against to get the extension (jpg/png) though...
if(isset($_POST['submit'])){
// get file info
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$thumbName = $_FILES['file']['name']; //
$thumbTmpName = $_FILES['file']['tmp_name']; //
$thumbSize = $_FILES['file']['size']; //
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
//allow file types
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png'); // ADDED PNG HERE
if(in_array($fileActualExt, $allowed)){
if($fileError === 0){
if($fileSize < 1000000){
$fileNameNew = $row['item_img'].".".$fileActualExt; //code!
$fileDestination = 'images/'.$col_id.'/'.$fileNameNew; //number
move_uploaded_file($fileTmpName, $fileDestination);
// if(???){ // START POSSIBLE IF/ELSE HERE?
// create thumbnail
$src = imagecreatefromjpeg($fileDestination);
list($width, $height) = getimagesize($fileDestination);
$thumbWidth = 100;
$thumbHeight = 100;
// } else { // POSSIBLE ELSE HERE?
// ADDED THIS FOR PNG
$src = imagecreatefrompng($fileDestination);
list($width, $height) = getimagesize($fileDestination);
$thumbWidth = 100;
$thumbHeight = 100;
// } // END POSSIBLE IF/ELSE HERE?
$tmp = imagecreatetruecolor($thumbWidth,$thumbHeight);
imagecopyresampled($tmp, $src, 0,0,0,0, $thumbWidth, $thumbHeight, $width, $height);
imagejpeg($tmp, 'images/'.$col_id.'/thumbs/'.$fileNameNew.'', 100);
imagedestroy($src);
imagedestroy($tmp);
//CHECK FOR IMAGE
$checkImgQuery = $db->prepare("SELECT item_image.item_image, item_item.item_id FROM item_image JOIN item_item ON item_item.item_img = item_image.item_image WHERE item_id = :item_id");
$checkImgQuery->execute(array(':item_id' => $item_id));
$check = $checkImgQuery->rowCount();
if($check > 0){
// UPDATE
} else {
// ADD
}
} else {
$error[] = 'your file is too big';
}
} else {
$error[] = 'there was an error uploading your file';
}
} else {
$error[] = 'you cannot upload files of this type';
}
}
Since it is not always happening, this is almost certain to come from the files, as they are the only thing that changes... I'm guessing your jpeg files are either corrupted (but not enough to not display the picture, but maybe make the PHP code crash) or they simply aren't real jpegs...
Here's what I'd recommend: There is no need to force the users on only one file type while PHP alone can handle multiple, so we can check the mime type and act accordingly.
switch(mime_content_type($fileDestination){
case 'image/jpeg':
$src = imagecreatefromjpeg($fileDestination);
break;
case 'image/png':
$src = imagecreatefrompng($fileDestination);
break;
case 'image/gif':
$src = imagecreatefromgif($fileDestination);
break;
default:
$error[] = 'your file is not of a recognized type';
}
if(isset($src)){
//do what you were doing.
}
So we test the mime type and use the corresponding function. Not that I did not include everything, but that should be a good start.
If you want an easier implementation, you could use this:
$src = imagecreatefromstring(file_get_content($fileDestination));
When creating an image from a string, the type is automatically detected. This would return false if the file is not recognized.
You will want to be careful with transparency when saving from PNG to JPG... But I'll leave that part to you.
This script will load an image (jpg, gif or png) and then save a PNG local copy for caching.
I'm trying to find a way to resize the image to 300x300 before saving it as a PNG.
I tried to use the function imagecopyresampled() but the image is still not resized.
2 problems now :
The script saves a resized PNG image in the correct folder, but the image is empty (it's all black)
The first time i will load the image, i will get an error (image cannot be displayed because it contains error) but the image will still be saved as PNG in the cache folder. Second time i load the image, it will be displayed correctly (using the cached version) but it isn't resized.
Here's the full code of my page. The first part is used to cache the image, the second part is used to display the non-cached image (it reads an image from a ZIP file and output the content without extracting anything)
if (empty($_GET['display'])) {
header('Content-Type: image/png');
$imgpochette = $_GET['i'];
$ENABLE_CACHE = true;
$CACHE_TIME_HOURS = 744;
$CACHE_FILE_PATH = "pochette_album/$imgpochette.png";
if($ENABLE_CACHE && file_exists($CACHE_FILE_PATH) && (time() - filemtime($CACHE_FILE_PATH) < ($CACHE_TIME_HOURS * 60 * 60))) {
echo #file_get_contents($CACHE_FILE_PATH);
} else {
// Load the requested image
$imgdisplay = "http://www.pirate-punk.com/pochette.php?i=$imgpochette&display=1";
$image = imagecreatefromstring(file_get_contents($imgdisplay));
$width = "30";
$height = "30";
list($originalWidth, $originalHeight) = getimagesize($CACHE_FILE_PATH);
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $width, $height, $originalWidth, $originalHeight);
// Send the image
imagepng($new_image, $CACHE_FILE_PATH);
exit();
#file_put_contents($CACHE_FILE_PATH, $output);
echo $output;
}
}
if (!empty($_GET['display'])) {
function showimage($zip_file, $file_name) {
$z = new ZipArchive();
if ($z->open($zip_file) !== true) {
echo "File not found.";
return false;
}
$stat = $z->statName($file_name);
$fp = $z->getStream($file_name);
// search for a path/to/file matching file, returning the index of it
$index = $z->locateName($file_name, ZipArchive::FL_NOCASE|ZipArchive::FL_NODIR);
// get the name of the file based on the index
$full_file_name = $z->getNameIndex($index);
// now get the stream
$fp = $z->getStream($full_file_name);
if(!$fp) {
echo "Could not load image.";
return false;
}
header('Content-Type: image/jpeg');
header('Content-Length: ' . $stat['size']);
fpassthru($fp);
return true;
}
$imgsrcencoded = $_GET['i'];
$imagesrc = base64_decode($imgsrcencoded);
$explodez = explode("#",$imagesrc);
$imgg = utf8_encode($explodez[1]);
$dirnfile = $explodez[0];
$zipp = end((explode('/', $dirnfile)));
$dirr = str_replace($zipp,"",$dirnfile);
$dirr = rtrim($dirr,"/");
$imgg = rtrim($imgg);
chdir($dirr);
if (empty($_GET['debug'])) {
echo showimage($zipp,$imgg);
}
}
Get the solution for .png images
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php resizing image on upload rotates the image when i don't want it to
I have created my first ever upload code and was testing it, the image resizes and uploads fine. The only issue I have is that it rotates.
Here is the code:
$errors = array();
$message = "";
if(isset($_POST["test"])){
$name = rand(1,999999) . $_FILES["uploadfile"]["name"];
$temp_name = $_FILES["uploadfile"]["tmp_name"];
$size = $_FILES["uploadfile"]["size"];
$extension = strtolower(end(explode('.', $_FILES['uploadfile']['name'])));
$path = "testupload/" . $name;
$info = getimagesize($temp_name);
$originalwidth = $info[0];
$originalheight = $info[1];
$mime = $info["mime"];
$acceptedHeight = 750;
$acceptedWidth = 0;
$acceptedMimes = array('image/jpeg','image/png','image/gif');
$acceptedfileSize = 4102314;
$acceptedExtensions = array('jpg','jpeg','gif','png');
echo $size;
// check mimetype
if(!in_array($mime, $acceptedMimes)){$errors[] = "mime type not allowed - The file you have just uploaded was a: " . $extension . " file!";}
if(!$errors){if($size > $acceptedfileSize){$errors[] = "filesize is to big - Your file size of this file is: " . $size;}}
if(!$errors){if(!in_array($extension, $acceptedExtensions)){$errors[] = "File extension not allowed - The file you have just uploaded was a: " . $extension . " file!";}}
if(!$errors){
// create the image from the temp file.
if ($extension === 'png'){
$orig = imagecreatefrompng($temp_name);
}elseif ($extension === 'jpeg'){
$orig = imagecreatefromjpeg($temp_name);
}elseif ($extension === 'jpg'){
$orig = imagecreatefromjpeg($temp_name);
}elseif ($extension === 'gif'){
$orig = imagecreatefromgif($temp_name);
}
// work out the new dimensions.
if ($acceptedHeight === 0){
$newWidth = $acceptedWidth;
$newHeight = ($originalheight / $originalwidth) * $acceptedWidth;
}else if ($acceptedWidth === 0){
$newWidth = ($originalwidth / $originalheight) * $acceptedHeight;
$newHeight = $acceptedHeight;
}else{
$newWidth = $acceptedWidth;
$newHeight = $acceptedHeight;
}
$originalwidth = imagesx($orig);
$originalheight = imagesy($orig);
// make ssure they are valid.
if ($newWidth < 1){ $newWidth = 1; }else{ $newWidth = round($newWidth ); }
if ($newHeight < 1){ $newHeight = 1; }else{ $newHeight = round($newHeight); }
// don't bother copying the image if its alreay the right size.
if ($originalwidth!== $newWidth || $originalheight !== $newHeight){
// create a new image and copy the origional on to it at the new size.
$new = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($new, $orig, 0,0,0,0, $newWidth, $newHeight, $originalwidth, $originalheight);
}else{
// phps copy on write means this won't cause any harm.
$new = $orig;
}
// save the image.
if ($extension === 'jpeg' || $extension === 'jpg'){
imagejpeg($new, $path, 100);
}else if ($save_ext === 'gif'){
imagegif($new, $path);
}else{
imagepng($new, $path, round(9 - (100 / (100 / 9))));
}
$message = $path;
Can someone please let me know what is going on?
Check the original image is actually in the orientation you expect. I work with images all day and the majority of the time it's Windows Photo Viewer showing the image in a certain orientation (reading an orientation change in the EXIF) but if you open it up in Photoshop it's different.
I tested your code with two images: one was landscape (width > height), the other was portrait (height > width). The code works.
The problem seems to be what #Tavocado said: newer cameras have a sensor to detect the orientation of the camera when the photo was taken, and they store that info in the photo. Also, newer photo viewing software reads that info back from the photo and rotates it before displaying the image. So you all the time see the image with the right orientation (sky up, earth down). However PHP functions (and the rest of the world) don't use that information and display the image as is was taken. That means that you will have to rotate yourself portrait images.
Just load your images in the browser (drag the file on the address bar) you you will see how the image is really stored in the file, without any automatic rotation.
The problem is that the image has embedded EXIF data, probably from the device that took the photo.
Investigate whether your images have embedded rotation information, using exif_read_data, and then auto-correct the rotation with a function like this.
I have a page while is used only for print, and some of the images on there are uploaded through a script I have. It seems to always reduce the image to 72 dpi, reguardless of what I set imagejpeg() and imagepng() to for quality.
I've used my own personal script and this one on git hub
https://github.com/maxim/smart_resize_image
I was hoping for a little guidance on preserving the dpi at the original 300dpi.
Here is my own personal script
if (!empty($_FILES['image']['name'])) //checking if file upload box contains a value
{
$saveDirectory = 'pics/'; //name of folder to upload to
$tempName = $_FILES['image']['tmp_name']; //getting the temp name on server
$fileName1 = $_FILES['image']['name']; //getting file name on users computer
$count = 1;
do{
$location = $saveDirectory . $_GET['section'] . $count . $fileName1;
$count++;
}while(is_file($location));
if (move_uploaded_file($tempName, $location)) //Moves the temp file on server
{ //to directory with real name
$image = $location;
// Get new sizes
list($width, $height, $type) = getimagesize($image); //gets information about new server image
$framewidth = 932;
$frameheight = 354;
$realwidth = $width; //setting original width and height
$realheight = $height;
// Load
$file1new = imagecreatetruecolor($framewidth, $frameheight); //creates all black image with target w/h
if($type == 2){
$source = imagecreatefromjpeg($image);
imagecopyresampled($file1new, $source , 0, 0, 0, 0, $framewidth, $frameheight, $realwidth, $realheight);
}
elseif($type == 3){
$source = imagecreatefrompng($image);
imagecopyresampled($file1new, $source , 0, 0, 0, 0, $framewidth, $frameheight, $realwidth, $realheight);
}
else{
echo "Wrong file type";
}
if($type == 2){
//creates jpeg image from file1new for file1 (also retains quality)
imagejpeg($file1new, $image,100);
//frees space
imagedestroy($file1new);
}
elseif($type == 3){
//creates png image from file1new for file1 (also retains quality)
imagepng($file1new, $image,10);
//frees space
imagedestroy($file1new);
}
else{
echo "Wrong file type";
}
}
else
{
echo '<h1> There was an error while uploading the file.</h1>';
}
}
}
Edit: Even if dpi isn't the answer, as I see jpgs in specific don't retain that information. I need some way of keeping these images very clear and crisp.
If you generate image and open with a browser, the browser will reduce it to 72dpi before rendering.
If you open with gimp/phptoshop/whatever image editor , it should preserve the same dpi quality.
Though on a screen, there is no difference since your screen is 72 dpi.
Not tested on new browsers, but it was like this in netscape and first firefox versions, I assume it has not changed since.
The function posted by lorezyra (at) lorezyra (dot) com here: http://www.php.net/manual/es/function.imagejpeg.php#85712 might do the trick.
I'm working in my site which is in zen cart, actually a want to add a little functionality on it, and that is.... When I upload a image for a product I also want to create a thumbnail size of that image to be in a folder. Now I tried to search a file where the code to upload image goes on... I found a file in htdocs/admin_folder/includes/modules/new_product_preview.php
Now after getting details from user from a page htdocs/admin_folder/product.php it form post it in new_product_review.php page with a action defined in it and here the code for uploading image I've just simply added code as follows but it is not uploading the image in folder.
I've tried to echo the name of the file, so I've just put the alert for the image name parameters, I'm getting the $_FILES["products_image"]["tmp_name"] as something like, /tmp/gsnVaX.. like but
when I check $_FILES["products_image"]["name"] it gives the correct name of the file...
Why its not putting the image in temporary folder? When I put the resize code on it then it saves image in my folder with the same size which I wanted but whole image is just blank black.
Code is:
$image = "../images/thumbs/anki_".$_FILES["products_image"]["name"];
move_uploaded_file($_FILES["products_image"]["tmp_name"],$image);
and code when I'm doing this through resize is:
$control = "products_image";
$fileName = $_FILES[$control]['name'];
$uploadedfile = $_FILES[$control]['tmp_name'];
echo "<script>alert('".$fileName."');</script>";
$exts = explode(".",$fileName);
$ext = array_pop($exts);
$uploadedfile = $_FILES[$control]['name'];
$extension = $ext;
$extension = strtolower($extension);
if($extension=="jpg" || $extension=="jpeg" )
{
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
$newwidth = 140;
list($width,$height)=getimagesize($uploadedfile);
$newheight=($height/$width)*$newwidth;
$newheight = 135;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = "../images/thumbs/". $fileName;
imagejpeg($tmp,$filename,100);
imagedestroy($src);
imagedestroy($tmp);
What am I doing wrong with it?