Core Coding®

PHP JPEG Progressive Check

  PHP JPEG Progressive Check
A PHP script to determine if a jpeg is progressive (Flash 7 can't display progressive pics) and if so, it resaves it in a non-progressive format.
<?php
// this code (C) Musicman 2001
// this code is GPL
// feel free to obtain a copy of LICENSE.TXT from
// the Free Software Foundation
// and read up the details

define("MARKER", 0xff);
define("SOI", 0xd8);
define("EOI", 0xd9);
define("JFIF", 0xe0);
define("APP", 0xe0);
define("QUANT", 0xdb);
define("HUFF", 0xc4);
define("SOF0", 0xc0);
define("SOF1", 0xc1);
define("SOF2", 0xc2);
define("SOS", 0xda);
define("ED", 0xed);
define("EE", 0xee);
define("DD", 0xdd);
function
u16($fp)
{
$res = ord(fread($fp, 1)) << 8;
$res += ord(fread($fp, 1));
return
$res;
}
function
jpeghdr($fp)
{ if(
ord(fread($fp, 1)) != MARKER || ord(fread($fp, 1)) != SOI)
return
false;
$length = 2;
$res = false;
while(
ord(fread($fp, 1)) == MARKER)
{
$cod = ord(fread($fp, 1));
if(
$cod == SOS)
break;
$len = u16($fp);
if(
$cod == QUANT || $cod == HUFF || $cod == DD || $cod == SOF0 || $cod == SOF1)
$length += 2 + $len;
if(
$cod == SOF0 || $cod == SOF1)
{
$len -= 5;
$res = array();
$res["prec"] = ord(fread($fp, 1));
$res["height"] = u16($fp);
$res["width"] = u16($fp);
}
else if(
$cod == SOF2)
return
false;
else if(
$cod != JFIF && $cod != QUANT && $cod != HUFF && $cod != DD && ($cod & APP) != APP)
return
false;
fseek($fp, $len-2, 1);
}
if(
$cod == SOS)
{
$pos = ftell($fp);
fseek($fp, 0, 2);
$length += ftell($fp) - $pos;
$res['length'] = $length;
return
$res;
}
return
false;
}
function
testjpeg($name)
{ if(!(
$fp = @fopen($name, "rb")))
return
false;
$res = jpeghdr($fp);
fclose($fp);
return
$res;
}

function
readjpeg($fp) { rewind($fp);
if(
ord(fread($fp, 1)) != MARKER || ord(fread($fp, 1)) != SOI)
return
false;
$buf = chr(MARKER) . chr(SOI);
while(
ord(fread($fp, 1)) == MARKER)
{
$cod = ord(fread($fp, 1));
if(
$cod == SOS)
break;
if(
$cod == QUANT || $cod == HUFF || $cod == DD || $cod == SOF0 || $cod == SOF1)
{
$len = u16($fp);
$buf .= chr(MARKER) . chr($cod);
$buf .= chr($len >> 8);
$buf .= chr($len & 0xff);
$buf .= fread($fp, $len-2);
}
else
{
$len = u16($fp);
fseek($fp, $len-2, 1);
}
}
$buf .= chr(MARKER) . chr($cod);
while(
$next = fread($fp, 4096))
$buf .= $next;
return
$buf;
}

// $pic is a local filename path to the image.
if ($jh = testjpeg($pic)) {
echo
'good';
} else {
echo
'Could be saved as progressive - fixing.';

$imagedata = getimagesize($pic);
$width = $imagedata[0];
$height = $imagedata[1];

$im2 = ImageCreateTrueColor($width, $height);
$image = ImageCreateFromJpeg($pic);
imageCopyResampled($im2, $image, 0, 0, 0, 0, $width, $height, $imagedata[0], $imagedata[1]);
@
imagejpeg($im2, $pic);
}


Go back to resources
Home Mail GitHub