Jump to content

I am not getting an image save using imagejpeg()


jakebur01

Recommended Posts

$watername is writable and when I echo $watername it shows the full path and filename to the image. The upload process that goes on before this watermark code does fine and the image and thumbnail is going into the directory fine. The image outputs to the browser fine with the watermark logo when I uncomment that part of the code out. I'm not sure why it's not saving/replacing the file in the directory.  I'm also not getting any errors when I turn reporting E_ALL on.

 

It does work when I create a blank test page with only watermark part of the code and manually type in the paths.

<?php
error_reporting(E_ALL);

$listingid = 0;
$primaryimage=0;

$valid_formats = array("jpg", "png", "gif", "bmp");
$max_file_size = 100 * 1024 * 1024; //100 mb
$path = "UploadImages/test/images/"; // Upload directory
$count = 0;

 //Some Settings
$ThumbSquareSize        = 167; //Thumbnail will be 200x200
$BigImageMaxSize        = 800; //Image Maximum height or width
$ThumbPrefix            = "thumb_"; //Normal thumb Prefix
$DestinationDirectory   = "UploadImages/test/images/"; //Upload Directory ends with / (slash)
$Quality                = 90;

ini_set('memory_limit', '-1'); // maximum memory!


if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
    // Loop $_FILES to execute all files
    //foreach ($_FILES['files']['name'] as $f => $name) { 





    // some information about image we need later.
$ImageName      = $_FILES['files']['name'];
$ImageSize      = $_FILES['files']['size'];
$TempSrc        = $_FILES['files']['tmp_name'];
$ImageType      = $_FILES['files']['type'];


if (is_array($ImageName)) 
{
    $c = count($ImageName);



    for ($i=0; $i < $c; $i++)
    {
        $processImage           = true; 
        $RandomNumber           = rand(0, 9999999999);  // We need same random name for both files.

        if(!isset($ImageName[$i]) || !is_uploaded_file($TempSrc[$i]))
        {
            echo '<h3>Error occurred while trying to process'.$ImageName[$i].', may be file too big!</h3>'; //output error
        }
        else
        {
            //Validate file + create image from uploaded file.
            switch(strtolower($ImageType[$i]))
            {
                case 'image/png':
                    $CreatedImage = imagecreatefrompng($TempSrc[$i]);
                    break;
                case 'image/gif':
                    $CreatedImage = imagecreatefromgif($TempSrc[$i]);
                    break;
                case 'image/jpeg':
                case 'image/pjpeg':
                    $CreatedImage = imagecreatefromjpeg($TempSrc[$i]);
                    break;
                default:
                    $processImage = false; //image format is not supported!
            }
            //get Image Size
            list($CurWidth,$CurHeight)=getimagesize($TempSrc[$i]);

            //Get file extension from Image name, this will be re-added after random name
            $ImageExt = substr($ImageName[$i], strrpos($ImageName[$i], '.'));
            $ImageExt = str_replace('.','',$ImageExt);

            //Construct a new image name (with random number added) for our new image.
            $NewImageName = $RandomNumber.'.'.$ImageExt;

            //Set the Destination Image path with Random Name
            $thumb_DestRandImageName    = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumb name
            $DestRandImageName          = $DestinationDirectory.$NewImageName; //Name for Big Image
$watername = $DestRandImageName;

            resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]);


// Load the stamp and the photo to apply the watermark to
$stamp = imagecreatefrompng('images/logo.png');
$im = imagecreatefromjpeg("$watername");

// Set the margins for the stamp and get the height/width of the stamp image
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);

// Copy the stamp image onto our photo using the margin offsets and the photo 
// width to calculate positioning of the stamp. 
imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));

// Output and free memory
//header('Content-type: image/png');
//imagepng($im);

/*
$filename = "$watername";
if (is_writable($filename)) {
    echo 'The file is writable';
} else {
    echo 'The file is not writable';
} */

//echo "$watername";


