I am trying to show the image uploaded by the user in a user profile page. The image is being uploaded successfully but shows this error when displayed: "the image can't not be displayed because it contains errors".
My upload code is:
<?php
session_start();
require_once("config.php");
header ("Content-type: image/jpg" );
if ( $_GET["id"] != "" )
{
if ( file_exists ( "media/userphotos/".$_GET["id"].".jpg" ) )
$imageToShow = SITEURL."media/userphotos/".$_GET["id"].".jpg";
else
{
$imgNumber = rand ( 1, 5 );
$imageToShow = SITEURL."images/nimg$imgNumber.jpg";
}
}
if ( strchr ( $imageToShow , ".gif" ) )
$image = imagecreatefromgif ( $imageToShow );
else
$image = imagecreatefromjpeg ( $imageToShow );
list ( $width, $height ) = getimagesize ( $imageToShow );
$diffWidth = 1;
$diffHeight = 1;
if ( $width > $height )
{
if ( $width > 130 )
{
$diffWidth = 1 - ( ( $width-130 ) / $width ) ;
$diffHeight = $diffWidth ;
}
}
else
{
if ( $height > 110 )
{
$diffHeight = 1 - ( ( $height-110 ) / $height ) ;
$diffWidth = $diffHeight ;
}
}
$modwidth = $width * $diffWidth ;
$modheight = $height * $diffHeight ;
//$modwidth = 130 ;
//$modheight = 110 ;
// Resizing the Image
$tn = imagecreatetruecolor ( $modwidth, $modheight ) ;
imagecopyresampled ( $tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height ) ;
/******** this line outputs image as thumbnail or not ( conditioned ) *********/
if ( $tn )
imagejpeg( $tn , "" , 99 ) ;
else
imagejpeg( $image , "" , 99 ) ;
imagedestroy ( $image ) ;
?>
To show the image I use:
<img src="<?php echo SITEURL."userimage.php?id=".$userDetails["UserID"] ?>" style="width:120px; padding:2px; border:#999999 1px solid;" />
Can anybody explain why the image won't show?
Ok I see 2 problems...
First a dodgy char and the end of the file... '`' not sure if that is in the actual code or not... make sure it isn't
Secondly, change
if ( $tn )
imagejpeg( $tn , "" , 99 ) ;
else
imagejpeg( $image , "" , 99 ) ;
To
if ( $tn )
imagejpeg( $tn , NULL , 99 ) ;
else
imagejpeg( $image , NULL , 99 ) ;
From imagejpeg
To skip this argument in order to provide the quality parameter, use NULL.
I believe if you put an empty string it'll attempt to save the image as a file, rather than send as a stream.