Rasher's Toolbox

Back

fix_jpeg

bool fix_jpeg(string filename) -- Removes extraneous bytes from JPEG image.

Description

Removes extraneous bytes from the end of a JPEG image. Some cameras (such as Nokia cellphones) create JPEG images which contain junk at the end, causing PHP to not like them. This function removes this garbage and produces a more valid jpeg image.

Example

<?php
  fix_jpeg
('image.jpg');
?>

Source

Published under the terms of the BSD License

<?php
function fix_jpeg($filename) {
    
$size filesize($filename);
    
$str file_get_contents($filename);
    
// Remove bytes as long as the string does not represent an image
    
$i 0;
    while (@
imagecreatefromstring($str) === false) {
        
// Remove the last byte before the two-byte EOI (0xFF 0xD9)
        
$str substr_replace($str'', -3, -2);
        
$i++;
        
// Abort if there's no possibility of $str being a jpeg image
        
if (strlen($str) < 20)
            return 
false;
    }
    if (
$i 0
        
// Write changes, if anything was removed 
        
return (file_put_contents($filename$str) == strlen($str));
    else
        
// Return true if nothing changed
        
return true;
}
?>

Last updated: Sat Jun 14 20:02:44 CEST 2008

Valid XHTML 1.0! Valid HTML 3.2!