imagejpeg($im, $watername , 90);



imagedestroy($im);





            //Resize image to our Specified Size by calling resizeImage function.
            if($processImage && resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]))
            {
                //Create a square Thumbnail right after, this time we are using cropImage() function


                if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]))
                    {
                        echo 'Error Creating thumbnail';
                    }
            }

                    /*At this point we have succesfully resized and created thumbnail image
                    We can render image to user's browser or store information in the database
                    For demo, we are going to output results on browser.


                    //Get New Image Size
                //  list($ResizedWidth,$ResizedHeight)=getimagesize($DestRandImageName);


                    echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
                    echo '<tr>';
                    echo '<td align="center"><img src="uploads/'.$ThumbPrefix.$NewImageName.'" alt="Thumbnail" height="'.$ThumbSquareSize.'" width="'.$ThumbSquareSize.'"></td>';
                    echo '</tr><tr>';
                    echo '<td align="center"><img src="uploads/'.$NewImageName.'" alt="Resized Image" height="'.$ResizedHeight.'" width="'.$ResizedWidth.'"></td>';
                    echo '</tr>';
                    echo '</table>';
                    /*
                    // Insert info into database table!
                    mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath)
                    VALUES ($DestRandImageName, $thumb_DestRandImageName, 'uploads/')");


            }else{
                echo '<h3>Error occurred while trying to process <strong>'.$ImageName[$i].'</strong>! Please check if file is supported</h3>'; //output error
            }   */

        }

    }

    }



/*    
        if ($_FILES['files']['error'][$f] == 4) {
            continue; // Skip file if any error found
        }          
        if ($_FILES['files']['error'][$f] == 0) {              
            if ($_FILES['files']['size'][$f] > $max_file_size) {
                $message[] = "$name is too large!.";
                continue; // Skip large files
            }
            elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
                $message[] = "$name is not a valid format";
                continue; // Skip invalid file formats
            }
            else{ // No error found! Move uploaded files 
            $ext = end(explode('.', $name));
            $newname = rand(10,10000) . rand(10,1000) . "." . "$ext";
                if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$newname)) {
                    $count++; // Number of successfully uploaded files
                }
            }
        }  */
    //}  
}



// This function will proportionally resize image 
function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)
{
    //Check Image size is not 0
    if($CurWidth <= 0 || $CurHeight <= 0) 
    {
        return false;
    }

    //Construct a proportional size of new image
    $ImageScale         = min($MaxSize/$CurWidth, $MaxSize/$CurHeight); 
    $NewWidth           = ceil($ImageScale*$CurWidth);
    $NewHeight          = ceil($ImageScale*$CurHeight);

    if($CurWidth < $NewWidth || $CurHeight < $NewHeight)
    {
        $NewWidth = $CurWidth;
        $NewHeight = $CurHeight;
    }
    $NewCanves  = imagecreatetruecolor($NewWidth, $NewHeight);
    // Resize Image
    if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))
    {
        switch(strtolower($ImageType))
        {
            case 'image/png':
                imagepng($NewCanves,$DestFolder);
                break;
            case 'image/gif':
                imagegif($NewCanves,$DestFolder);
                break;          
            case 'image/jpeg':
            case 'image/pjpeg':
                imagejpeg($NewCanves,$DestFolder,$Quality);
                break;
            default:
                return false;
        }
    if(is_resource($NewCanves)) { 




      imagedestroy($NewCanves); 
    } 
    return true;
    }

}


