PHP - Images Not Reducing In Size:
Hi, I'm using the script below to that allows a user to upload a photo, which then appears on the page as a thumbnail, the image can be clicked and opens up in a lightbox image pop up.
All this works fine except the images are not resizing. I.e if a a picture is 1024px wide, before upload - it stays that size on the server. I need it to compress down to around 600px wide and have the KB of the file reduced. I know that I should be using GD library to do this but not sure how to implement it. The script I am using is he ############################################################################################## function upload($user_id,$fileid) ############################################################################################## { global $db; $maxsize = $_POST['MAX_FILE_SIZE']; if(is_uploaded_file($_FILES['userfile']['tmp_name'][$fileid])) { if($_FILES['userfile']['size'][$fileid] < $maxsize) { $imgData = addslashes(file_get_contents($_FILES['userfile']['tmp_name'][$fileid])); $size = getimagesize($_FILES['userfile']['tmp_name'][$fileid]); $sql_query = "SELECT * FROM user_images WHERE image_id = '999999999999999999'"; if(mysqli_num_rows(mysqli_query($db, $sql_query)) > 0) { $sql_query = "UPDATE user_images SET image_type = '{$size['mime']}', image = '{$imgData}', image_size = '{$size[3]}', image_name = '{$_FILES['userfile']['name'][$fileid]}' WHERE image_id = '$user_id'"; } else { $sql_query = "INSERT INTO user_images ( image_type ,image, image_size, image_name) VALUES ('{$size['mime']}', '{$imgData}', '{$size[3]}', '{$_FILES['userfile']['name'][$fileid]}')"; } if(!mysqli_query($db,$sql_query)) { echo '<div class="error">Unable to upload file</div>'; } else { $return = mysqli_insert_id($db); } } else { echo '<div>File exceeds the Maximum File limit. Skipping uploading of image.</div> <div>Maximum File limit is '.$maxsize.'</div> <div>File '.$_FILES['userfile']['name'][$fileid].' is '.$_FILES['userfile']['size'][$fileid].' bytes</div> <hr />'; } } return $return; }//END - upload() ############################################################################################## function imageResize($width, $height, $target) ############################################################################################## { //protect function if image sizes not set (i.e. image doesn't exist in database) if((!isset($width)) || (!isset($height))) { $width = '1'; $height = '1'; } //if trying to resize an image that is much smaller than target...essentially do nothing and keep the original sizing elseif(($width < $target) && ($height < $target)) { } else { //takes the larger size of the width and height and applies the formula accordingly...this is so this script will work dynamically with any size image if ($width > $height) { $percentage = ($target / $width); } else { $percentage = ($target / $height); } //gets the new value and applies the percentage, then rounds the value $width = round($width * $percentage); $height = round($height * $percentage); } //returns the new sizes in html image tag format... return "width=\"$width\" height=\"$height\""; }//END - imageResize ############################################################################################## Similar TutorialsHi all I have an SQL table with a quantity in and I am trying to write a piece of code to reduce the quantity by 1 each time. Here's my code: $queryc = mysql_query(" SELECT FROM `voucher_codes` WHERE name = '".$voucherc."'"); $resultc = mysql_fetch_array ($queryc); $voucherqtyvalue = $resultc['qty']; $newvoucherqty = $voucherqtyvalue - 1; $queryi = mysql_query(" UPDATE `voucher_codes` SET qty = '".$newvoucherqty."' WHERE name = '".$_SESSION['vouchercode']."'"); $resulti = mysql_result($queryi); Instead, this changes the value to -1 in the table. Please help! Cheers Pete Hi, What is a shorter way instead of having all these if statements? Here it is: Code: [Select] if($matchno==1) return 66; elseif($matchno==2) return 67; elseif($matchno==3) return 68; elseif($matchno==4) return 69; elseif($matchno==5) return 70; elseif($matchno==6) return 71; elseif($matchno==7) return 72; elseif($matchno==8) return 73; elseif($matchno==9) return 74; elseif($matchno==10) return 75; elseif($matchno==11) return 76; elseif($matchno==12) return 77; elseif($matchno==13) return 78; elseif($matchno==14) return 79; elseif($matchno==15) return 80; elseif($matchno==16) return 81; elseif($matchno==17) return 82; elseif($matchno==18) return 83; elseif($matchno==19) return 84; elseif($matchno==20) return 85; elseif($matchno==21) return 86; elseif($matchno==22) return 87; elseif($matchno==23) return 88; elseif($matchno==24) return 89; elseif($matchno==25) return 90; elseif($matchno==26) return 91; elseif($matchno==27) return 92; elseif($matchno==28) return 93; elseif($matchno==29) return 94; elseif($matchno==30) return 95; elseif($matchno==31) return 96; elseif($matchno==32) return 97; someone please code shorter? I will learn this way. Thanks. Does anybody have links or scripst on a script where the user has an account with money which decreases as one purchases items. Regards For solely to reduce duplicated code and when injection isn't applicable, should one use inheritance or traits? <?php abstract class BaseClass { private $id, $name; public function __construct(int $id, string $name) { $this->id=$id; $this->name=$name; } public function getId():int { return $this->id; } public function getName():string { return $this->name; } } <?php class A extends BaseClass{} class B extends BaseClass{} class C extends BaseClass { private $foo; public function __construct(int $id, string $name, Foo $foo) { parent::__construct($id, $name); $this->foo=$foo; } public function getFoo():Foo { return $this->foo; } } <?php trait MyTrait { private $id, $name; public function __construct(int $id, string $name) { $this->id=$id; $this->name=$name; } public function getId():int { return $this->id; } public function getName():string { return $this->name; } } <?php class A { use MyTrait; } class B { use MyTrait; } class C { use MyTrait; private $foo; public function __construct(int $id, string $name, Foo $foo) { $this->id=$id; $this->name=$name; $this->foo=$foo; } public function getFoo():Foo { return $this->foo; } } Edited January 2, 2020 by NotionCommotion Hi Guys and Gals, I run a simple fansite for some of my fellow MTG Tactics players at www.onlinegamekey.com I recently made a Booster Page value page he http://www.onlinegamekey.com/booster-packs.php And it seems the page loads really slow, but I kind of understand that since its doing a lot of math and dealing with a lot of data. I am wondering if there is a way to possibly optimize the page and querys in such a way that it doesn't take so long to load. I'm basically using 4 queries to get the value of each pack and 1 function to average the query data. And I add them up as I go. This is my function to find average values Code: [Select] ///AVERAGE FUNCTION function calculate_average($arr) { $count = count($arr); //total numbers in array foreach ($arr as $value) { $total = $total + $value; // total value of array numbers } $average = ($total/$count); // get average value return $average; } These are the queries to get the Average Values Code: [Select] <?php ///SETTING THE DAY $today = date("Y/m/d"); ///ALTERING DAY QUERY TIME (20 Days of Data) $minusday = mktime(0,0,0,date("m"),date("d")-20,date("Y")); ///SETTING THE DAY FOR THE QUERIES $queryday = date("Y/m/d",$minusday); ///DATA SET FOR BOOSTER PACK 1 //GET THE MYTHIC AVERAGE VALUE $sqlMythic=mysql_query("SELECT AVG( ab.Price_Per ) AS Aaverage FROM auctions AS ab INNER JOIN cardlist AS c ON c.card_name = ab.Card_Name WHERE ab.Day >= '$queryday' AND c.rarity = 'Mythic Rare' AND c.set = '1' GROUP BY c.card_name, ab.Card_Name") or die; while ($row=mysql_fetch_array($sqlMythic)) { $MythicValues[]=$row['Aaverage']; } ///MYTHIC VALUE IS 10% OF AVERAGE VALUE $Mythic = calculate_average($MythicValues) * .1; //GET THE RARE AVERAGE VALUE $sqlRare=mysql_query("SELECT AVG( ab.Price_Per ) AS Aaverage FROM auctions AS ab INNER JOIN cardlist AS c ON c.card_name = ab.Card_Name WHERE ab.Day >= '$queryday' AND c.rarity = 'Rare' AND c.set='1' GROUP BY c.card_name, ab.Card_Name") or die; while ($row=mysql_fetch_array($sqlRare)) { $RareValues[]=$row['Aaverage']; } ///RARE VALUE IS 90% OF AVERAGE RARE VALUE $Rare = calculate_average($RareValues) *.9; ///TOTAL CONTRIBUTION TO PACK 100% IS 10% MYTHIC + 90% RARE $raremythic= $Mythic + $Rare; ///GET THE UNCOMMON AVERAGE VALUE $sqlUncommon=mysql_query("SELECT AVG( ab.Price_Per ) AS Aaverage FROM auctions AS ab INNER JOIN cardlist AS c ON c.card_name = ab.Card_Name WHERE ab.Day >= '$queryday' AND c.rarity = 'Uncommon' AND c.set='1' GROUP BY c.card_name, ab.Card_Name") or die; while ($row=mysql_fetch_array($sqlUncommon)) { $ucValues[]=$row['Aaverage']; } ///UNCOMMON VALUE IS VALUE * 3 $Uncommon = calculate_average($ucValues); $urm= ($Uncommon * 3) + $raremythic; ///GET THE COMMON VALUE $sqlCommon=mysql_query("SELECT AVG( ab.Price_Per ) AS Aaverage FROM auctions AS ab INNER JOIN cardlist AS c ON c.card_name = ab.Card_Name WHERE ab.Day >= '$queryday' AND c.rarity = 'Common' AND c.set='1' GROUP BY c.card_name, ab.Card_Name") or die; while ($row=mysql_fetch_array($sqlCommon)) { $cValues[]=$row['Aaverage']; } ///COMMON VALUE IS VALUE * 10 $common = calculate_average($cValues); //TOTAL SET 1 VALUE IS ALL VALUES ADDED UP $curm= ($common * 10) + $urm; ?> But I'm not real sure where the strain is coming from. The page seems to load really slow, and I'm not sure if I should just try and write all these queries as a separate function then have it write the data to a separate table, or if there is another way to optimize this code. I'm still have a lot to learn so I would appreciate any thoughts or ideas you folks can offer me. Many thanks could someone help in how to resize a uploaded image size, say if someone is uploading a 1mb photo to my server, i wish for it to become 100kb and also resize its width and height? here is my code Code: [Select] //////////////////////////////////////uploader else if($action=="uploader") { echo "Upload your picture and copy the link <br/>after uploading to user it at gallery.<br/><br/>"; echo "<form method=\"post\" enctype=\"multipart/form-data\" action=\"index.php?action=uploaded&sid=$sid\">"; echo "Choose Pictu <br />"; echo "<input name=\"uploaded\" type=\"file\" /><br /><br />"; echo "<input type=\"submit\" value=\"Upload\" />"; echo "</form><br/>"; echo "<p align=\"center\">"; echo "<a href=\"index.php?action=main&sid=$sid\">Home</a>"; echo "</p>"; } //////////////////////////////////////uploader else if($action=="uploaded") { $blacklist = array(".php", ".php.jpg", ".php.jpeg", ".php.gif", ".php.png", ".phtml", ".php3", ".php4"); foreach ($blacklist as $item) { if(preg_match("/$item\$/i", $_FILES['uploaded']['name'])) { echo "<p align=\"center\">"; echo "Oops sorry we do not allow those files.<br/>"; echo "<a href=\"index.php?action=main&sid=$sid\">Home</a>"; echo "</p>"; exit; } } $target = "../images/"; $target = $target . basename( $_FILES['uploaded']['name']) ; $ok=1; if (file_exists("../images/" . $_FILES["uploaded"]["name"])) { echo "<p align=\"center\">"; echo $_FILES["file"]["name"] . "Oops file name already exists<br/> kindly rename your picture and upload again. <br/>"; echo "<a href=\"index.php?action=main&sid=$sid\">Home</a>"; echo "</p>"; }else{ //This is our size condition if ($uploaded_size > 25600){ echo "Your file is too large. We have a 25kb limit.<br/>"; $ok=0; } $types = array('image/jpeg', 'image/gif', 'image/png'); if (in_array($_FILES['uploaded']['type'], $types)) { // file is okay continue } else { $ok=0; } //Here we check that $ok was not set to 0 by an error if ($ok==0){ echo "<p align=\"center\">"; Echo "Sorry your file was not uploaded.<br/> It may be the wrong filetype. <br/>We only allow JPG, GIF, and PNG filetypes.<br/>"; echo "<a href=\"index.php?action=main&sid=$sid\">Home</a>"; echo "</p>"; } //If everything is ok we try to upload it else{ if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)){ echo "<p align=\"center\">"; echo "The file ". basename( $_FILES['uploadedfile']['name']). " Picture uploaded successfully.<br/><br/><b>$target <br/>"; echo "<a href=\"index.php?action=main&sid=$sid\">Home</a>"; echo "</p>"; } else{ echo "<p align=\"center\">"; echo "Sorry, there was a problem uploading your file.<br/>"; echo "<a href=\"index.php?action=main&sid=$sid\">Home</a>"; echo "</p>"; } } } } Hi there, In a string for a shopping cart I am storing both the item id and the item size selected in a number like this 12s1 where 12 is the id and 1 is the size. How can I separate these from one another again? I'm guessing it's to do with expand() ? Thanks, Jack I have this script from http://lampload.com/...,view.download/ (I am not using a database) I can upload images fine, I can view files, but I want to delete them. When I press the delete button, nothing happens
http://www.jayg.co.u...oad_gallery.php
<form>
<?php $dir = dirname(__FILENAME__)."/images/gallery" ; $files1 = scandir($dir); foreach($files1 as $file){ if(strlen($file) >=3){ $foil = strstr($file, 'jpg'); // As of PHP 5.3.0 $foil = $file; $pos = strpos($file, 'css'); if ($foil==true){ echo '<input type="checkbox" name="filenames[]" value="'.$foil.'" />'; echo "<img width='130' height='38' src='images/gallery/$file' /><br/>"; // for live host //echo "<img width='130' height='38' src='/ABOOK/SORTING/gallery-dynamic/images/gallery/ $file' /><br/>"; } } }?> <input type="submit" name="mysubmit2" value="Delete"> </form>
any ideas please?
thanks
Hello again How to convert size from taken from sql as the numbers and converted to MB in php? i need help gettig the size of a directory I am able to get directory size of folder inside folders owned by me but I need to get folder size of a root owned folder. Is it possible to do this? Thanks in advance! Hello: Hoping someone can help me figure this out... I am resizing a photo/thumbnails with GD (I think that's the correct term) upon uploading. Works fine but the one thing I can't figure out is how to scale the height proportionate with the width. Meaning, I have the width set to 690px, and the height set to 500px. It is making the images look squished. What I would like to do is have a set width (like 690px), but have the height scale down proportionalety. Or, can I just remove the height (although I tried that and it did not work). This is the code: Code: [Select] // 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]); $old_width = $size[0]; $old_height = $size[1]; $thumbnail_width = 690; $thumbnail_height = ($old_height * $thumbnail_width / $old_width); } 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 ); $destination_handle = imagecreatetruecolor( $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; width: 100px;' />"; Anyone have any ideas on this? Thanks much. hi, i want to resize the font-size in my website ussing php butt it doenst work why ?? can someone help me to get it working?? Code: [Select] <html> <head> <title>Een website naam.</title> </head> <!-- this doent work, this was a test to see ik ik works!! --> <style type='text/css'> html{ font-size: 300%; } </style> <!-- this is my php code for working with resize!! This must got to work !!! --> <!-- Start varible font-size --> <?php //start session Session_start(); $_SESSION['FontSize']='300'; // check default fontsize if($_SESSION['FontSize']=='') { ?> <style type='text/css'> body { font-size: 100%; } </style> <?php } else { echo "<style type='text/css'>body { font-size: ".$_SESSION['FontSize']."%; } </style>"; } ?> <!-- end varible font-size --> how can tell my wath i do wrong??? thnx, Hi I know that maximum size of one cookie is 4Kb.. That is kilobytes right? and not kilobit? And a byte is 8 bits right? So if I have "Hello" in my cookie thats 5 characters which means the cookie is 5 x 8 = 40 bit which is again 5 bytes (?). Does this mean that I can have a maximum of 4000 characters in my cookie? Or did I miss something here? Thanks This topic has been moved to CSS Help. http://www.phpfreaks.com/forums/index.php?topic=347531.0 rating_bar($rows['id'],'6','static')." Show a star rating but the stars are to big. How can I change the size of the rating_bar, like I change the font size? echo "<TD style='font-size: 10px;' ALIGN=justify width=50% height=10 scope='row'><p>Please rate</p>". rating_bar($rows['id'],'6','static')."</TD>"; 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? Font size GD Library Hi All I'm trying to create a font tester - http://www.ttmt.org.uk/fonts/index.php (this demo doesn't use the font I'm using.). I'm using the GD library to create images of the text. I'm not happy with the quality of the fonts at small sizes. I've tried everything to fix it but nothing is working. One suggestion I had was to create the fonts larger then reduce the size of the image. Can anyone offer any advise how I might do this? Code: [Select] <?php header('Content-Type: image/png'); $im = imagecreatetruecolor(1000, 200); $gray = imagecolorallocate($im, 240, 240, 240); $black = imagecolorallocate($im, 0, 0, 0); imagefilledrectangle($im, 0, 0, 1000, 199, $gray); $text = $_GET['text']; $textSize = $_GET['size']; $font = $_GET['font']; imagefttext($im, $textSize, 0, 15, 160, $black, $font, $text); imagepng($im); imagedestroy($im); ?> Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>untitled</title> <style type="text/css"> *{margin:0;padding:0;} #wrap{margin:20px 0 0 20px;} h1{margin:0px 0 20px 0;clear:both;} h2{font-size:1.1em;margin:15px 0 5px 0;} #top{padding:0 0 20px 0;} form{margin:0 0 20px 0;} </style> </head> <body> <div id="wrap"> <form action="index.php" method="post"> <!--<input type="text" name="text" value="<?php echo $_POST['text'];?>" />--> <select name="text" > <option value="<?php echo $_POST['text'];?>">Text</option> <option value="ABCDEFGHIJKLMNOPQRSTUVWXYZ">ABCDEFGHIJKLMNOPQRSTUVWXYZ</option> <option value="abcdefghijklmnopqrstuvwxyz">abcdefghijklmnopqrstuvwxyz</option> <option value="0123456789">0123456789</option> </select> <select name="size"> <option value="<?php echo $_POST['size'];?>">Size</option> <option value="10">10</option> <option value="12">12</option> <option value="14">14</option> <option value="18">18</option> <option value="24">24</option> <option value="30">30</option> <option value="38">38</option> <option value="42">42</option> <option value="50">50</option> <option value="60">60</option> <option value="80">80</option> <option value="100">100</option> </select> <input type="submit" name="submit" value="Set →" /> </form> <div id="top"> <?php $theFont="corbelb.ttf"; if(!empty($_POST['submit'])){ $myText = $_POST['text']; $mySize = $_POST['size']; echo '<img src="imageftt.php?text='.$myText.'&size='.$mySize.'&font='.$theFont.'">'; }else{ $myText = "Handgloves"; $mySize = 24; echo '<img src="imageftt.php?text='.$myText.'&size='.$mySize.'&font='.$theFont.'">'; } ?> </div> </div> </body> </html> Is there a way I can get the .jpg file in kilobytes from a remote url and check it to make sure it does not exceed 40 kilobytes before it saves the remote url into my database? |