Page 1 of 1

Image uploading

Posted: Wed Aug 03, 2011 1:27 pm
by SabirAhmed
Hi guys, I'm really stumped on this point and i hope someone can help me.

Basically I have set up some php coding to allow the user to upload pictures, up to 10, and depending on the size of them the PHP should make copies of the image and resize it.

I've set up the form and the PHP coding to actually resize the images is performed by an include.

The problem I am getting is that when I try and upoload a picture which is 'large' (more than 1500 pixels height), it will upload the picture, but it will not upload the next picture if the next picture is a medium - less than 1500 height).

If I upload all pictures which are medium in size then it works fine ... it is just when I include a large picture that some medium-sized subsequent pictures do not get uploaded.

CODE TO RESIZE IMAGES BASED ON SIZE - IT IS AN INCLUDE

Code: Select all


<?php
$newimage = "";
$newtarget = ""; # from now TARGET_PATH1 is not going to change with alterations, it needs to be specified at the end that $TARGET_PATH1_MED is $NEWTARGETPATH_MED etc before this page is finished to allow for placing of all files together at end

$newfile_type = "";
$new_image_ = "";
$new_height = "";
$new_width = "";
$newnew_image_med = "";
$newnew_image_thumb = "";
$newnew_image_large = "";
$newresized_image_med = "";
$newresized_image_thumb = "";
$newresized_image_large = "";

$NEWTARGETPATH_MED = "";
$NEWTARGETPATH_THUMB = "";
$NEWTARGETPATH_LARGE = "";

$newfile_type = "";

$newimage = $image4;
$newtarget = $TARGET_PATH4; # from now TARGET_PATH1 is not going to change with alterations, it needs to be specified at the end that $TARGET_PATH1_MED is $NEWTARGETPATH_MED etc before this page is finished to allow for placing of all files together at end

$newfile_type = $file_type4;
$new_image_ = $new_img4;
$new_height = $height4;
$new_width = $width4;
$newnew_image_med = $new_img4_med;
$newnew_image_thumb = $new_img4_thumb;
$newresized_image_med = $resized_img4_med;
$newresized_image_thumb = $resized_img4_thumb;


$NEWTARGETPATH_MED = $TARGET_PATH4_med;
$NEWTARGETPATH_THUMB = $TARGET_PATH4_thumb;

$newfile_type = $_FILES['image4']['type'];



$Upperheight = 1500;
$Upperwidth = 2000;
$Med_height = 200;
$Med_width = 533;
$large_height = 1500;
$large_width = 2000;

// Build our target path full string. This is where the file will be moved do
// i.e. images/picture.jpg
$newtarget = $newtarget.$newimage['name'];

// Check to make sure that our file is actually an image
// You check the file type instead of the extension because the extension can easily be faked
if (!is_valid_type($newimage))
{
$errorstring = $errorstring."Upload a jpeg, gif, or bmpWER, ";
$ivalue = $ivalue.$image;
}

// Here we check to see if a file with that name already exists
// You could get past filename problems by appending a timestamp to the filename and then continuing
if (file_exists($newtarget))
{
$errorstring = $errorstring."A file with that name already existsERW".$newimage['name'];
$ivalue = $ivalue.$image;
}

//RESIZING IMAGES //

if($newfile_type == "image/pjpeg" || $newfile_type == "image/jpeg"){
$new_image_ = imagecreatefromjpeg($newimage['tmp_name']);
}elseif($newfile_type == "image/x-png" || $newfile_type == "image/png"){
$new_image_ = imagecreatefrompng($newimage['tmp_name']);
}elseif($newfile_type == "image/gif"){
$new_image_ = imagecreatefromgif($newimage['tmp_name']);} // FILE TYPE CHECK FOR 1ST IMAGE

//list the width and height and keep the height ratio.
$new_height = imagesy($new_image_);
$new_width = imagesx ($new_image_);

if ($new_height > 0 && $new_height < $Med_height)
{
$errorstring = $errorstring."The file is too medium ";
$ivalue = $ivalue.$image;
}