//This function corps image to create exact square images, no matter what its original size!
function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType)
{    
    //Check Image size is not 0
    if($CurWidth <= 0 || $CurHeight <= 0) 
    {
        return false;
    }

    //abeautifulsite.net has excellent article about "Cropping an Image to Make Square"
    //http://www.abeautifulsite.net/blog/2009/08/cropping-an-image-to-make-square-thumbnails-in-php/
    if($CurWidth>$CurHeight)
    {
        $y_offset = 0;
        $x_offset = ($CurWidth - $CurHeight) / 2;
        $square_size    = $CurWidth - ($x_offset * 2);
    }else{
        $x_offset = 0;
        $y_offset = ($CurHeight - $CurWidth) / 2;
        $square_size = $CurHeight - ($y_offset * 2);
    }

    $NewCanves  = imagecreatetruecolor($iSize, $iSize); 
    if(imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size))
    {
        switch(strtolower($ImageType))
        {
            case 'image/png':
                imagepng($NewCanves,$DestFolder);
                break;
            case 'image/gif':
                imagegif($NewCanves,$DestFolder);
                break;          
            case 'image/jpeg':
            case 'image/pjpeg':
                imagejpeg($NewCanves,$DestFolder,$Quality);
                break;
            default:
                return false;
        }
    if(is_resource($NewCanves)) { 
      imagedestroy($NewCanves); 
    } 
    return true;

    }

}
?>

P.S. Where did everybody go?  It's been a few years since I was last on here, but there was a lot more activity back then.

Link to comment
Share on other sites

What does

$filename = "$watername";
if (is_writable(dirname($filename))) {
    echo 'The file is writable';
} else {
    echo 'The file is not writable';
}

//echo "$watername";


imagejpeg($im, $watername , 90);
say?

 

Where did everybody go?  It's been a few years since I was last on here, but there was a lot more activity back then.

:psychic: PHP's not as popular as it used to be. Forums aren't as popular as they used to be. And as time goes by, more and more questions can be answered through Google.
Link to comment
Share on other sites

The file is writable

 

 

When I take away the rest of the upload code and put the watermark code on it's on page and manually enter paths for the variables it overrites the image in the directory with the watermarked image fine.  There must be something in my surrounding upload code that's throwing a wrench in things.

Link to comment
Share on other sites

The file is writable

 

 

When I take away the rest of the upload code and put the watermark code on it's on page and manually enter paths for the variables it overrites the image in the directory with the watermarked image fine.  There must be something in my surrounding upload code that's throwing a wrench in things.

When you manually enter the path are you putting in relative or full path?

Link to comment
Share on other sites

You first say the image and thumbnail are going into the directory (?).  But then you say the file is not being saved.  What are we talking about?

 

PS - see my signature to find the missing line you need for error checking displaying

Link to comment
Share on other sites

This a regular image upload script I've had and used for a long time.  The time has come where I need to add a watermark on images for a particular site.  The image upload part is working correctly, meaning the regular upload script puts an image and thumbnail into the directory.

 

I'm attempting to add in this watermark code to watermark the image after it has been resized and put in the directory.  You'll see I added the watermark code in after the resizeImage function of the upload script.

 

However, the watermark code is not taking the image and resaving it to the directory.  It will in the script above output it to the browser if I comment out the imagejpeg and uncomment the header and imgpng, etc.

 

If I take the watermark code alone and put it in a separate test.php and key in the relative paths to the image that was uploaded using the upload script, it will work and resave the image with the watermark.

 

So, there must be something in the upload script that is conflicting with the watermark script I've added in.  When I get home I'll try repositioning it.  I may try moving it to after the thumbnail is created and see if it works there.

Link to comment
Share on other sites

I could try it.  Although, it doesn't have any trouble replacing it in the standalone test script without the upload code.

 

Thank's for pointing that out.  I'll determine the filetype and change the image***() accordingly.

 

 

I wonder if it is still processing the image when it is trying to access it.  In other words, when the watermark script is trying to access the image, it doesn't see it because the upload script hasn't finished creating it?

Link to comment
Share on other sites

I moved it below the :

	//Resize image to our Specified Size by calling resizeImage function.
			if($processImage && resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]))
			{
				//Create a square Thumbnail right after, this time we are using cropImage() function
			
			
				if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]))
					{
						echo 'Error Creating thumbnail';
					}
			}
				

Now it works!

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.