PHP - Resizing And Uploading An Image
Hi all,
I have been trying to create a thumbnail but have realised I can just resize the image instead. I have been trying to do this and have made the code below however do not know what else I need to do to upload the new image. Could someone help? Thanks <?php $filename = $_FILES['image']; $reg = "G-ZZZZ"; $width = 200; $height = 200; list($width_orig, $height_orig) = getimagesize($filename); $ratio_orig = $width_orig/$height_orig; if ($width/$height > $ratio_orig) { $width = $height*$ratio_orig; } else { $height = $width/$ratio_orig; } $destination='aircraft/'.$reg."1.jpg"; $temp_file = $_FILES['image']['tmp_name']; move_uploaded_file($temp_file,$destination); ?> Similar TutorialsI've got a submission form for users to upload an image. Once uploaded, I want to resize the image twice: one full size and one thumbnail size. I've attached the current PHP I'm using. Currently, both images are being outputted.. the large one is resized and saved properly but the thumbnail is only displaying the black image placeholder and not the image. I've been working around the idea that the problem is around the thumbnail having trouble pulling the file's temporary location AFTER the full size pulls it. Any help? $fname = strtolower($_FILES['subimg']['name']); // grab uploaded image's filename and lowercase the extension (ex: .JPG) // verify that image uploaded is proper extension if(preg_match('/[.](jpg)|(gif)|(png)$/', $fname)) { // set image variables $path_image = '../submissions/'; $final_width_of_image = 600; $randomappend=rand(0000,9999); // generate random number to append to filename $src = $_FILES['subimg']['tmp_name']; // grab the src for where the image is temporarily held $filesub = $randomappend . $fname; // initiate new file name for submission's full image $target = $path_image . $filesub; // set variable for submission image's new location with appended name $path_image_thumb = '../submissions/thumbs/'; $final_width_of_thumb = 250; $final_height_of_thumb = 180; $filethumb = $randomappend . $fname; // initiate new file name for submission's thumbnail $target_thumb = $path_image_thumb . $filethumb; // set variable for thumbnail's new location with appended name move_uploaded_file($src, $target); // RESIZE TO FIT NEWS COLUMN WIDTH // CHECK FILE EXTENSION if(preg_match('/[.](jpg)$/', $filesub)){ $img = imagecreatefromjpeg($path_image . $filesub); } else if (preg_match('/[.](gif)$/', $filesub)){ $img = imagecreatefromgif($path_image . $filesub); } else if (preg_match('/[.](png)$/', $filesub)){ $img = imagecreatefrompng($path_image . $filesub); } // FIND UPLOADED FILE'S ORIGINAL DIMENSIONS $ox = imagesx($img); $oy = imagesy($img); // SET NEW DIMENSIONS FOR SUBMISSION IMAGE $sx = $final_width_of_image; $sy = floor($oy * ($final_width_of_image / $ox)); $sm = imagecreatetruecolor($sx, $sy); imagecopyresampled($sm, $img, 0,0,0,0,$sx,$sy,$ox,$oy); if(!file_exists($path_image)){ if(!mkdir($path_image)){ die("There was a problem."); } } imagejpeg($sm, $path_image . $filesub, 80); $sub .= '<br /><img src="' . $path_image . $filesub . '" alt="submission image">'; $sub .= '<br />Submission was successfuly created!<br />'; echo $sub; move_uploaded_file($src, $target_thumb); if(preg_match('/[.](jpg)$/', $filethumb)){ $img2 = imagecreatefromjpeg($path_image_thumb . $filethumb); } else if (preg_match('/[.](gif)$/', $filethumb)){ $img2 = imagecreatefromgif($path_image_thumb . $filethumb); } else if (preg_match('/[.](png)$/', $filethumb)){ $img2 = imagecreatefrompng($path_image_thumb . $filethumb); } $tox = imagesx($img2); $toy = imagesy($img2); // SET NEW DIMENSIONS FOR THUMBNAIL $tx = $final_width_of_thumb; $ty = $final_height_of_thumb; $tm = imagecreatetruecolor($tx, $ty); imagecopyresampled($tm, $img2, 0,0,0,0,$tx,$ty,$tox,$toy); if(!file_exists($path_image_thumb)){ if(!mkdir($path_image_thumb)){ die("There was a problem."); } } imagejpeg($tm, $path_image_thumb . $filethumb, 80); $tn .= '<br /><img src="' . $path_image_thumb . $filethumb . '" alt="thumbnail image">'; $tn .= '<br />Thumbnail was successfuly created!<br />'; echo $tn; I am trying to upload files to a user profile system. here is the profile page Code: [Select] <?php include('core/init.inc.php'); if (isset($_POST['email'], $_POST['location'], $_POST['about'])) { $errors = array(); if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) { $errors[] = "The email address you entered is not valid"; } if(preg_match('#^[a-z0-9 ]+$#i',$_POST['location'])===0) { $errors[] = 'Your location must only contain A-Z 0-9 and spaces.'; } if (empty($_FILES['avatar']['tmp_name']) === false) { $file_ext = end(explode('.', $_FILES['avatar']['name'])); if(in_array(strtolower($file_ext), array('jpg', 'jpeg', 'gif', 'png')) === false) { $errors[] = 'Your avatar must be an image.'; } } if(empty($errors)) { print_r($_FILES); set_profile_info($_POST['email'],$_POST['location'],$_POST['about'], (empty($_FILES['avatar']['tmp_name'])) ? false : $_FILES['avatar']['tmp_name']); } $userinfo = array( 'email' => htmlentities($_POST['email']), 'location' => htmlentities($_POST['location']), 'about' => htmlentities($_POST['about']) ); } else { $userinfo = fetch_user_info($_SESSION['uid']); } ?> <!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>Edit your Profile</title> </head> <body> <div> <?php if(isset($errors) == false) { echo 'Click update to edit your profile.'; } else if(empty($errors)) { echo 'Your profile has been updated.'; } else { echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>'; } ?> </div> <form action="" method="post" enctype="multipart/form-data"> <div> <label for="email">Email: </label> <input type="text" name="email" id="email" value="<?php echo $userinfo['email']; ?>" /> </div> <div> <label for="location">Location: </label> <input type="text" name="location" id="location" value="<?php echo $userinfo['location']; ?>" /> </div> <div> <label for="about">About Me: </label> <textarea name="about" id="about" rows="14" cols="50"><?php echo strip_tags($userinfo['about']); ?></textarea> </div> <div> <label for="avatar">Avatar: </label> <input type="file" name="avatar" id="avatar"/> </div> <div> <input type="submit" value="Update" /> </div> </form> </body> </html> here is the function taken from an external file Code: [Select] function set_profile_info($email, $location,$about,$avatar) { $email = mysql_escape_string(htmlentities($email)); $about = mysql_escape_string(nl2br(htmlentities($about))); $location = mysql_escape_string($location); if (file_exists($avatar)) { $src_size = getimagesize($avatar); if ($src_size['mime'] === 'image/jpeg') { $src_img = imagecreatefromjpeg($avatar); } else if ($src_size['mime'] === 'image/png') { $src_img = imagecreatefrompng($avatar); } else if ($src_size['mime'] === 'image/gif') { $src_img = imagecreatefromgif($avatar); } else { $src_img = false; } if ($src_img !== false) { $thumb_width= 200; if($src_size[0] <= $thumb_width) { $thumb = $src_img; } else { $new_size[0] = $thumb_width; $new_size[1] = ($src_size[1] / $src_size[0]) * $thumb_width; $thumb = imagecreatetruecolor($new_size[0], $new_size[1]); imagecopyresampled($thumb, $src_img, 0, 0, 0, 0, $new_size[0], $new_size[1], $src_size[0], $src_size[1]); } imagejpeg($thumb, "{$GLOBALS['path']}/user_avatars/{$_SESSION['uid']}.jpg"); } } $sql = "UPDATE `users` SET `user_email` = '{$email}', `user_about` = '{$about}', `user_location` = '{$location}' WHERE `user_id` = {$_SESSION['uid']}"; mysql_query($sql); } Below I have returned the array of files to check if its been uploaded correctly. Array ( [avatar] => Array ( [name] => Sonic.jpg [type] => image/jpeg [tmp_name] => /var/tmp/php.waq8n [error] => 0 [size] => 48477 ) ) But I get this error message. Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: '/var/tmp/php.waq8n' is not a valid JPEG file in /web/stud/u0963643/userprofilesection/finaluserprofile/core/inc/user.inc.php on line 71 If someone could point out where in this code I have made an error I would be very grateful Thanks Jamie Can I get some help or a point in the right direction.
I am trying to create a form that allows me to add, edit and delete records from a database.
I can add, edit and delete if I dont include the image upload code.
If I include the upload code I cant edit records without having to upload the the same image to make the record save to the database.
So I can tell I have got the code processing in the wrong way, thing is I cant seem to see or grasp the flow of this, to make the corrections I need it work.
Any help would be great!
Here is the form add.php code
<?php require_once ("dbconnection.php"); $id=""; $venue_name=""; $address=""; $city=""; $post_code=""; $country_code=""; $url=""; $email=""; $description=""; $img_url=""; $tags=""; if(isset($_GET['id'])){ $id = $_GET['id']; $sqlLoader="Select from venue where id=?"; $resLoader=$db->prepare($sqlLoader); $resLoader->execute(array($id)); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Add Venue Page</title> <link href='http://fonts.googleapis.com/css?family=Droid+Sans' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <?php $sqladd="Select * from venue where id=?"; $resadd=$db->prepare($sqladd); $resadd->execute(array($id)); while($rowadd = $resadd->fetch(PDO::FETCH_ASSOC)){ $v_id=$rowadd['id']; $venue_name=$rowadd['venue_name']; $address=$rowadd['address']; $city=$rowadd['city']; $post_code=$rowadd['post_code']; $country_code=$rowadd['country_code']; $url=$rowadd['url']; $email=$rowadd['email']; $description=$rowadd['description']; $img_url=$rowadd['img_url']; $tags=$rowadd['tags']; } ?> <h1 class="edit-venue-title">Add Venue:</h1> <form role="form" enctype="multipart/form-data" method="post" name="formVenue" action="save.php"> <input type="hidden" name="id" value="<?php echo $id; ?>"/> <div class="form-group"> <input class="form-control" type="hidden" name="id" value="<?php echo $id; ?>"/> <p><strong>ID:</strong> <?php echo $id; ?></p> <strong>Venue Name: *</strong> <input class="form-control" type="text" name="venue_name" value="<?php echo $venue_name; ?>"/><br/> <br/> <strong>Address: *</strong> <input class="form-control" type="text" name="address" value="<?php echo $address; ?>"/><br/> <br/> <strong>City: *</strong> <input class="form-control" type="text" name="city" value="<?php echo $city; ?>"/><br/> <br/> <strong>Post Code: *</strong> <input class="form-control" type="text" name="post_code" value="<?php echo $post_code; ?>"/><br/> <br/> <strong>Country Code: *</strong> <input class="form-control" type="text" name="country_code" value="<?php echo $country_code; ?>"/><br/> <br/> <strong>URL: *</strong> <input class="form-control" type="text" name="url" value="<?php echo $url; ?>"/><br/> <br/> <strong>Email: *</strong> <input class="form-control" type="email" name="email" value="<?php echo $email; ?>"/><br/> <br/> <strong>Description: *</strong> <textarea class="form-control" type="text" name="description" rows ="7" value=""><?php echo $description; ?></textarea><br/> <br/> <strong>Image Upload: *</strong> <input class="form-control" type="file" name="image" value="<?php echo $img_url; ?>"/> <small>File sizes 300kb's and below 500px height and width.<br/><strong>Image is required or data will not save.</strong></small> <br/><br/> <strong>Tags: *</strong> <input class="form-control" type="text" name="tags" value="<?php echo $tags; ?>"/><small>comma seperated vales only, e.g. soul,hip-hop,reggae</small><br/> <br/> <p>* Required</p> <br/> <input class="btn btn-primary" type="submit" name="submit" value="Save"> </div> </form> </div> </body> </html>Here is the save.php code <?php error_reporting(E_ALL); ini_set("display_errors", 1); include ("dbconnection.php"); $venue_name=$_POST['venue_name']; $address=$_POST['address']; $city=$_POST['city']; $post_code=$_POST['post_code']; $country_code=$_POST['country_code']; $url=$_POST['url']; $email=$_POST['email']; $description=$_POST['description']; $tags=$_POST['tags']; $id=$_POST['id']; if(is_uploaded_file($_FILES['image']['tmp_name'])){ $folder = "images/hs-venues/"; $file = basename( $_FILES['image']['name']); $full_path = $folder.$file; if(move_uploaded_file($_FILES['image']['tmp_name'], $full_path)) { //echo "succesful upload, we have an image!"; var_dump($_POST); if($id==null){ $sql="INSERT INTO venue(venue_name,address,city,post_code,country_code,url,email,description,img_url,tags)values(:venue_name,:address,:city,:post_code,:country_code,:url,:email,:description,:img_url,:tags)"; $qry=$db->prepare($sql); $qry->execute(array(':venue_name'=>$venue_name,':address'=>$address,':city'=>$city,':post_code'=>$post_code,':country_code'=>$country_code,':url'=>$url,':email'=>$email,':description'=>$description,':img_url'=>$full_path,':tags'=>$tags)); }else{ $sql="UPDATE venue SET venue_name=?, address=?, city=?, post_code=?, country_code=?, url=?, email=?, description=?, img_url=?, tags=? where id=?"; $qry=$db->prepare($sql); $qry->execute(array($venue_name, $address, $city, $post_code, $country_code, $url, $email, $description, $full_path, $tags, $id)); } if($success){ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Saved!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Saved!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } } //if uploaded else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Upload Recieved but Processed Failed!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } } //move uploaded else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Updated.')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } ?>Thanks in advance! Edited by hankmoody, 12 August 2014 - 05:15 PM. Hey guys, I am making a quotes siggy, code: <?php /** * @author Jragon * @copyright 2010 */ $textfile = "quotes.txt"; $quotes = array(); if (file_exists($textfile)) { $quotes = explode("\n", file_get_contents($textfile)); srand((float)microtime() * 10000000); $string = $quotes[array_rand($quotes)]; $string = wordwrap($string, 100, "\n", true); text_to_image($string, 800); } else { $string = "Sig file non-existant..."; } function text_to_image($text, $image_width, $colour = array(0, 244, 34), $background = array(0, 0, 0)) { $font = 5; $line_height = 15; $padding = 2; $text = wordwrap($text, ($image_width/10)); $lines = explode("\n", $text); $image = imagecreate($image_width, ((count($lines) * $line_height)) + ($padding * 2)); $background = imagecolorallocate($image, $background[48], $background[44], $background[44]); $colour = imagecolorallocate($image, $colour[0], $colour[1], $colour[2]); imagefill($image, 0, 0, $background); $i = $padding; foreach ($lines as $line) { imagestring($image, $font, $padding, $i, trim($line), $colour); $i += $line_height; } header("Content-type: image/jpeg"); imagejpeg($image); imagedestroy($image); exit; } ?> What i want it to do is have the lines the same legnth, and when a quote is smaller the image to shrink. Thanks jragon Hello, Does anyone have any knowledge of resizing an image in PHP keeping contraints on the dimensions? If not, any tutorial websites any knows? George. Having a nightmare here lol $img->set_size(225); That is resizing the image with a maximum width but i need to resize it to make it have a maximum height but can't figure out how to do it Here's my full code if you want to see it: Code: [Select] <?php include("class.imaging.php"); // The file $dir = "upload/"; $file = $newfile; $filename = $dir . $file; $img = new imaging; $img->set_img($filename); $img->set_quality(120); // Profile Picture $img->set_size(225); $img->save_img("upload/thumb/" . $file); $img->clear_cache(); ?> i have a script that uses simple file function to upload images.. is der a way i can sumhow select multiple files and use them to upload.. or is there a way i can resize or reduced the size of the image as its being uploaded.. if yes please guide me through! i use simple form to upload the file and use the following file to upload move_uploaded_file($_FILES['img']['tmp_name'], "images/albums/{$_FILES['img']['name']}"); Hello: I have a photo uploader in my admin area. First time I tried this so it's new to me. The upload form sends it to the page below, and does the resizing and saving. It seems to automatically resize the photos to make thumbnails, which is really nice. However, I am trying to do 2 things and can't figure it out. 1 - I would like to resize the main photo and not the thumbnail (or just use the thumbnail as the main photo, whichever seems easier). I would like it to be 690px wide but let it scale in proportion to what the height should be (not set a height as I think that's what it is doing now). This is the area where it gets resized: Code: [Select] { $thumbnail_width = 690; $thumbnail_height = (int)(100 * $size[1] / $size[0]); } else { $thumbnail_width = (int)(690 * $size[0] / $size[1]); $thumbnail_height = 100; } Also, the thumbnails are coming out very dark and de-colored. How can I set it so it retains all the color and clarity, but just resizes them? Point I'm trying to do is just resize upon upload, as most of my clients do not and will not resize photos before uploading them, and that means each photo from a digital camera will be about 1.3 MBs, which starts to make a photo gallery page very heavy and clunky. This is the full code, if it will help: Code: [Select] <?php // initialization $result_final = ""; $counter = 0; // List of our known photo types $known_photo_types = array( 'image/pjpeg' => 'jpg', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/bmp' => 'bmp', 'image/x-png' => 'png' ); // GD Function List $gd_function_suffix = array( 'image/pjpeg' => 'JPEG', 'image/jpeg' => 'JPEG', 'image/gif' => 'GIF', 'image/bmp' => 'WBMP', 'image/x-png' => 'PNG' ); // Fetch the photo array sent by preupload.php $photos_uploaded = $_FILES['photo_filename']; // Fetch the photo caption array $photo_caption = $_POST['photo_caption']; while( $counter <= count($photos_uploaded) ) { if($photos_uploaded['size'][$counter] > 0) { if(!array_key_exists($photos_uploaded['type'][$counter], $known_photo_types)) { $result_final .= "File ".($counter+1)." is not a photo<br />"; } else { mysql_query( "INSERT INTO gallery_photos(`photo_filename`, `photo_caption`, `photo_category`) VALUES('0', '".addslashes($photo_caption[$counter])."', '".addslashes($_POST['category'])."')" ); $new_id = mysql_insert_id(); $filetype = $photos_uploaded['type'][$counter]; $extention = $known_photo_types[$filetype]; $filename = $new_id.".".$extention; mysql_query( "UPDATE gallery_photos SET photo_filename='".addslashes($filename)."' WHERE photo_id='".addslashes($new_id)."'" ); // Store the orignal file copy($photos_uploaded['tmp_name'][$counter], $images_dir."/".$filename); // Let's get the Thumbnail size $size = GetImageSize( $images_dir."/".$filename ); if($size[0] > $size[1]) //{ //$thumbnail_width = 100; //$thumbnail_height = (int)(100 * $size[1] / $size[0]); //} //else //{ //$thumbnail_width = (int)(100 * $size[0] / $size[1]); //$thumbnail_height = 100; //} { $thumbnail_width = 690; $thumbnail_height = (int)(500 * $size[1] / $size[0]); } else { $thumbnail_width = (int)(690 * $size[0] / $size[1]); $thumbnail_height = 500; } // Build Thumbnail with GD 1.x.x, you can use the other described methods too $function_suffix = $gd_function_suffix[$filetype]; $function_to_read = "ImageCreateFrom".$function_suffix; $function_to_write = "Image".$function_suffix; // Read the source file $source_handle = $function_to_read ( $images_dir."/".$filename ); if($source_handle) { // Let's create an blank image for the thumbnail $destination_handle = ImageCreate ( $thumbnail_width, $thumbnail_height ); // Now we resize it ImageCopyResized( $destination_handle, $source_handle, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $size[0], $size[1] ); } // Let's save the thumbnail $function_to_write( $destination_handle, $images_dir."/tb_".$filename ); ImageDestroy($destination_handle ); // $result_final .= "<img src='".$images_dir. "/tb_".$filename."' style='margin-right: 20px;' />"; } } $counter++; } // Print Result echo <<<__HTML_END $result_final __HTML_END; ?> Anyone know how to fix this? Thanks. Hi all I am trying to write a piece of code that will resize and image to fit in a canvas 300 by 300 pixels and centre horizontally and vertically. Here's my code: Code: [Select] $imagelarge = $_FILES['image']['tmp_name']; $imagelargemain = $_FILES['image']['name']; $src = imagecreatefromjpeg($imagelarge); list($width,$height)=getimagesize($imagelarge); $newwidth=300; $newheight=($height/$width)*$newwidth; $center_x = 300/300; $center_y = (300/2)-($newheight/2); $tmp=imagecreatetruecolor(300,300); $white = imagecolorallocate($tmp, 255, 255, 255); imagefill($tmp, 0, 0, $white); imagecopyresampled($tmp,$src,$center_x,$center_y,0,0,$newwidth,$newheight,$width,$height); This works ok but if the user uploads a very thin and tall image it only shows the middle? Please help! Many thanks Pete As a point of curiosity, I am seeking some clarification. I have developed code to resize an image, thus reducing the file size by a percentage of it's original. My first question is, what exactly is being done to the file? I understand that some data is being removed (or condenced) but how does this effect the image when compared with the original on a webpage? Next, what should my expectation be if I wanted to reverse the process? If I am 'shrinking' an image for a faster upload speed and reduced storage capacity, how successful will I be if I wanted to 'restore' the file size before printing a physical photograph? Will this provide a 'better' end result?
Hey everyone. I have been trying to make a script that allows me to resize an image but I am having some trouble. I have got a script that takes an image and resize's it: Code: [Select] <?php $save = $_REQUEST['SavedAs'] ; $file = $_REQUEST['ImgAdd'] ; echo "Creating file: $save"; $size = 0.45; header('Content-type: image/jpeg') ; list($width, $height) = getimagesize($file) ; $modwidth = 240; $modheight = 180; $tn = imagecreatetruecolor($modwidth, $modheight) ; $image = imagecreatefromjpeg($file) ; imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ; imagejpeg($tn, $save, 100) ; header ("Location: $save"); ?> But depending on the image, the aspect ratio looks wrong. Is there anyway to take an image, crop it, then resize it? Or something that makes it look decent? Thanks Hey guys, i have been creating a profile page for a site i am doing. When i upload an image the profile image gets resized to 150px x 150px (CSS) however you can imagine if the image isnt a perfect size it will be squashed. Is there anyway i can resize the image? so that it doesnt look squashed like keep the full size upload image but pass it through a function before it displays in the profile section? if someone could point me in the right direction that would be awesome. Thanks!! Sorry bit rusty but been trying this for hours I upload an image no errors are showing i upload a jpg file and it saves to the server fine but its saving the original size not the new resized image size any ideas?? Code: [Select] if (isset ($_FILES['file'])) { $tmp_name = $_FILES["file"]["tmp_name"]; $file_type = $_FILES["file"]["type"]; $fileatt_name = $_FILES["file"]["name"]; if ($file_type=="image/pjpeg" OR $file_type=="image/jpeg" OR $file_type=="image/jpg") { $src = imagecreatefromjpeg($tmp_name); } // END if ($file_type=="image/pjpeg" OR $file_type=="image/jpeg" OR $file_type=="image/jpg") if ($file_type=="image/png" OR $file_type=="image/x-png") { $src = imagecreatefrompng($tmp_name); } // END if ($file_type=="image/png" OR $file_type=="image/x-png") if ($file_type=="image/gif") { $src = imagecreatefromgif($tmp_name); } // END if ($file_type=="image/gif") list($width,$height)=getimagesize($tmp_name); $width = $width; $height = $height; $newwidth = "200"; $newheight = "200"; $ratio=''; if($width==$height) { $newwidth = "200"; $newheight = "200"; } if($width>$height) { $ratio=($height/$width); $newwidth = "200"; $newheight = ($newwidth*$ratio); } if($width<$height) { $ratio=($width/$height); $newheight = "200"; $newwidth = ($newheight*$ratio); } $tmp = imagecreatetruecolor($newwidth, $newheight); $new=imagecopyresampled($tmp, $src,0,0,0,0,$newwidth,$newheight,$width,$height); $filename = "./yxy/". $fileattt_name; imagejpeg($tmp,$filename,100); imagedestroy($tmp); } Good Morning, Freaks, I hope you're all well. I've a question - I've been researching coding image resize functionality. While looking into the functions I'd need to do this I came across very similar code used in examples from 3 different sources so decided this was good code to learn from. So I tweeked it a bit and put it into a class method -> public function imageResize($target, $newcopy, $w, $h, $ext) { list($orig_w, $orig_h) = getimagesize($target); $scale_ratio = $orig_w/$orig_h; if(($w / $h) > $scale_ratio) { $w = $h * $scale_ratio; } else { $h = $w / $scale_ratio; } $img = ""; if($ext == "gif" || $ext == "GIF") { $img = imagecreatefromgif($target); } else if($ext == "png" || $ext == "PNG") { $img = imagecreatefrompng($target); } else if($ext == "jpg" || $ext == "JPG" || $ext == "jpeg" || $ext == "JPEG") { $img = imagecreatefromjpeg($target); } $create_tci = imagecreatetruecolor($w, $h); imagecopyresampled($create_tci, $img, 0, 0, 0, 0, $w, $h, $orig_w, $orig_h); imagejpeg($create_tci, $newcopy, 80); } and then connected it to a button -> <?php require("assets/initializations.php"); if(isset($_POST['upload_image'])) { $image_obj = new Image($conn, $user); $image_obj->imageUpload(); } else if(isset($_POST['resize_image'])) { mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT); $image_obj = new Image($conn, $user); $kaboom = explode(".", $image_name); //object params $image_ext = $kaboom[-1]; $target_image = "/opt/lampp/htdocs/site/admin/img/$image_name"; $resized_image = "/opt/lampp/htdocs/site/admin/img/resized_$image_name"; $max_w = 150; $max_h = 150; $image_obj->imageResize($target_image, $resized_image, $max_w, $max_h, $image_ext); //header("Location: add_photo.php"); } ?> Setup: A preview button chooses the image, a preview which is displayed underneath it (using js). There's also an upload button to bring it into the sites file system. This functionality works fine. I've just added the resize button beside the preview button and connected the object method to it. Intended Result: The resize button resizes the previewed image and the resized image is now previewed instead of the original image. Result: Nothing. The button stays in the active state, but nothing happens. I get no warning nor error messages and absolutely nothing in dev tools to work from. Not sure what my next step would be outside asking more experienced coders Any advise or guidance on getting this resolved would be met with appreciation. TIA
I am wanting to resize images on the fly in a loop (i.e. without saving them). However, any methods I have looked all need saving and won't just output the image in a loop. Is there any way to actually accomplish this? I use a simple php code (taken from php.net example) to resize an image Code: [Select] list($width, $height) = getimagesize($filename); $new_height = $height / $width * 400; $image_p = imagecreatetruecolor(400, $new_height); $image = imagecreatefromjpeg($filename); imagecopyresampled($image_p, $image, 0, 0, 0, 0, 400, $new_height, $width, $height); imagejpeg($image_p, "new.jpg"); Here, we create a blank image and merge it with the resized image. I wonder if it is the simplest way to resize and save an image. Is it really necessary to create a blank background image? I am using an upload page for photos, and When I try to display the photo after it's been uploaded it only displays part of the photo. I realize that that is probably because the file is too big, but if anyone out there knows how to resize an image for display after its been uploaded I would really appreciate the help. This is the get.php page I'm using to display the image Code: [Select] <?php $id=$_REQUEST['id']; $image=mysql_query("SELECT*FROM demophotos WHERE id=$id"); $image=mysql_fetch_assoc($image); $image=$image['image']; header ("Content-type: image/jpeg"); echo $image; ?> And this is the photo.php page that I'm using for uploading Code: [Select] <?php $file= $_FILES['image'] ['tmp_name']; if (!isset($file)) echo "Please select an image"; else { $image= addslashes(file_get_contents($_FILES['image'] ['tmp_name'])); $image_name= addslashes($_FILES['image'] ['name']); $image_size= getimagesize($_FILES['image'] ['tmp_name']); if ($image_size==FALSE) echo "Well that's not an image now, is it?"; else { if(!$insert= mysql_query("INSERT INTO demophotos(id, name, image) VALUES ('', '$image_name', '$image')")) echo "?"; else { $lastid=mysql_insert_id(); echo "Image uploaded <p /> You're Image: <p /><img src= get.php?id=$lastid>"; } } } ?> Hello there, Ill get straight to the point I want to copy part of an image with a set height and width with as little aspect ratio losing as possible. I tried just copying the size i wanted onto the destination image but when a large image was being used i lost quite alot of the picture. So then I just copied it all across but that compacted the image and I didnt want to do that (well not to that degree although some were funny because they were people.) So what have i got so far; Below is the important function which is doing the job. function copy_crop_image($width, $height, $new_width, $new_height, $dest, $source, $dx=55, $dy=19){ $top_x=0;// The x location on the source image $top_y=0;// Same as above but for the y // $dx and $dy are the destination x y of where to paste the image imagecopyresampled($dest, $source, $dx, $dy, $top_x, $top_y, $new_width, $new_height, $width, $height)===false; } Please can you help me out with guidance on how to resize the image then crop it in one go if possible to save resources. I know it can be done but I just can't think. Thank-you all Paul Hutchinson Hi there I have an image in a directory, that I need to resize on the fly but has to be a background in a div with a max width. I have to determine the correct height according to this max width. So I sucessfully I have accomplished this, but its not scaling its jsut giving me the top left corner according to my height width properties. Here is my working code to grab height and width: Code: [Select] $img_path = $CONFIG["full_url"].$CONFIG["upload_folder"].ReadDB($News["image"]); $max_width = 110; $max_height = 400; list($width, $height) = getimagesize($img_path); $ratioh = $max_height/$height; $ratiow = $max_width/$width; $ratio = min($ratioh, $ratiow); // New dimensions $mywidth = intval($ratio*$width); $myheight = intval($ratio*$height); Now using those I need to resize the image proper to get it centered up. I dont really want to save the file I just want to display it. Is this possible? My attempts have garnered a bunch of crazy characters on screen and not an image. Here is the code I added to the end: Code: [Select] // Resample $image_p = imagecreatetruecolor($mywidth, $myheight); $image = imagecreatefromjpeg($filename); imagecopyresampled($image_p, $image, 0, 0, 0, 0, $mywidth, $myheight, $width, $height); // Output imagejpeg($image_p, null, 100); Then Im using it on the page like so: Code: [Select] <div class="theimg" style="display:block; width:<?php echo $mywidth;?>px; height:<?php echo $myheight;?>px; background-image:url(<?php echo $image_p; ?>); background-repeat: no-repeat;"/> </div> and heres what I get :/ What am I doing wrong?? The image is not displaying inside its rounded corner border and we have crazy crap on top. Thanks in advance Hi guys Im trying to create a form which allows me to insert records into my database, and upload an image, the name of which will be stored in the database. I have the following code which inserts all the data into the db, except the image name and the image isnt uploaded either Code: [Select] <?php require_once('../Connections/pwnedbookv4.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) { $insertSQL = sprintf("INSERT INTO Games (gametitle, info, genre, releasedate, format) VALUES (%s, %s, %s, %s, %s)", GetSQLValueString($_POST['gametitle'], "text"), GetSQLValueString($_POST['info'], "text"), GetSQLValueString($_POST['genre'], "text"), GetSQLValueString($_POST['releasedate'], "date"), GetSQLValueString($_POST['format'], "text")); mysql_select_db($database_pwnedbookv4, $pwnedbookv4); $Result1 = mysql_query($insertSQL, $pwnedbookv4) or die(mysql_error()); } ?> <form action="<?php echo $editFormAction; ?>" method="post" enctype="multipart/form-data" name="form1" id="form1"> <table align="center"> <tr valign="baseline"> <td nowrap="nowrap" align="right">Gametitle:</td> <td><input name="gametitle" type="text" value="" size="50" maxlength="50" /></td> </tr> <tr valign="baseline"> <?php //define a maxim size for the uploaded images in Kb define ("MAX_SIZE","100"); //This function reads the extension of the file. It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } //This variable is used as a flag. The value is initialized with 0 (meaning no error found) //and it will be changed to 1 if an errro occures. //If the error occures the file will not be uploaded. $errors=0; //checks if the form has been submitted if(isset($_POST['Submit'])) { if($_POST['Submit'] == ""){ // submit empty die ("you must include a picture"); } //reads the name of the file the user submitted for uploading $image=$_FILES['image']['name']; //if it is not empty if ($image) { //get the original name of the file from the clients machine $filename = stripslashes($_FILES['image']['name']); //get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); //if it is not a known extension, we will suppose it is an error and will not upload the file, //otherwise we will do more tests if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { //print error message echo '<h1>Unknown extension!</h1>'; $errors=1; } else { //get the size of the image in bytes //$_FILES['image']['tmp_name'] is the temporary filename of the file //in which the uploaded file was stored on the server $size=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($size > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=time().'.'.$extension; //the new name will be containing the full path where will be stored (images folder) $newname="coverart/".$image_name; //Writes the information to the database mysql_query("UPDATE Games SET cover = '$image_name' WHERE gametitle= '$gametitle'"); //we verify if the image has been uploaded, and print error instead $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; }}}} ?> <td nowrap="nowrap" align="right">Cover:</td> <td><input type="file" name="image"></td></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right">Info:</td> <td><input name="info" type="text" value="" size="50" /></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right">Gen </td> <td><input type="text" name="genre" value="" size="50" /></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right">Releasedate:</td> <td><input type="text" name="releasedate" value="" size="50" /></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right">Format:</td> <td><input type="text" name="format" value="" size="50" /></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"> </td> <td><input type="submit" value="Submit" /></td> </tr> </table> <input type="hidden" name="MM_insert" value="form1" /> </form> Can anybody see what im missing? |