if ($new_height > 1500)
{
$newresized_image_large = $resized_img3_large;
$newnew_image_large = $new_img3_large;
$NEWTARGETPATH_LARGE = $TARGET_PATH3_large;
}

if ($new_height > $Med_height)
{
if($newfile_type == "image/pjpeg" || $newfile_type == "image/jpeg")
{$newnew_image_med = imagecreatefromjpeg($newimage['tmp_name']);}
elseif($newfile_type == "image/x-png" || $newfile_type == "image/png")
{$newnew_image_med = imagecreatefrompng($newimage['tmp_name']);}
elseif($newfile_type == "image/gif")
{$newnew_image_med = imagecreatefromgif($newimage['tmp_name']);} // FILE TYPE CHECK FOR MED

if (function_exists(imagecreatetruecolor))
{$newresized_image_med = imagecreatetruecolor($Med_width,$Med_height);}
imagecopyresampled($newresized_image_med, $newnew_image_med, 0, 0, 0, 0, $Med_width, $Med_height, $new_width, $new_height);

# Now put a WATERMARK on

$watermark = imagecreatefrompng('watermark.png');

$watermark_width = imagesx($watermark);
$watermark_height = imagesy($watermark);
$image = imagecreatetruecolor($watermark_width, $watermark_height);

$dest_x = $Med_width - $watermark_width - 7;
$dest_y = $Med_height - $watermark_height - 5;

imagecopymerge($newresized_image_med, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height, 100);

$NEWTARGETPATH_MED = $newtarget."_med_".$newimage['name'];
$NEWTARGETPATH_LARGE = $newtarget."_large_".$newimage['name'];
/*

IN SQL YOU SHOULD SAVE IMAGE NAME and IMAGE HEIGHT ONLY,

THEN PULL IT UP IN LIGHTBOX BY SAYING, for example:

A H-REF: <?php echo $NAME."_med".$NAME; ?>

IF (IMAGE1_HEIGHT >350)
{A H-REF: <?php echo $NAME."_large".$NAME; ?> ) */

if($newfile_type == "image/pjpeg" || $newfile_type == "image/jpeg")
{$newnew_image_thumb = imagecreatefromjpeg($newimage['tmp_name']);}
elseif($newfile_type == "image/x-png" || $newfile_type == "image/png")
{$newnew_image_thumb = imagecreatefrompng($newimage['tmp_name']);}
elseif($newfile_type == "image/gif")
{$newnew_image_thumb = imagecreatefromgif($newimage['tmp_name']);} // FILE TYPE CHECK FOR THUMB

if (function_exists(imagecreatetruecolor))
{$newresized_image_thumb = imagecreatetruecolor(140,100);}
else
{$errorstring = $errorstring."GD Library version 2+ Bot available ";
$ivalue = $ivalue.$image; }

//the resizing is going on here!
if (
imagecopyresampled($newresized_image_thumb, $newnew_image_thumb, 0, 0, 0, 0, 140, 100, $new_width, $new_height))
{}
else
{ $errorstring = $errorstring."Couldnt Uplaod Files3 ";
$ivalue = $ivalue.$image; }

$NEWTARGETPATH_THUMB = $newtarget."_thumb_".$image1['name'];


// Lets attempt to move the file from its temporary directory to its new home
if (
ImageJpeg($newresized_image_med, $NEWTARGETPATH_MED, 100) &&
ImageJpeg($newresized_image_thumb, $NEWTARGETPATH_THUMB, 100))
{
}
else
{
// A common cause of file moving failures is because of
// bad permissions on the directory attempting to be written to
// Make sure you chmod the directory to be writeable
$errorstring = $errorstring."Couldnt Uplaod Files4 $TARGET_PATH1";
$ivalue = $ivalue.$image;
} #REMEMBER TO REMOVE THIS TO THE OTHER IMAGE UPLOADING FINAL SECTION



}

