Resize Image + retain quality + upload to mysql database

Reply

Join Date: Feb 2008
Posts: 5
Reputation: rajeshswain is an unknown quantity at this point 
Solved Threads: 0
rajeshswain rajeshswain is offline Offline
Newbie Poster

Resize Image + retain quality + upload to mysql database

 
0
  #1
Nov 24th, 2008
Hi Friends,

I want to upload a image file to my mysql database. But before that i want to resize it. I have used the following code. But what happens is that the image is successfully resized but the quality is not retained. Please someone guide me with some help.

The code goes here:

The php part
  1. <?php
  2. //***********************************************************************************************************
  3. ////////////////-------Photo upload, validation at server-------//////////////////////////
  4. //////////////////////////////////////////////////////////////////////////////////////////
  5.  
  6. $sPhotoFileName = $_FILES['photo']['name']; // get client side file name
  7. if ($sPhotoFileName) // file uploaded
  8. { $aFileNameParts = explode(".", $sPhotoFileName);
  9. $sFileExtension = end($aFileNameParts); // part behind last dot
  10. if ($sFileExtension != "jpg"
  11. && $sFileExtension != "JPEG"
  12. && $sFileExtension != "JPG")
  13. { die ("Choose a JPG for the photo");
  14. }
  15. $nPhotoSize = $_FILES['photo']['size']; // size of uploaded file
  16. if ($nPhotoSize == 0)
  17. { die ("Sorry. The upload of $sPhotoFileName has failed.
  18. Search a photo smaller than 100K, using the button.");
  19. }
  20. if ($nPhotoSize > 10240000000)
  21. { die ("Sorry.
  22. The file $sPhotoFileName is larger than 100K.
  23. Advice: reduce the photo using a drawing tool.");
  24. }
  25.  
  26. // read photo
  27. $sTempFileName = $_FILES['photo']['tmp_name']; // temporary file at server side
  28. $oTempFile = fopen($sTempFileName, "r");
  29. $sBinaryPhoto = fread($oTempFile, fileSize($sTempFileName));
  30.  
  31. // Try to read image
  32. $nOldErrorReporting = error_reporting(E_ALL & ~(E_WARNING)); // ingore warnings
  33. $oSourceImage = imagecreatefromstring($sBinaryPhoto); // try to create image
  34. error_reporting($nOldErrorReporting);
  35.  
  36. if (!$oSourceImage) // error, image is not a valid jpg
  37. { die ("Sorry.
  38. It was not possible to read photo $sPhotoFileName.
  39. Choose another photo in JPG format.");
  40. }
  41. }
  42. //////////////////////////////////////////////////////////////////////////////////////////
  43. //////////////-------Photo upload, validation at server ends---/////////////////////////////
  44.  
  45. //***********************************************************************************************************
  46. ////////////////----------Create thumbnail--------------//////////////////////////////////
  47. //////////////////////////////////////////////////////////////////////////////////////////
  48.  
  49. $nWidth = imagesx($oSourceImage); // get original source image width
  50. $nHeight = imagesy($oSourceImage); // and height
  51.  
  52. // create small thumbnail
  53. $nDestinationWidth = 80;
  54. $nDestinationHeight = 60;
  55. //$oDestinationImage = imagecreatetruecolor($nDestinationWidth, $nDestinationHeight);
  56. $oDestinationImage = imagecreate($nDestinationWidth, $nDestinationHeight);
  57.  
  58. /*$oResult = imagecopyresampled(
  59. $oDestinationImage, $oSourceImage,
  60. 0, 0, 0, 0,
  61. $nDestinationWidth, $nDestinationHeight,
  62. $nWidth, $nHeight); // resize the image
  63. */
  64. imagecopyresized($oDestinationImage, $oSourceImage,0, 0, 0, 0,$nDestinationWidth, $nDestinationHeight,$nWidth, $nHeight); // resize the image
  65.  
  66. ob_start(); // Start capturing stdout.
  67. imageJPEG($oDestinationImage); // As though output to browser.
  68. $sBinaryThumbnail = ob_get_contents(); // the raw jpeg image data.
  69. ob_end_clean(); // Dump the stdout so it does not screw other output.
  70.  
  71. //***********************************************************************************************************
  72. ////////////////------Store Thumbnail in database------//////////////////////////////////
  73. //////////////////////////////////////////////////////////////////////////////////////////
  74. if($_POST['send'])
  75. {
  76. $sBinaryThumbnail = addslashes($sBinaryThumbnail);
  77.  
  78. $oDatabase = mysql_connect("localhost", "root", "karma");
  79. mysql_select_db("upload", $oDatabase);
  80.  
  81. $sQuery = "insert into image (thumbnail) values ('$sBinaryThumbnail')";
  82. echo $sQuery;
  83.  
  84. mysql_query($sQuery, $oDatabase);
  85. }
  86.  
  87. ?>

The html form

  1. <form enctype="multipart/form-data" method="post" action="" name="form1">
  2. <input type="hidden" name="MAX_FILE_SIZE" value="102400">
  3. <input type="file" name="photo">
  4. <input type="hidden" name="id" value="12345">
  5. <input type=submit value="Send" name=send>
  6. </form>

Here is the code where i have displayed the uploaded image. the quality becomes bad here.
  1. <?
  2. $oDatabase = mysql_connect("localhost", "root", "karma");
  3. mysql_select_db("upload", $oDatabase);
  4. $s="select thumbnail from image";
  5. $r=mysql_query($s);
  6. while($p=mysql_fetch_array($r))
  7. {
  8. $bytes = $p[0];
  9. if($bytes == null)
  10. {
  11. $instr = fopen("images/d_silhouette.gif","rb");
  12. $bytes = fread($instr,filesize("images/d_silhouette.gif"));
  13. }
  14. $data = base64_encode($bytes);
  15. echo '<img src="data:image/jpeg;base64,', $data, '" border=0 />';
  16. }
  17. ?>

Waiting for reply...
Last edited by peter_budo; Nov 24th, 2008 at 6:21 pm. Reason: Keep It Organized - For easy readability, always wrap programming code within posts in [code] (code blocks) and [icode] (inline code) tags.
Reply With Quote Quick reply to this message  
Join Date: Feb 2008
Posts: 347
Reputation: kevin wood is an unknown quantity at this point 
Solved Threads: 1
kevin wood's Avatar
kevin wood kevin wood is offline Offline
Posting Whiz

Re: Resize Image + retain quality + upload to mysql database

 
0
  #2
Nov 24th, 2008
try this code out i have no problems with the image quality with it.

  1. <?php
  2.  
  3.  
  4.  
  5. set_time_limit(0);
  6.  
  7. $link = mysql_connect(localhost, xxxxxxxx, xxxxxxxxx) or die("Could not connect to host."); //put in your db connection details here
  8. mysql_select_db(xxxxxxx) or die("Could not find database."); // put your db name in here where the xxxx are
  9.  
  10.  
  11.  
  12.  
  13. //define a maxim size for the uploaded images
  14. define ("MAX_SIZE","500");
  15. // define the width and height for the thumbnail
  16. // note that theese dimmensions are considered the maximum dimmension and are not fixed,
  17. // because we have to keep the image ratio intact or it will be deformed
  18. define ("WIDTH","150"); //set here the width you want your thumbnail to be
  19. define ("HEIGHT","120"); //set here the height you want your thumbnail to be.
  20.  
  21. // this is the function that will create the thumbnail image from the uploaded image
  22. // the resize will be done considering the width and height defined, but without deforming the image
  23. function make_thumb($img_name,$filename,$new_w,$new_h)
  24. {
  25. //get image extension.
  26. $ext=getExtension($img_name);
  27. //creates the new image using the appropriate function from gd library
  28. if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
  29. $src_img=imagecreatefromjpeg($img_name);
  30.  
  31. if(!strcmp("png",$ext))
  32. $src_img=imagecreatefrompng($img_name);
  33.  
  34. if(!strcmp("gif",$ext))
  35. $src_img=imagecreatefromgif($img_name);
  36.  
  37. //gets the dimmensions of the image
  38. $old_x=imageSX($src_img);
  39. $old_y=imageSY($src_img);
  40.  
  41. // next we will calculate the new dimmensions for the thumbnail image
  42. // the next steps will be taken:
  43. // 1. calculate the ratio by dividing the old dimmensions with the new ones
  44. // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
  45. // and the height will be calculated so the image ratio will not change
  46. // 3. otherwise we will use the height ratio for the image
  47. // as a result, only one of the dimmensions will be from the fixed ones
  48. $ratio1=$old_x/$new_w;
  49. $ratio2=$old_y/$new_h;
  50. if($ratio1>$ratio2) {
  51. $thumb_w=$new_w;
  52. $thumb_h=$old_y/$ratio1;
  53. }
  54. else {
  55. $thumb_h=$new_h;
  56. $thumb_w=$old_x/$ratio2;
  57. }
  58.  
  59. // we create a new image with the new dimmensions
  60. $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
  61. // resize the big image to the new created one
  62. imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
  63.  
  64. // output the created image to the file. Now we will have the thumbnail into the file named by $filename
  65. if(!strcmp("png",$ext))
  66. imagepng($dst_img,$filename);
  67. else
  68. imagejpeg($dst_img,$filename);
  69.  
  70. if (!strcmp("gif",$ext))
  71. imagegif($dst_img,$filename);
  72.  
  73. //destroys source and destination images.
  74. imagedestroy($dst_img);
  75. imagedestroy($src_img);
  76. }
  77.  
  78. // This function reads the extension of the file.
  79. // It is used to determine if the file is an image by checking the extension.
  80. function getExtension($str) {
  81. $i = strrpos($str,".");
  82. if (!$i) { return ""; }
  83. $l = strlen($str) - $i;
  84. $ext = substr($str,$i+1,$l);
  85. return $ext;
  86. }
  87. // This variable is used as a flag. The value is initialized with 0 (meaning no error found)
  88. //and it will be changed to 1 if an error occures. If the error occures the file will not be uploaded.
  89. $errors=0;
  90. // checks if the form has been submitted
  91. if(isset($_POST['Submit']))
  92. {
  93. //reads the name of the file the user submitted for uploading
  94. $image=$_FILES['cons_image']['name'];
  95. // if it is not empty
  96. if ($image)
  97. {
  98. // get the original name of the file from the clients machine
  99. $filename = stripslashes($_FILES['cons_image']['name']);
  100.  
  101. // get the extension of the file in a lower case format
  102. $extension = getExtension($filename);
  103. $extension = strtolower($extension);
  104. // if it is not a known extension, we will suppose it is an error, print an error message
  105. //and will not upload the file, otherwise we continue
  106. if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
  107. {
  108. echo '<h1>Unknown extension! Please use .gif, .jpg or .png files only.</h1>';
  109. $errors=1;
  110. }
  111. else
  112. {
  113. // get the size of the image in bytes
  114. // $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which
  115. //the uploaded file was stored on the server
  116. $size=getimagesize($_FILES['cons_image']['tmp_name']);
  117. $sizekb=filesize($_FILES['cons_image']['tmp_name']);
  118.  
  119. //compare the size with the maxim size we defined and print error if bigger
  120. if ($sizekb > MAX_SIZE*1024)
  121. {
  122. echo '<h1>You have exceeded the 1MB size limit!</h1>';
  123. $errors=1;
  124. }
  125.  
  126.  
  127. $rand= rand(0, 1000);
  128. //we will give an unique name, for example a random number
  129. $image_name=$rand.'.'.$extension;
  130. //the new name will be containing the full path where will be stored (images folder)
  131. $consname="image/".$image_name; //change the image/ section to where you would like the original image to be stored
  132. $consname2="image/thumb".$image_name; //change the image/thumb to where you would like to store the new created thumb nail of the image
  133. $copied = copy($_FILES['cons_image']['tmp_name'], $consname);
  134. $copied = copy($_FILES['cons_image']['tmp_name'], $consname2);
  135.  
  136. $sql="UPDATE your table name SET image= '$consname2' WHERE id= '$lastid'"or die(mysql_error());
  137. $query = mysql_query($sql)or die(mysql_error());
  138. //we verify if the image has been uploaded, and print error instead
  139. if (!$copied) {
  140. echo '<h1>Copy unsuccessfull!</h1>';
  141. $errors=1;
  142. }
  143. else
  144. {
  145. // the new thumbnail image will be placed in images/thumbs/ folder
  146. $thumb_name=$consname2 ;
  147. // call the function that will create the thumbnail. The function will get as parameters
  148. //the image name, the thumbnail name and the width and height desired for the thumbnail
  149. $thumb=make_thumb($consname,$thumb_name,WIDTH,HEIGHT);
  150. }
  151. }
  152. }
  153. }
  154.  
  155. //If no errors registred, print the success message and how the thumbnail image created
  156. if(isset($_POST['Submit']) && !$errors)
  157. {
  158. echo "<h5>Thumbnail created Successfully!</h5>";
  159. echo '<img src="'.$thumb_name.'">';
  160. echo $lastid;
  161. }
  162.  
  163. echo "<form name=\"newad\" method=\"post\" enctype=\"multipart/form-data\" action=\"\">";
  164. echo "<input type=\"file\" name=\"cons_image\" >";
  165. echo "<input name=\"Submit\" type=\"submit\" id=\"image1\" value=\"Upload image\" />";
  166. echo "</form>";
  167.  
  168. ?>

just change the sql section to an insert and this should work fine for you.
Reply With Quote Quick reply to this message  
Join Date: Jul 2007
Posts: 2
Reputation: parkerproject is an unknown quantity at this point 
Solved Threads: 0
parkerproject parkerproject is offline Offline
Newbie Poster

Re: Resize Image + retain quality + upload to mysql database

 
0
  #3
Mar 8th, 2009
reading your code,it looks like you are storing just the filename in the database.i guess if i want to store the thumbnail in the database,then i would INSERT $thumb rather than $consname2

correct me in am wrong
Reply With Quote Quick reply to this message  
Join Date: Feb 2008
Posts: 347
Reputation: kevin wood is an unknown quantity at this point 
Solved Threads: 1
kevin wood's Avatar
kevin wood kevin wood is offline Offline
Posting Whiz

Re: Resize Image + retain quality + upload to mysql database

 
0
  #4
Mar 9th, 2009
this code stores the path to the image in the db an stores two copies of the image on the server. the original and the newly created thumbnail image.

you will need to create a folder called image and one call thumb inside of that.
Reply With Quote Quick reply to this message  
Join Date: Jul 2007
Posts: 2
Reputation: parkerproject is an unknown quantity at this point 
Solved Threads: 0
parkerproject parkerproject is offline Offline
Newbie Poster

Re: Resize Image + retain quality + upload to mysql database

 
0
  #5
Mar 9th, 2009
All the images are stored in the images folder.I want the thumbnails stored in the thumb and the original store in images.

can you help
Reply With Quote Quick reply to this message  
Join Date: Feb 2008
Posts: 347
Reputation: kevin wood is an unknown quantity at this point 
Solved Threads: 1
kevin wood's Avatar
kevin wood kevin wood is offline Offline
Posting Whiz

Re: Resize Image + retain quality + upload to mysql database

 
0
  #6
Mar 10th, 2009
if you look for the section where the values of $consname and $consname2 are set you can change where the files are stored on the server there.
if you want the oiginal image stored in the images folder then the line of code should look like this

  1. $consname="images/".$image_name;

and the thumbs to be stored in a thumb folder the next line of code will be

  1. $consname2="thumb/".$image_name;
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Other Threads in the PHP Forum
Thread Tools Search this Thread



Tag cloud for PHP
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC