PHP Image Tag Traverser and Resizer

.
This code was developed after using the Yahoo YUI Editor and realising that none of the images were being assigned proper width/height attributes without the extended options. We needed a way to read the string collected from the Editor, collect all image tags, get the actual size of the embedded image, resample it to within some constraints, then inject that new data back into the string before sending it to a MySQL database.

The following function should take some of the headache out of doing that.

 PHP |  copy code |? 
  1. function scanimgs($cleaned_up){
  2. preg_match_all('/<img[^>]+>/im',$cleaned_up, $imgarrays);
  3. $imgs=$imgarrays[0];
  4. $i=0; while($i<sizeof($imgs)){
  5. $thisimg = explode('"',stripslashes($imgs[$i]));
  6. $ii=0; while($ii<sizeof($thisimg)){
  7. if(substr($thisimg[$ii],0,4)=="http"){ $imgsize = getimagesize($thisimg[$ii]); break; } $ii++; }
  8. // Constraints
  9. $max_width = 765; $max_height = 765;
  10. if($imgsize[0]>$max_width || $imgsize[1]>$max_height){
  11. // Resample image down
  12. list($width, $height) = $imgsize; $ratioh = $max_height/$height; $ratiow = $max_width/$width;
  13. $ratio = min($ratioh, $ratiow); $imgwidth = intval($ratio*$width); $imgheight = intval($ratio*$height);
  14. } else {
  15. // Use original dimensions
  16. $imgwidth=$imgsize[0]; $imgheight=$imgsize[1];
  17. }
  18. // Put it back into the var
  19. $newsrc = substr(stripslashes($imgs[$i]),0,-1).' width="'.$imgwidth.'" height="'.$imgheight .'">';
  20. $count = 1; $cleaned_up = str_replace(($imgs[$i]), $newsrc, $cleaned_up, $count);
  21. $i++;
  22. }
  23. return $cleaned_up;
  24. }

Example usage:

 PHP |  copy code |? 
  1. $withtags = scanimgs("<your_html_code_in_here>");

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>