if ($new_height > $large_height)
{
if($newfile_type == "image/pjpeg" || $newfile_type == "image/jpeg")
{$newnew_image_large = imagecreatefromjpeg($newimage['tmp_name']);}
elseif($newfile_type == "image/x-png" || $newfile_type == "image/png")
{$newnew_image_large = imagecreatefrompng($newimage['tmp_name']);}
elseif($newfile_type == "image/gif")
{$newnew_image_large = imagecreatefromgif($newimage['tmp_name']);} // FILE TYPE CHECK FOR LARGE

if (function_exists(imagecreatetruecolor))
{$newresized_image_large = imagecreatetruecolor($large_width,$large_height);}
imagecopyresampled($newresized_image_large, $newnew_image_large, 0, 0, 0, 0, $large_width, $large_height, $new_width, $new_height);

$watermark2 = imagecreatefrompng('watermark.png');

$watermark_width2 = imagesx($watermark2);
$watermark_height2 = imagesy($watermark2);
$image2 = imagecreatetruecolor($watermark_width2, $watermark_height2);

$bufferw = ($large_width/100);
$bufferh = ($large_height/100) * 2.5;
$dest_x2 = $large_width - $watermark_width2 - $bufferw;
$dest_y2 = $large_height - $watermark_height2 - $bufferh;

imagecopymerge($newresized_image_large, $watermark2, $dest_x2, $dest_y2, 0, 0, $watermark_width2, $watermark_height2, 60);

if (
ImageJpeg($newresized_image_large, $NEWTARGETPATH_LARGE, 100)
)
{
}
else
{
// A common cause of file moving failures is because of
// bad permissions on the directory attempting to be written to
// Make sure you chmod the directory to be writeable
$errorstring = $errorstring."Couldnt Uplaod Files42 $TARGET_PATH1";
$ivalue = $ivalue.$image;
}
}
?>

... This is the code for image four in particular, all other images follow this coding aswell.

And here's the code used in the html form image upload page

Code: Select all


[syntax=php]

if($_POST['submit'])

{
// Start a session for error reporting
session_start();

// Call our connection file
# require("includes/conn.php");


$errorstring = ""; //default value of error string
$pvalue = "";
$nvalue = "";
$dvalue = "";
$ivalue = "";
$checkm = "";
$checkf = "";
$checkb = "";
$checkl = "";
$checkn = "";
$checkm = "";

// Check to see if the type of file uploaded is a valid image type
function is_valid_type($file)
{
// This is an array that holds all the valid image MIME types
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif");

if (in_array($file['type'], $valid_types))
return 1;
return 0;
}

// Just a short function that prints out the contents of an array in a manner that's easy to read
// I used this function during debugging but it serves no purpose at run time for this example
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}

// Set some constants

// This variable is the path to the image folder where all the images are going to be stored
// Note that there is a trailing forward slash
$TARGET_PATH1 = "gchomeimages2/";
$TARGET_PATH2 = "gchomeimages2/";
$TARGET_PATH3 = "gchomeimages2/";
$TARGET_PATH4 = "gchomeimages2/";
$TARGET_PATH5 = "gchomeimages2/";
$TARGET_PATH6 = "gchomeimages2/";
$TARGET_PATH7 = "gchomeimages2/";
$TARGET_PATH8 = "gchomeimages2/";

// Get our POSTed variables
$Name = $_POST['Name'];
$Promoter = $_POST['Promoter'];
$Town = $_POST['Town'];
$Gender = $_POST['gender'];
$Description = $_POST['Description'];
$Something = $_POST['Something'];
$image1 = $_FILES['image1'];
$image2 = $_FILES['image2'];
$image3 = $_FILES['image3'];
$image4 = $_FILES['image4'];
$image5 = $_FILES['image5'];
$image6 = $_FILES['image6'];
$image7 = $_FILES['image7'];
$image8 = $_FILES['image8'];

if (!$image1['name'])
{
$errorstring = $errorstring."Upload a jpeg, gif, or bmp,utru ";
$ivalue = $ivalue.$image1;
}
else
{
$image1_height = imagesy ($image1);
$image1_width = imagesx ($image1);
include ("gchomesimageuploaderdiff_image1.php");
}

