PHP - Image Resize And Upload Issue (thumbs)
Hi guys,
Im trying to resize and create thiumbnails while uploading an image but it doesnt work, as i am new to php and i have followed other tutorials, i might have made a mistake which i dont understand. i have a table called test (find attached image) and what i need is when i upload an image, it copies the location of both image and on fly created thumb into my database i appreciate your help & please excuse me for messed up code <?php session_start(); include ("../global.php"); //welcome messaage echo "Welcome, " .$_SESSION['username']."!<p>"; $username=$_SESSION['username']; //get user id & credit limit $query=mysql_query("SELECT id FROM users"); while($row = mysql_fetch_array($query)) { $id = $row['id']; echo $id; } $credit=mysql_query("SELECT credit FROM users"); while($row = mysql_fetch_array($credit)) { $creditcheck = $row['credit']; echo "your credit is: $creditcheck"; } $reference = rand(11111111,99999999); //image1 define ("MAX_SIZE","100"); define ("WIDTH","150"); define ("HEIGHT","100"); function make_thumb($img_nameone,$filenameone,$new_w,$new_h) { $ext=getExtension($img_nameone); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) $src_imgone=imagecreatefromjpeg($img_nameone); if(!strcmp("png",$ext)) $src_imgone=imagecreatefrompng($img_nameone); $old_x=imageSX($src_imgone); $old_y=imageSY($src_imgone); $ratio1=$old_x/$new_w; $ratio2=$old_y/$new_h; if($ratio1>$ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; } $dst_imgone=ImageCreateTrueColor($thumb_w,$thumb_h); imagecopyresampled($dst_imgone,$src_imgone,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); if(!strcmp("png",$ext)) imagepng($dst_imgone,$filenameone); else imagejpeg($dst_imgone,$filenameone); imagedestroy($dst_imgone); imagedestroy($src_imgone); function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } $errors=0; if ($creditcheck<=0) Header("Location: buy-credit.php"); else if ($creditcheck>=0){ if(isset($_POST['register'])) $submit = mysql_query("INSERT INTO test (reference) VALUES ('$reference')"); { $image=$_FILES['myfileone']['nameone']; if ($image) { $filename = stripslashes($_FILES['myfileone']['nameone']); $extension = getExtension($filenameone); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } else { $size=getimagesize($_FILES['myfileone']['tmp_name']); $sizekb=filesize($_FILES['myfileone']['tmp_name']); if ($sizekb > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } $image_nameone=time().'.'.$extension; $newname="rentimages/".$image_nameone; $copied = copy($_FILES['myfileone']['tmp_name'], $newname); if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { $thumb_name='rentimages/thumbs/thumb_'.$image_name; $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} if(isset($_POST['register']) && !$errors) { $locationone="rentimages/$nameone"; $image1 = mysql_query ("UPDATE test SET image1='$newname', thumb='$thumb_name' WHERE reference='$referenceran'"); } } } ?> <html> <body> <form action='imagetests.php' method='POST' enctype='multipart/form-data'> File: <input type='file' name='myfileone'><p /> <input type='submit' name='register' value='Update'> <p /> </body> </html> Similar TutorialsHi the file file upload whenever i upload an image to main directory it saves one image into photos folder and copy another into thumbs folder but whenever i upload image to a different album (not main directory) it doesnt copy the other image to thumbs folder what i'm i doing wrong this is the line that i chose the folder... function make_locations ($locs) { $html = '<select name="locations" class="input"><option value="0">-- Main Directory --</option>'; foreach ($locs AS $key => $value) { $html .= '<option value="' .$value['album_id']. '">' .addslashes($value['album_name']). '</option>'; } $html .= '</select>'; return $html; } this is the whole code <?php /** * create a sub album directory for photos * to be stored in */ function create_album ($album_name, $sub_album = 0) { global $db; $sql = "INSERT INTO " .ALBUMS_TABLE. " ( album_name, sub_album ) VALUES ( '" .addslashes($album_name). "', " .intval($sub_album). " )"; if ($db->query($sql)) { return TRUE; } else { return FALSE; } } /** * get a list of sub albums */ function get_albums ($sub_album = 0) { global $db; $sql = "SELECT * FROM " .ALBUMS_TABLE. " WHERE sub_album = " .intval($sub_album); $db->query($sql); // initialise album storage $albums = array(); while ($row = $db->fetch()) { $albums[] = $row; } return $albums; } /** * get a list of photos within an album */ function get_photos ($album = 0) { global $db; $sql = "SELECT * FROM " .PHOTOS_TABLE. " WHERE album_id = " .intval($album). " ORDER BY photo_id ASC"; $db->query($sql); // initialise album storage $photos = array(); while ($row = $db->fetch()) { $photos[] = $row; } return $photos; } /** * get a large version of a particular photo */ function get_large ($photo, $album = 0, $next = '') { global $db, $template, $account_details; // shall we get the next / previous photo switch ($next) { case "next" : $next_sql = "AND photo_id > " .intval($photo). " ORDER BY photo_id ASC"; break; case "previous" : $next_sql = "AND photo_id < " .intval($photo). " ORDER BY photo_id DESC"; break; default : $next_sql = "AND photo_id = " .intval($photo); break; } $sql = "SELECT * FROM " .PHOTOS_TABLE. " WHERE album_id = " .intval($album). " " .$next_sql. " LIMIT 1"; $db->query($sql); if ($db->num_rows() == 0) { return ''; } else { $photo_info = $db->fetch(); // note the total directory $location = 'photos/' .$photo_info['photo_proper']; // now we need to resize list($width, $height) = getimagesize($location); if ($width < 300) { $new_width = $width; $new_height = $height; } elseif ($width > $height) { $new_width = 300; $new_height = $height * ($new_width / $width); } elseif ($width < $height) { $new_width = $width * ($new_height / $height); $new_height = 300; } // work out the next link $next = '<a href="portfolio.php?p=' .$photo_info['photo_id']. '&a=' .$photo_info['album_id']. '&next=next">Next</a>'; $previous = '<a href="portfolio.php?p=' .$photo_info['photo_id']. '&a=' .$photo_info['album_id']. '&next=previous">Previous</a>'; return '<div id="largephoto"><img src="' .$location. '" height="' .$new_height. '" width="' .$new_width. '" class="large"><br /><div id="prevnext">' .$previous. ' :: ' .$next. '</div></div>'; } } /** * get an array of locations */ function get_locations () { global $db; // initialise array $locations = array(); // select albums $sql = "SELECT album_id, album_name FROM " .ALBUMS_TABLE; $db->query($sql); while ($row = $db->fetch()) { $locations[] = $row; } return $locations; } /** * make the locations table */ function make_locations ($locs) { $html = '<select name="locations" class="input"><option value="0">-- Main Directory --</option>'; foreach ($locs AS $key => $value) { $html .= '<option value="' .$value['album_id']. '">' .addslashes($value['album_name']). '</option>'; } $html .= '</select>'; return $html; } /** * delete an album from the database * does not delete the photos in it */ function delete_albums ($album_ids) { global $db; if (sizeof($album_ids) > 0) { $sql = "DELETE FROM " .ALBUMS_TABLE. " WHERE album_id IN (" .implode(',', $album_ids). ")"; if ($db->query($sql)) { return TRUE; } } return FALSE; } /** * delete a set of photos */ function delete_photos ($photo_ids) { global $db; if (sizeof($photo_ids) > 0) { // select photo names for deletion $sql = "SELECT photo_proper FROM " .PHOTOS_TABLE. " WHERE photo_id IN (" .implode(',', $photo_ids). ")"; $db->query($sql); $unlink_ids = array(); while ($row = $db->fetch()) { $unlink_ids[] = $row['photo_proper']; } // now delete the photos if (sizeof($unlink_ids) > 0) { $sql = "DELETE FROM " .PHOTOS_TABLE. " WHERE photo_id IN (" .implode(',', $photo_ids). ")"; if ($db->query($sql)) { // remove photo from directory for ($i = 0; $i < sizeof($unlink_ids); $i++) { unlink("photos/" .$unlink_ids[$i]); unlink("photos/thumbs/" .$unlink_ids[$i]); } return TRUE; } } } return FALSE; } /** * upload a set of files */ function upload_files ($save_dir = '', $album = 0) { global $db; // check the save dir is writable if (!is_writable($save_dir)) { return FALSE; } // specify allowed file types $allowed_types = array ( 'image/jpg', 'image/jpeg', 'image/pjpeg', 'image/gif' ); // keep a list of uploaded files $uploaded = array(); // store bytes uploaded $total_bytes = 0; // go through the list of files while (list($key, $value) = each($_FILES['userfile']['name'])) { // check file has been passed if (!empty($value)) { // find extension $extension = substr($_FILES['userfile']['name'][$key], strpos($_FILES['userfile']['name'][$key],".") + 1); // time + $key for name $name = time(). "_" .$key. "." .$extension; // save url $add = $save_dir. "/" .$name; if (move_uploaded_file($_FILES['userfile']['tmp_name'][$key], $add)) { chmod($add, 0777); // add photo to database create_photo($_FILES['userfile']['name'][$key], $name, $album); } } } return TRUE; } /** * insert photo details into the database */ function create_photo ($photo_name, $key_name, $album = 0) { global $db; // get the filesize if (!$size = filesize("photos/" .$key_name)) { $size = 0; } // insert the photo in the database $sql = "INSERT INTO " .PHOTOS_TABLE. " ( photo_name, photo_date, photo_proper, photo_size, album_id ) VALUES ( '" .addslashes($photo_name). "', " .time(). ", '" .addslashes($key_name). "', " .intval($size). ", " .$album. " )"; if ($db->query($sql)) { return TRUE; } else { return FALSE; } } /** * get a complete raw copy of the directory */ function get_dir_contents ($dir) { // declare content array $contents = array(); // check gallery exists if (is_dir($dir)) { if ($handle = opendir($dir)) { while (FALSE !== ($file = readdir($handle))) { if ($file != '.' && $file != '..' && $file != 'thumbs') { if (file_exists($dir. '/thumbs/' .$file) || thumbnail($file, $dir. '/' .$file, $dir. '/thumbs')) { $contents[] = $dir. '/thumbs/' .$file; } else { $contents[] = 'no_image.gif'; } } } } } return $contents; } /** * create a thumbnail of a photo and store it * in the thumbs directory */ function thumbnail ($filename, $source_file, $destination, $new_h = 75, $new_w = 75) { if (!is_file($source_file)) { return FALSE; } // get the image details list($old_w, $old_h, $type) = getimagesize($source_file); // create source image switch($type) { case 1: $source = @imagecreatefromgif($source_file); break; case 2: $source = @imagecreatefromjpeg($source_file); break; case 3: $source = @imagecreatefrompng($source_file); break; default : return FALSE; } // work out dimensions if ($old_w < $old_h) { $thumb_w = $new_w; $thumb_h = $old_h * ($new_h / $old_w); } elseif ($old_w > $old_h) { $thumb_w = $old_w * ($new_w / $old_h); $thumb_h = $new_h; } elseif ($old_w == $old_h) { $thumb_w = $new_w; $thumb_h = $new_h; } $thumb = @imagecreatetruecolor($thumb_w, $thumb_h); // create image imagecopyresized($thumb, $source, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_w, $old_h); // check we have a proper destination if (!is_dir($destination)) { mkdir($destination, 0777); } // save image switch ($type) { case 1: case 2: imagejpeg($thumb, $destination. '/' .$filename); break; case 3: imagepng($thumb, $destination. '/' .$filename); break; } // memory saving imagedestroy($thumb); imagedestroy($source); // thumbnail created successfully return TRUE; } /** * make the table to show the directories and photos */ function make_table ($list, $type, $row = 3) { // initialize gallery html array $gallery_html = array(); // check if we have a list > 0 if ($size = sizeof($list)) { switch ($type) { case "GALLERIES" : $gallery_html[] = '<div id="galleries">'; break; case "PHOTOS" : case "RAW" : $gallery_html[] = '<div id="photos">'; break; } // loop through list for ($i = 0; $i < sizeof($list); $i++) { // shall we open a new list if ($i % $row == 0) { $gallery_html[] = '<ul>'; } // add to list switch ($type) { case "GALLERIES" : // create the delete link $delete_link = ''; if ($_SESSION['logged_in']) { $delete_link = '[ <a href="admin.php?mode=deletealbum&a=' .$list[$i]['album_id']. '">Delete</a> ]'; } $gallery_html[] = '<a href=portfolio.php?albums='.$list[$i]['album_id'].'><img src="folder.gif" class="directory"><br />' .addslashes($list[$i]['album_name']). '</a><br />' .$delete_link. '</li>'; break; case "PHOTOS" : // construct photo name $name = $list[$i]['photo_proper']; // construct location $location = "photos/"; // create thumbnail if (!file_exists($location. "/thumbs/" .$name)) { thumbnail($name, $location. "/" .$name, $location. "/thumbs/"); } // construct date $date = '<div class="date">' .date("d/m G:ia", $list[$i]['photo_date']). '</div>'; // create the delete link $delete_link = ''; if ($_SESSION['logged_in']) { $delete_link = '[ <a href="admin.php?mode=deletephoto&p=' .$list[$i]['photo_id']. '">Delete</a> ]'; } // image information list($width, $height) = getimagesize($location . $list[$i]['photo_proper']); // add to the html $gallery_html[] = '<li><a href="' .$location . $list[$i]['photo_proper']. '" rel="lightbox[racing]" title="Photos"><img src="' .$location. "/thumbs/" .$name. '" class="picture"><br />View</a><br />' .$delete_link. '</li>'; break; case "RAW" : $gallery_html[] = '<li><img src="' .$list[$i]. '" class="picture"></li>'; break; } // shall we close the list if ( ($i + 1) % $row === 0 || ($i + 1) == $size) { $gallery_html[] = '</ul>'; } } $gallery_html[] = '</div>'; } return implode('', $gallery_html); } ?> Hello, How could I resize the image to 320x480 before it is uploaded. Here is the code for the upload: Code: [Select] <?php require("connect.php"); $query = mysql_query("SELECT * FROM items ORDER BY id DESC"); if (mysql_num_rows($query) > 0) { $row = mysql_fetch_assoc($query); $id = $row['id']; $id++; echo $id."<br>"; $username = $_GET['user']; $dateofupload = date("Y-m-d"); $uploaddir = './pqimages/'.$dateofupload.'/'; $file = basename($_FILES['userfile']['name']); $uploadfile = $uploaddir.$id.".jpg"; if (move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadfile)){ echo "http://randomaydesigns.com/pqimages/{$file}"; $userid = mysql_query("SELECT * FROM users WHERE username ='$username'"); while ($row2 = mysql_fetch_assoc($userid)){ $userid = $row2['id']; $updateuserlastupload = mysql_query("UPDATE users SET lastupload='pqimages/".$dateofupload."/$id.jpg' WHERE username='$username'"); $updateuser = mysql_query("INSERT INTO items VALUES('','$userid','1','i','','','pqimages/".$dateofupload."/$id.jpg','0','a','$dateofupload')"); } } } ?>Cheers, GEORGE What I want to do is to upload an image, find out what the size is and then make the height=377, and keep with width at the same ratio. this is my upload code: Code: [Select] <?php error_reporting(0); mysql_connect("localhost","root","") or die(mysql_error()); mysql_select_db("myDB") or die(mysql_error()); $picture = $_FILES['image']['tmp_name']; $brand = $det['pro_name']; $year = $det['pro_vint']; $story = $det['pro_story']; $description = $det['pro_desc']; $why = $det['pro_why']; $intensity = $det['F12']; $body = $det['F11']; $sweet = $det['F8']; $acid = $det['F9']; $oak = $det['F10']; $lcbo = $det['lcbo_num']; $size = $det['pro_size']; $btl = $det['pro_btl']; $price = $det['pro_price']; $lto = $det['F7']; $audio = $det['wineAudio']; if(!isset($picture)) echo ""; else { $image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); $image_name = addslashes($_FILES['image']['name']); $image_size = getimagesize($_FILES['image']['tmp_name']); list($width, $height, $type, $attr) = getimagesize($_FILES['image']['tmp_name']); if($height != $width * 1.5 ){ echo "Image does not meet requirements"; }else{ if($image_size==FALSE) echo "This is not an Image"; else{ if(!$insert = mysql_query ("UPDATE `phpmy1_vincastweb_com`.`Sheet1` SET `image_name` = '".$image_name."', image='".$image."' WHERE `pro_id` ='".$id."'")) echo "Problem Uploading Image."; else{ $lastid = mysql_insert_id(); echo "Image Uploaded!<p />".$text."<p /><p /> Your Image:<p />"; $lastid = $id; echo "<img src='get_2.php?Product=$lastid' width='250' height='320' /><br />Click <a href='Agency/product3.php?Product=".$id."' target='_blank'>HERE</a> to view with Product" ; } } } } ?> right now I have it so that its at a ratio of height=3, and width=2...everything works fine but its not exactly what i want.. any ideas ? I am having a lot of trouble finding material to help me with this problem. I am using cakephp 1.2. What i want to be able to do is give users the ability to upload an avatar. For form is quite basic (takes the data and updates the corresponding record in the database) but I need to add in a file upload form object so the user can pick an image then i my code to be able to take that image and save it in multiple sizes and finally to save the image name and extension (ex: image.jpg) in to the database table. If anyone can help me with this it would be such a massive help. I am using cakephp and i need a quick simple image upload and re-size script, can any one help? I am VERY new to PHP, but I am trying to adapt code from http://www.4wordsystems.com/php_image_resize.php to work with multiple images. Can any please help? I know I need to place it in a loop of some kind, but I don't know how to write the code for that. Here is the code: HTML FORM CODE: Code: [Select] <form action="upload.php" method="post" enctype="multipart/form-data" > <input type="file" name="uploadfile"/> <input type="submit"/> </form> upload.php CODE: Code: [Select] <?php // This is the temporary file created by PHP $uploadedfile = $_FILES['uploadfile']['tmp_name']; // Create an Image from it so we can do the resize $src = imagecreatefromjpeg($uploadedfile); // Capture the original size of the uploaded image list($width,$height)=getimagesize($uploadedfile); // For our purposes, I have resized the image to be // 600 pixels wide, and maintain the original aspect // ratio. This prevents the image from being "stretched" // or "squashed". If you prefer some max width other than // 600, simply change the $newwidth variable $newwidth=600; $newheight=($height/$width)*600; $tmp=imagecreatetruecolor($newwidth,$newheight); // this line actually does the image resizing, copying from the original // image into the $tmp image imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); // now write the resized image to disk. I have assumed that you want the // resized, uploaded image file to reside in the ./images subdirectory. $filename = "images/". $_FILES['uploadfile']['name']; imagejpeg($tmp,$filename,100); // For our purposes, I have resized the image to be // 150 pixels high, and maintain the original aspect // ratio. This prevents the image from being "stretched" // or "squashed". If you prefer some max height other than // 150, simply change the $newheight variable $newheight=150; $newwidth=($width/$height)*150; $tmp=imagecreatetruecolor($newwidth,$newheight); // this line actually does the image resizing, copying from the original // image into the $tmp image imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); // now write the resized image to disk. I have assumed that you want the // resized, uploaded image file to reside in the ./images subdirectory. $filename = "images/thumb_". $_FILES['uploadfile']['name']; imagejpeg($tmp,$filename,100); imagedestroy($src); imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request // has completed. echo "Successfully Uploaded: <img src='".$filename."'>"; ?> Okay, so I found this code on-line that uploads images via a form, inserts them in to MySQL and displays the images on the page. It works great! Problem is, I spent a long time hacking this script to make it work with my site just to realize it did not re-size the image after it uploaded (dumb me). I have found other code that do this but I really do not want to start over at this point and my level of expertise with PHP are a step below what I need to figure this out. I am attaching the "original" code. If anyone knows how to add the necessary lines of code to make every image re-size (reduce) itself. I would very much appreciate it. Thanks <?php $con=mysql_connect("localhost", "root", "rootwdp")or die("cannot connect"); mysql_select_db("student",$con)or die("cannot select DB"); if(isset($_POST['upload'])) { $img=$_FILES["image"]["name"]; foreach($img as $key => $value) { $name=$_FILES["image"]["name"][$key] ; $tname=$_FILES["image"]["tmp_name"][$key]; $size=$_FILES["image"]["size"][$key]; $oext=getExtention($name); $ext=strtolower($oext); $base_name=getBaseName($name); if($ext=="jpg" || $ext=="jpeg" || $ext=="bmp" || $ext=="gif"){ if($size< 1024*1024){ if(file_exists("upload/".$name)){ move_uploaded_file($tname,"upload/".$name); $result = 1; list($width,$height)=getimagesize("upload/".$name); $qry="select id from img where `img_base_name`='$base_name' and `img_ext`='$ext'"; $res=mysql_fetch_array(mysql_query($qry)); $id=$res['id']; $qry="UPDATE img SET `img_base_name`='$base_name' ,`img_ext`='$ext' ,`img_height`='$height' ,`img_width`='$width' ,`size`='$size' ,`img_status`='Y' where id=$id"; mysql_query($qry); echo "Image '$name' updated<br />"; } else{ move_uploaded_file($tname,"upload/".$name); $result = 1; list($width,$height)=getimagesize("upload/".$name); $qry="INSERT INTO `img`(`id` ,`img_base_name` ,`img_ext` ,`img_height` ,`img_width`, `size` ,`img_status`)VALUES (NULL , '$base_name', '$ext', '$height', '$width', '$size', 'Y');"; mysql_query($qry); echo "Image '$name' uploaded<br />"; } } else{ echo "Image size excedded.<br />File size should be less than 1Mb<br />"; } } else{ echo "Invalid file extention '.$oext'<br />"; } } } function getExtention($image_name){ return substr($image_name,strrpos($image_name,'.')+1); } function getBaseName($image_name){ return substr($image_name,0,strrpos($image_name,'.')); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type="text/javascript"> function addItems() { var table1 = document.getElementById('tab1'); var newrow = document.createElement("tr"); var newcol = document.createElement("td"); var input = document.createElement("input"); input.type="file"; input.name="image[]"; newcol.appendChild(input); newrow.appendChild(newcol); table1.appendChild(newrow); } function remItems() { var table1 = document.getElementById('tab1'); var lastRow = table1.rows.length; if(lastRow>=2) table1.deleteRow(lastRow-1); } </script> <style type="text/css"> <a class="tooltip" and them url href="/http.www.anyurl.com" </a> a.tooltip:hover span{display:inline; position:absolute; border:2px solid #cccccc; background:#efefef; color:#333399;} a.tooltip span {display:none; padding:2px 3px; margin-left:8px; width:150px;} </style> </head> <body> <form method="post" action="" enctype="multipart/form-data"> <table align="center" border="0" id="tab1"> <tr> <td width="218" align="center"><input type="file" name="image[]" /></td> <td width="54" align="center"><img src="Button-Add-icon.png" alt="Add" style="cursor:pointer" onclick="addItems()" /></td> <td><img src="Button-Delete-icon.png" alt="Remove" style="cursor:pointer" onclick="remItems()" /></td> </tr> </table> <table align="center" border="0" id="tab2"> <tr><td align="center"><input type="submit" value="Upload" name="upload" /></td></tr> </table> </form> <table border="0" style="border:solid 1px #333; width:800px" align="center"><tr><td align="center"> <iframe style="display:none" name="if1" id="if1"></iframe> <? $qry="select * from img where img_status='Y' order by id"; $res=mysql_query($qry); $i=0; if(mysql_num_rows($res)){ ?> <div align="center"><ul style="width:650px; border: 0px"> <? while($fetch=mysql_fetch_array($res)){ $hratio=120/$fetch['img_height']; $wratio=120/$fetch['img_width']; $ratio=($hratio < $wratio) ? $hratio : $wratio; $hth=$fetch['img_height']*$ratio; $wth=$fetch['img_width']*$ratio; ?> <li style="width:120px; height:180px; border:0px solid #333;float:left;list-style:none outside none; padding-right:5px;"><img src="upload/<? echo $fetch['img_base_name'].'.'.$fetch['img_ext']; ?>" width="<? echo $wth; ?>" height="<? echo $hth; ?>" title="<? echo "image : ".$fetch['img_base_name'].".".$fetch['img_ext']; ?>" /><br /> <? if($i==0) $fp=fopen("fileInfo.txt",'w'); else $fp=fopen("fileInfo.txt",'a'); fwrite($fp,"Image : ".++$i ."\r\n"); fwrite($fp,"Name : ".$fetch['img_base_name'].".".$fetch['img_ext']."\r\n"); fwrite($fp,"width X height : ".$fetch['img_width']." X ".$fetch['img_height']."\r\n"); fwrite($fp,"Size : ".round($fetch['size']/1024,1)."Kb\r\n"); fwrite($fp,"____________________________________\r\n"); fclose($fp); echo $fetch['img_base_name'].".".$fetch['img_ext'].'<br />'; echo $fetch['img_width'].' X '; echo $fetch['img_height'].'<br />'; echo round($fetch['size']/1024,1) .'Kb'; ?> </li> <? }?> </ul> </div><? }?> </td></tr></table> </body> </html> I am working on an uploader and slowly getting it working, I am uploading 3 images at once, and setting arrays for each one as keys, with an increment of ++1. I am wanting to resize the image before it gets copied to the thumbnail folder. I have this code.
Everything works with it. As you see, I started on getting the file info, but after that I am totally stuck on what to do after to resize the image proportionally with a maximum width of xPX and height to match it without looking distorted. Any help would be really appreciated. Thank You. I have a working image upload script that uploads, renames the file and adds filename to the database. is it possible to include some sort of image resize code? if so can anyone point me in the right direction or better still show some example code and explain how it works etc. below is my working code: Code: [Select] <?php $rand = mt_rand(1,9999999); $member_id = $_SESSION['SESS_MEMBER_ID']; $caption = $_POST["caption"]; if(isset($_FILES['uploaded']['name'])) { $allowed_filetypes = array('.jpg','.gif','.bmp','.png','.jpeg'); $max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB) $fileName = basename($_FILES['uploaded']['name']); $errors = array(); $target = "gallery/"; $fileBaseName = substr($fileName, 0, strripos($fileName, '.')); // Get the extension from the filename. $ext = substr($fileName, strpos($fileName,'.'), strlen($fileName)-1); //$newFileName = md5($fileBaseName) . $ext; $newFileName = $target . $rand . "_" . $member_id.$ext; // Check if filename already exists if(file_exists("gallery/" . $newFileName)) { $errors[] = "The file you attempted to upload already exists, please try again."; } // Check if the filetype is allowed. if(!in_array($ext,$allowed_filetypes)) { $errors[] = "The file you attempted to upload is not allowed."; } // Now check the filesize. if(!filesize($_FILES['uploaded']['tmp_name']) > $max_filesize) { $errors[] = "The file you attempted to upload is too large."; } // Check if we can upload to the specified path. if(!is_writable($target)) { $errors[] = "You cannot upload to the specified directory, please CHMOD it to 777."; } //Here we check that no validation errors have occured. if(count($errors)==0) { //Try to upload it. if(!move_uploaded_file($_FILES['uploaded']['tmp_name'], $newFileName)) { $errors[] = "Sorry, there was a problem uploading your file."; } } //Lets INSERT database information here if(count($errors)==0) { $result = mysql_query("INSERT INTO `gallery` (`image`, `memberid`, `caption`) VALUES ('$newFileName', '$member_id', '$caption')") or die (mysql_error()); } //If no errors show confirmation message if(count($errors)==0) { echo "<div class='notification success png_bg'> <a href='#' class='close'><img src='img/cross_grey_small.png' title='Close this notification' alt='close' /></a> <div> Image has been uploaded.<br>\n </div> </div>"; //echo "The file {$fileName} has been uploaded"; echo "<br>\n"; echo "<a href='gallery.php'>Go Back</a>\n"; } else { //show error message echo "<div class='notification attention png_bg'> <a href='#' class='close'><img src='img/cross_grey_small.png' title='Close this notification' alt='close' /></a> <div> Sorry your file was not uploaded due to the following errors:<br>\n </div> </div>"; //echo "Sorry your file was not uploaded due to the following errors:<br>\n"; echo "<ul>\n"; foreach($errors as $error) { echo "<li>{$error}</li>\n"; } echo "</ul>\n"; echo "<br>\n"; echo "<a href='gallery.php'>Go Back</a>\n"; } } else { //Show the form echo "Use the following form below to add a new image to your gallery;<br /><br />\n"; echo "<form enctype='multipart/form-data' action='' method='POST'>\n"; echo "Please choose a file:<br /><input class='text' name='uploaded' type='file' /><br />\n"; echo "Image Caption:<br /><input class='text' name='caption' type='text' value='' /><br /><br />\n"; echo "<input class='Button' type='submit' value='Upload' />\n"; echo "</form>\n"; } ?> Many thanks to phpfreaks again. Hi, Im rather new to php and really unable to get the above to work. Everything works apart from the image being resized. File is uploaded, and the image name is printed into the SQL database. But i cant for the life of me get the image to go to 300x200? If you could help me i would be very grateful My code for the form processing page is attached. Ive put a few line breaks into the code as to where i think is the issue. I just cant seem to resize the image. Does the image resize need to come before the part it writes the image to the server or can this be done afterwards? Please help. P.S - Thanks in advance I have code written for image uploading, but it doesn't allow multiple images on a single upload, and doesn't re-size. Anyone willing to share a good upload script that will do the following?: -Allow multiple image uploads (10+ per submission), -Re-size images on upload, and -Rename images. Thanks Brett Warning: imagejpeg() [function.imagejpeg]: Unable to open '/Applications/XAMPP/xamppfiles/htdocs/images/category/90f9f5fb6bd92875b85a69ed2f5749cc.jpg' for writing: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/admin/library/functions.php on line 254 getting this error when i try to upload a photo using my admin section of a shopping cart. cant figure it out. any help greatly appreciated. heres my code: Code: [Select] function copyImage($srcFile, $destFile, $w, $h, $quality = 75) { $tmpSrc = pathinfo(strtolower($srcFile)); $tmpDest = pathinfo(strtolower($destFile)); $size = getimagesize($srcFile); if ($tmpDest['extension'] == "gif" || $tmpDest['extension'] == "jpg") { $destFile = substr_replace($destFile, 'jpg', -3); $dest = imagecreatetruecolor($w, $h); imageantialias($dest, TRUE); } elseif ($tmpDest['extension'] == "png") { $dest = imagecreatetruecolor($w, $h); imageantialias($dest, TRUE); } else { return false; } switch($size[2]) { case 1: //GIF $src = imagecreatefromgif($srcFile); break; case 2: //JPEG $src = imagecreatefromjpeg($srcFile); break; case 3: //PNG $src = imagecreatefrompng($srcFile); break; default: return false; break; } imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $size[0], $size[1]); switch($size[2]) { case 1: case 2: imagejpeg($dest,$destFile, $quality); break; case 3: imagepng($dest,$destFile); } return $destFile; } Hey there so I'm using the below code to upload images/files to my server via ftp. The issue I've found is that anything bigger than 200KB either stalls out and partially uploads or doesn't upload at all. I've set my php.ini file to have upload_max_filesize = 1000M and post_max_size = 1000M. And still anything bigger than 200KB won't upload right. Any help would be appreciated. I'm using php version 5.2.14 fyi. Thanks so much. ---CODE--- <?if(!isset($_POST["submit"])){?> <!-- THE FORM ACTION IS ONTO ITSELF --> <form action="index.php" method="POST" enctype="multipart/form-data"> <input name="userfile" type="file" size="40"> <input type="submit" name="submit" value="Upload image" /> </form> <? } else { set_time_limit(30000);//i noticed that this had to be pretty big otherwise your upload was likely to stall out. $paths='/yourfilepath/yourfilepath/'; $filep=$_FILES['userfile']['tmp_name']; $ftp_server='ftp.yourdomain.com'; $ftp_user_name='your_user_name'; $ftp_user_pass='your_password'; $name=$_FILES['userfile']['name']; $conn_id = ftp_connect($ftp_server); $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); if ((!$conn_id) || (!$login_result)) { echo "FTP connection has encountered an error!"; echo "Attempted to connect to $ftp_server for user $ftp_user_name...."; exit; } else { echo ""; } $upload = ftp_put($conn_id, $paths.'/'.$name, $filep, FTP_BINARY); if (!$upload) { echo "FTP upload has encountered an error!"; } else { echo "Uploaded file with name $name Succsessfully "; } ftp_close($conn_id); } ?> Hi Guys Probably a simple answer here that i'm missing. I've got a simple upload script for an image uploader that does various checks for security sake. One of the checks is on file size to make sure it doesn't exceed the upload limit set in php.ini . The limit is set at 2mb, so the script checks that the file doesn't exceed this limit. The problem occurs when I try to upload a file that far exceeds the limit (the one below is 3.5mb). When i do this the upload gets passed my script because the $_FILES['picture1']['size'] gets set to no value. A print_r of the files array shows: Code: [Select] [picture1] => Array ( [name] => DSC01468.JPG [type] => [tmp_name] => [error] => 1 [size] => 0 ) So what i wanted to know was whether this was normal? And should i simply do a check to see if the size value is empty? Any advice would be good! Thanks Drongo When i use the following script to upload and resize an image, it throws out errors (see after script) <?php $image = $_FILES['image']['name']; $uploaddir = "./images/$gender/"; $pext = getExtension($image); $pext = strtolower($pext); if (($pext != "jpg") && ($pext != "jpeg") && ($pext != "gif")) { print "<h1>ERROR</h1>Image Extension Unknown.<br>"; print "<p>Please upload only an image with the extension .jpg or .jpeg or .gif ONLY<br><br>"; print "The file you uploaded had the following extension: $pext</p>\n"; unlink($imgfile); exit(); } $imgsize = GetImageSize($image); /*== check size 0=width, 1=height ==*/ if (($imgsize[0] > 460) || ($imgsize[1] > 345)) { $tmpimg = tempnam("/tmp", "MKUP"); system("djpeg $image >$tmpimg"); system("pnmscale -xy 250 200 $tmpimg | cjpeg -smoo 10 -qual 50 >$imgfile"); unlink($tmpimg); } $rand = rand(0,9999999); $date = DATE("d.m.y"); $image_name=$date.$id.$rand.'.'.$extension; $final_filename = str_replace(" ", "_", $image_name); $newfile = $uploaddir . "/$final_filename"; if (is_uploaded_file($image)) { if (!copy($imgfile,"$newfile")) { print "Error Uploading File."; exit(); } } unlink($image); print("<img src=\"$newfile\">"); ?> errors: Quote Warning: getimagesize((R)Photo-0027.jpg) [function.getimagesize]: failed to open stream: No such file or directory in /home/bumwarsc/public_html/images.php on line 77 Warning: unlink((R)Photo-0027.jpg) [function.unlink]: No such file or directory in /home/bumwarsc/public_html/images.php on line 126 Hi! I'm looking for a script that can do the following: upload one or preferably fx. five image files(jpg) resizes them to a specific size if they exceeds that size. create a thumbnail No files above 100kb can be uploaded. uploaded and/or processed files must be renamed with a unique file name. Work with php5 I have searched the internet for a script like that, but I can't find one that matches my needs. Also, the code must include good comments and nott be to hard to understand. So as basic code as possible. Alright guys, i have been looking for a simple script for this online to try get my head around it. I need a script thats is going to take an image and save the orginal file along with two modified files (small and medium thumbnail). I really cant get my head around the ones i have already seen so i was wondering if anyone had any advice or a link they can post me to that can help me. I want to reduce a picture size from 600px * 500px to 60px * 50px size, then crop it become 50px *50px. I have two groups of codes, 1 is to reduce the size of image, other 1 is to crop the image. The problem is they works separately, how to combine this two groups of codes to make them work together? Below is my codes : Code: [Select] <?php //codes of group A - Reduce the size of image from 600px * 500px to 60px * 50px $save2 = "images/users/" . $image_name_2; //This is the new file you saving list($width2, $height2) = getimagesize($file) ; $modwidth2 = 50; $diff2 = $width2 / $modwidth2; $modheight2 = $height2 / $diff2; $tn2 = imagecreatetruecolor($modwidth2, $modheight2) ; $image2 = imagecreatefromjpeg($file) ; imagecopyresampled($tn2, $image2, 0, 0, 0, 0, $modwidth2, $modheight2, $width2, $height2) ; imagejpeg($tn2, $save2, 100) ; //codes of group B - Crop the image from 60px * 50px to 50px * 50px $save3 = "images/users/" . $image_name_3; list($width3, $height3) = getimagesize($file) ; $modwidth3 = 60; $diff3 = $width3 / $modwidth3; $modheight3 = $height3 / $diff3; $left = 0; $top = 0; $cropwidth = 50; //thumb size $cropheight = 50; $tn3 = imagecreatetruecolor($cropwidth, $cropheight) ; $image3 = imagecreatefromjpeg($file) ; imagecopyresampled($tn3, $image3, 0, 0, $left, $top, $cropwidth, $cropheight, $modwidth3, $modheight3) ; imagejpeg($tn3, $save3, 100) ; //save the cropped image ?> As you can see from 2 groups of codes above, 1st group resize the pic then save it to a folder. 2nd group of codes crop the pic then save it into the folder too. My question is ... After 1st group of codes resize the picture, is it necessary to save it into folder before I can crop it? If it is necessary, then I need to write new lines of codes to retrieve the resized pic from the folder for 2nd group of codes to crop it? If it is not necessary, after resizing the pic, how do I pass the pic to 2nd group of codes to crop it? php image-resizing hello I want download a file from another website and resize it to new size then reduce quality to 60% and save in on my host. this is my code about download and reduce quality. //images address $images1 = textbetween('<a href="','"',$text0); //save images $im = imagecreatefromjpeg($images1); // original image //reduce image quality imagejpeg($im, "/public_html/static/images/book/".$imagename.".jpg" , 60); // save to new image, third value is quality (0-100) if not specified its the default (75) can anyone help me to resize it? thank you |