.
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 | | ? |
- function scanimgs($cleaned_up){
- preg_match_all('/<img[^>]+>/im',$cleaned_up, $imgarrays);
- $imgs=$imgarrays[0];
- $i=0; while($i<sizeof($imgs)){
- $thisimg = explode('"',stripslashes($imgs[$i]));
- $ii=0; while($ii<sizeof($thisimg)){
- if(substr($thisimg[$ii],0,4)=="http"){ $imgsize = getimagesize($thisimg[$ii]); break; } $ii++; }
- // Constraints
- $max_width = 765; $max_height = 765;
- if($imgsize[0]>$max_width || $imgsize[1]>$max_height){
- // Resample image down
- list($width, $height) = $imgsize; $ratioh = $max_height/$height; $ratiow = $max_width/$width;
- $ratio = min($ratioh, $ratiow); $imgwidth = intval($ratio*$width); $imgheight = intval($ratio*$height);
- } else {
- // Use original dimensions
- $imgwidth=$imgsize[0]; $imgheight=$imgsize[1];
- }
- // Put it back into the var
- $newsrc = substr(stripslashes($imgs[$i]),0,-1).' width="'.$imgwidth.'" height="'.$imgheight .'">';
- $count = 1; $cleaned_up = str_replace(($imgs[$i]), $newsrc, $cleaned_up, $count);
- $i++;
- }
- return $cleaned_up;
- }
Example usage:
| PHP | | copy code | | ? |
- $withtags = scanimgs("<your_html_code_in_here>");