if (!$image2['name'])
{
}
else
{
$image2_height = imagesy ($image2);
$image2_width = imagesx ($image2);
include ("gchomesimageuploaderdiff_image2.php");
}

if (!$image3['name'])
{
}
else
{
$image3_height = imagesy ($image3);
$image3_width = imagesx ($image3);
include ("gchomesimageuploaderdiff_image3.php");
}

if (!$image4['name'])
{
}
else
{
$image4_height = imagesy ($image4);
$image4_width = imagesx ($image4);
include ("gchomesimageuploaderdiff_image4.php");
}

[/syntax]

... The code goes on like this for all 10 pictures .


Can someone please help me? I've looked around for ages and cannot for the life of me work out what is wrong

Re: Image uploading

Posted: Wed Aug 03, 2011 1:54 pm
by genix2011
Hi,

I'll look over it, but it'll take some time.

Re: Image uploading

Posted: Wed Aug 03, 2011 2:15 pm
by SabirAhmed
oh ok, thanks!

Re: Image uploading

Posted: Wed Aug 03, 2011 2:25 pm
by SabirAhmed
Also, if you like i can give u a version with the redundant code stripped. Would hav offered this earlier but got the feeling this is something u can do in seconds anyway

Re: Image uploading

Posted: Wed Aug 03, 2011 3:30 pm
by genix2011
Hi,

So I rewrote your code, removed all redundant code and polished it a bit, but you have to further adjust it. (integrate form etc)

Code: Select all

<?php
session_start();

/*
 * Create your form for multiple upload like that:
 *
 * <form action="" method="post" enctype="multipart/form-data">
 *     <input type="file" name="images[]" />
 *     <input type="file" name="images[]" />
 *     <input type="file" name="images[]" />
 *     <input type="submit" name="submit" value="Send" />
 * </form>
 */

$ERRORS = array();

if (!function_exists('imagecreatetruecolor')){
    die("GD Library version 2+ is required!");
}

// Define some constants
define('TARGET_PATH',  'gchomeimages2/');

define('UPPER_HEIGHT', 1500);
define('UPPER_WIDTH',  2000);

define('MED_HEIGHT',   200);
define('MED_WIDTH',    533);

define('LARGE_HEIGHT', 1500);
define('LARGE_WIDTH',  2000);

define('THUMB_HEIGHT', 100);
define('THUMB_WIDTH',  140);

function is_valid_type($type){
    $valid_types = array("image/jpg",
                         "image/pjpeg",
                         "image/jpeg",
                         "image/bmp",
                         "image/gif",
                         "image/x-png",
                         "image/png");
    
    if (in_array($type, $valid_types)) return true;

    return false;
}

function createImage($id){
    $imagetype = $_FILES["images"]["type"][$id];
    $tmp_name  = $_FILES["images"]["tmp_name"][$id];
    $image = null;
    switch($imagetype){
        case "image/pjpeg":
        case "image/jpeg":
        case "image/jpg":
            $image = imagecreatefromjpeg($tmp_name);
            break;
        case "image/x-png":
        case "image/png":
            $image = imagecreatefrompng($tmp_name);
            break;
        case "image/gif":
            $image = imagecreatefromgif($tmp_name);
            break;
    }

    return $image;
}

function addWatermark($image, $wmimg, $quality, $bufferw, $bufferh){
    $img_h = imagesy($image);
    $img_w = imagesx($image);
    
    $watermark = imagecreatefrompng($wmimg);
    $watermark_w = imagesx($watermark);
    $watermark_h = imagesy($watermark);

    $x = $img_w - $watermark_w - $bufferw;
    $y = $img_h - $watermark_h - $bufferh;
    
    imagecopymerge($image, $watermark, $x, $y, 0, 0, $watermark_w, $watermark_h, $quality);

    return $image;
}

