PHP - Image Resizing
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?
Similar TutorialsHey 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: 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. 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. 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 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']}"); 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); } 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 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 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? 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); ?> 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'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; 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
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 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 I have uploaded images from a server onto a website, they run through a mysql database (database holds the image file names). The problem I am having is resizing the images. Can anyone help? Thank you in advance GWG I've been working on this site that allows users to upload images to the server... the code i have right now basically uploads the file to the server and then resizes it and makes a new copy of it... Upuntil now it was working flawlessly, however now i'm getting this error: Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG library reports unrecoverable error: in /home/content/t/h/e/thereferralpro/html/beta/region.php on line 144 Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: 'images/projects/porncheck_star.png' is not a valid JPEG file in /home/content/t/h/e/thereferralpro/html/beta/region.php on line 144 Warning: imagecopyresampled(): supplied argument is not a valid Image resource in /home/content/t/h/e/thereferralpro/html/beta/region.php on line 162 Warning: imagedestroy(): supplied argument is not a valid Image resource in /home/content/t/h/e/thereferralpro/html/beta/region.php on line 165 In order for you guys to understand the error here's the code i'm using //move file to the folder before resizeing move_uploaded_file($_FILES['image']['tmp_name'], $target); //resize the image and add to server $source_pic = $target; $final_pic = $dir.$final_img_name; $max_width = 800; $max_height = 600; $src = imagecreatefromjpeg($source_pic); list($width,$height)=getimagesize($source_pic); $x_ratio = $max_width / $width; $y_ratio = $max_height / $height; if( ($width <= $max_width) && ($height <= $max_height) ){ $tn_width = $width; $tn_height = $height; }elseif (($x_ratio * $height) < $max_height){ $tn_height = ceil($x_ratio * $height); $tn_width = $max_width; }else{ $tn_width = ceil($y_ratio * $width); $tn_height = $max_height; } $tmp=imagecreatetruecolor($tn_width,$tn_height); imagecopyresampled($tmp,$src,0,0,0,0,$tn_width, $tn_height,$width,$height); imagejpeg($tmp,$final_pic,80); imagedestroy($src); imagedestroy($tmp); list($width, $height, $type, $attr) = getimagesize($final_pic); Keep in mind that this code was working perfectly and now for some reason its not working anymore, and no i have not touch it at all nor i have done nay edits to this code Hope someone can help me out because i have no idea what this could be. Thanks Hey, I know how to use the PHP GD functions but how would I resize an image > 1000 width to 1000 width and just resizing the height to w/e needed to keep aspect ratio if the image is set to 1000 width in pixels of course. I don't mess with images much so idk the whole ratio thing. |