I run a blogging site that allowed users to publish images from their cell phones. For some reason, the nokia 3220 produces jpegs with extrandeous data before the EOF 0xFFF9
I wrote this class to allow you to fix the images so that they can be used with GD to resize and manipulate. Without applying the fix both GD and gimp report errors for the file. If basically keeps eating bytes from the junk part till the file is a valid jpeg. Here is an example bunk pic written by a nokia 3220 that you cna test it with http://www.shawnrider.com/moblog/cache/0854747001121624103.jpg
/*
Author: Paul Visco
Hompage: http://www.elmwoodstrip.com?u=paul
AIM: paulsidekick
Notes: The file allows you fix the jpegs created by the Nokia 3220 picture phone so that they can be manipulated using the GD library with PHP.
Usage: Simply instanitiate the class and then call the fix method for each image.
e.g.
$nokia = new nokia;
$nokia->debug ="y";
$nokia->fix("yourpic.jpg");
*/
class nokia
{
public $file;
public $debug = "n";
public $dir_name = "";
private $img; //the image created from the string
private $str;
function fix($file)
{
//set the file to fix
$this->file = $file;
//load the file into a string
$this->str = file_get_contents($this->file);
//test to see if it is a nokia image or if it has been corrupted previously
if (substr_count($this->str, chr(0x28).chr(0x36).chr(0x28).chr(0x2B)) == 0 || @imagecreatefromstring($this->str))
{
if ($this->debug =="y")
{
echo "\n<br />".$this->file." is not a corrupted Nokia pic";
}
return true;
}
//make a directory for fixed images if it doesn't exist and is specified
if(!empty($this->dir_name) && !is_dir($this->dir_name))
{
@mkdir($this->dir_name, 0777);
}
//strip out the funk e crap from the file
$this->eat($this->str);
//write the file back to itself
file_put_contents($this->dir_name.$this->file, $this->str);
//return true for fixed
return true;
}
function eat()
{
//check the image
$this->img = @imagecreatefromstring($this->str);
//if the image doesn't work then keep striping out crap
while(!$this->img)
{
//cut off the bad bytes one by one
$this->str= substr_replace($this->str, "", -3, -2);
//check the image again
$this->img = @imagecreatefromstring($this->str);
}
if ($this->debug =="y")
{
//notify the user it's fixed
echo "\n<br />Nasty bits eaten!! ".$this->file." is fixed now thanks to p:labs!";
}
return true;
}
}