function resizeImage($image, $w, $h){
    $img_h = imagesy($image);
    $img_w = imagesx($image);
    $img = imagecreatetruecolor($w, $h);

    imagecopyresampled($img, $image,  0, 0, 0, 0, $w, $h, $img_w, $img_h);
    
    return $img;
}

function saveImage($image, $path){
    global $ERRORS;
    if(!ImageJpeg($image, $path, 100)){
        $ERRORS[] = "Image $path couldn't be saved";
        return;
    }
}

function processImage($id){
    global $ERRORS;
    
    // Get some image informations
    $filename =  $_FILES["images"]["name"][$id];
    $name = $filename;

    $img_no = $id + 1;
    
    if(($pos = strpos($filename, '.')) > 0){
        // Remove file-extension from filename
        $name = substr($filename, -$pos);
    }
    
    $imagetarget = TARGET_PATH . $_FILES["images"]["name"][$id];
    $imagetype   = $_FILES["images"]["type"][$id];

    if(!is_valid_type($imagetype)){
        $ERRORS[] = "Image $img_no is a wrong image type. Upload a jpeg, gif or bmp";
        return;
    }

    if(file_exists($imagetarget)){
        $ERRORS[] = "A image with the name $filename already exists in target";
        return;
    }
    
    // using factory to create image
    // automatically checks type and returns the right image
    $image      = createImage($id);

    $img_height = imagesy($image);
    $img_width  = imagesx($image);

    $img_large = null;
    $img_med   = null;
    $img_thumb = null;
    
    if($img_height > 0 && $img_height < MED_HEIGHT){
        $ERRORS[] = "File $img_no is too medium";
        return;
    }

    if($img_height > UPPER_HEIGHT){
        $img_large = resizeImage($image, LARGE_WIDTH, LARGE_HEIGHT);
        $img_large = addWatermark($img_large, "watermark.png", 60, (LARGE_WIDTH / 100), (LARGE_HEIGHT / 100) * 2.5);
        saveImage($img_large, TARGET_PATH. $name . "_large.jpeg");
    }

    if($img_height > MED_HEIGHT){
        $img_med = resizeImage($image, MED_WIDTH, MED_HEIGHT);
        $img_med = addWatermark($img_med, "watermark.png", 100, 7, 5);
        saveImage($img_med, TARGET_PATH . $name . "_med.jpeg");
    }

    $img_thumb = resizeImage($image, THUMB_WIDTH, THUMB_HEIGHT);
    saveImage($img_thumb, TARGET_PATH . $name . "_thumb.jpeg");
}

if($_POST['submit']){
    if(!$_FILES["images"]["name"][0]) {
        die("Upload a jpeg, gif or bmp");
    }
    foreach ($_FILES["images"]["error"] as $key => $error) {
       if ($error == UPLOAD_ERR_OK) {
           // will create thumb, med and large images
           // if imagefile is "image.png" it will create:
           //     image_thumb.jpeg, image_med.jpeg, image_large.jpeg
           //
           processImage($key);
       } else {
           $no_img = $key + 1;
           $ERRORS [] = "File $no_img couldn't be uploaded. ERROR CODE:" . $error;
       }
    }

    $Name = $_POST['Name'];
    $Promoter = $_POST['Promoter'];
    $Town = $_POST['Town'];
    $Gender = $_POST['gender'];
    $Description = $_POST['Description'];
    $Something = $_POST['Something'];

    // print errors
    echo implode($ERRORS, "<br />");
}
// Create form etc. here

?>

Re: Image uploading

Posted: Wed Aug 03, 2011 7:09 pm
by SabirAhmed
Hi genix,

great, thanks for this. I'll plug this in and see how it works.

I was also considering the idea that it could be to do with maximum file size on my php.ini file, since the problem mainly occurs when i try and upload more than 1 'Large' image. I will try that after I have tried your code. Thanks

Re: Image uploading

Posted: Fri Aug 05, 2011 11:15 am
by SabirAhmed
Hi Genix, thanks for the great code. It was very easy to implement too way you wrote it in such a well organized way. Nice!

After significant testing of the form, I Just a quick question I want to ask -

At the moment, if a user only enters two images, for example, it comes up with an error message for all the other 6 inputs. How do i do it so that only image 1 is compulsory, and all other 7 images are optional, so an error message will not show if they do not enter a certain image.

The reason I'm finding this a bit confusing is because i'm not sure where to put an if statement, I've tried different places and it hasn't worked the way I want it to so far, because obviously I still want the error message to show if they enter an image but it just doesnt get uploaded properly for some other reason ... so i dont want to take that error message out completely for all the other images.

What are your thoughts on this? Thanks

Re: Image uploading

Posted: Fri Aug 05, 2011 12:15 pm
by genix2011
Hi,

oh yes didn't think of that, just change the if in $_POST['submit'] to:

Code: Select all

       } elseif($error == UPLOAD_ERR_NO_FILE){
           continue;
       } else {
           $no_img = $key + 1;
           $ERRORS [] = "File $no_img couldn't be uploaded. ERROR CODE:" . $error;
       }
that should do it.

Re: Image uploading

Posted: Tue Aug 09, 2011 6:32 am
by SabirAhmed
Genix - i definitely replie dto this yesterday, onder what happened to it?

Anyway, I just replied to say thanks, and also to let you know that there was something in the code that I had to change slightly to make it work. Just thought you might find it useful to kknow that. I explained the problem fuilly in my previous post (the one which has wierdly dissapeared here?) , but now I dont quite have the time to go into it in detail again. It was just to d with the variable $name not passing through properly, it just had to be replaced by the variable $filename, so it was just a small problem.

Anyway, thanks a lot for the great code. I'll make sure to dissect this and learn as much as I can from it . Thanks!

Re: Image uploading

Posted: Tue Aug 09, 2011 9:02 am
by genix2011
Hi,

always happy to be helpful :)

Greets.

Re: Image uploading

Posted: Wed Oct 05, 2011 5:47 am
by SabirAhmed
Hi,

I recently countered a problem with this coding and was wondering if anyone could help me with it? (or even Genix, if he's still around :))

Basically, I now want to be able to store in the pitcure file names into a My SQL database, but I want to do this all at once. I.e - once it has saved all images into the relevant folder, I want all image names to be stored into the database at once.

The problem I am getting is I am having trouble getting the SQL statement to recognize a file name.

When I am forming the SQL query, which filename would I use for each picture??

Any help would be great, Im lost right now!

Re: Image uploading

Posted: Wed Oct 05, 2011 5:48 am
by SabirAhmed
Hi,

I recently countered a problem with this coding and was wondering if anyone could help me with it? (or even Genix, if he's still around :))

Basically, I now want to be able to store in the pitcure file names into a My SQL database, but I want to do this all at once. I.e - once it has saved all images into the relevant folder, I want all image names to be stored into the database at once.

The problem I am getting is I am having trouble getting the SQL statement to recognize a file name.

When I am forming the SQL query, which filename would I use for each picture??

Any help would be great, Im lost right now!

Re: Image uploading

Posted: Wed Oct 05, 2011 9:45 am
by genix2011
Hello,

yeah I'm still around sometimes :)

You could change the foreach to fill an array with the successfully processed images:

Code: Select all

$processed_imgs=array();
foreach ($_FILES["images"]["error"] as $key => $error) {
       if ($error == UPLOAD_ERR_OK) {
           // will create thumb, med and large images
           // if imagefile is "image.png" it will create:
           //     image_thumb.jpeg, image_med.jpeg, image_large.jpeg
           //
           processImage($key);
           $filename =  $_FILES["images"]["name"][$key];
           $processed_imgs[] = $filename;
       } else {
           $no_img = $key + 1;
           $ERRORS [] = "File $no_img couldn't be uploaded. ERROR CODE:" . $error;
       }
}

//WRITE $processed_imgs into Database

Greets.

Re: Image uploading

Posted: Wed Oct 05, 2011 10:38 am
by SabirAhmed
Hey!

wow, Thanks Genix! You saved my day again it seems, nice :)