1

I am trying to convert a JPG (well any image) to PNG. I have an HTML form that posts the image just fine to the server. I need to rename that file and also convert it to PNG. Later in my code after I do a related table database insert I rename the file yet again to append the record ID to the file name to ensure its uniqueness.

I am more of an objective C programmer then PHP, so i'm struggling here with this code I have found in other questions that does not seem to work for me.

Here is print_r($_FILES);

Array ( [image] => Array ( [name] => BBnL9Ho.jpg [type] => image/jpeg [tmp_name] => /tmp/phphhqHam [error] => 0 [size] => 1636 ) )

So, I want to convert it to PNG and rename BBnL9Ho.jpg to image1.png. I have tried using the following code, but to no avail:

$newfileName = imagepng(imagecreatefromjpeg($_FILES['image']['tmp_name']), "image1.png");

Later after I do a related database table INSERT, I change the name again and append the ID of the related database record (I store the filename in separate table then rest of form data due to one to many relationship):

$fileName="$lastinsertID".$newfileName;

Then I INSERT that name into the database which enters correctly. I then need to move the file to an uploads directory which I attempt to do like so:

move_uploaded_file("$fileName",$dir . $fileName);

Here is where my problem is. The file does not move AND when I do a check on the attributes of the file, it seems it did not actually convert the file. I use this to check the type:

$fileType = $_FILES["image"]["type"];

and it still shows it is a JPG. I must be missing something very obvious but I would appreciate some assistance.

Thank you very much.

miken32
  • 42,008
  • 16
  • 111
  • 154
mreynol
  • 309
  • 3
  • 17

1 Answers1

2

Use the following script to convert any image(JPEG, PNG and GIF) to PNG format. Go through the following script carefully, I have added comments at every critical step.

// $dir specifies the directory where you upload your image files

// get the file by it's temporary name
$tmp_file_name = $_FILES['image']['tmp_name'];

// get the file extension
$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));

// specify the whole path here
$actual_file_name = $dir . basename($_FILES['image']['name'], "." . $ext) . ".png";

// check whether a valid image is uploaded or not
if(getimagesize($tmp_file_name)){

    // get the mime type of the uploaded image
    $image_array = getimagesize($tmp_file_name);
    $mime_type = $image_array['mime'];

    // get the height and width of the uploaded image
    list($width_orig, $height_orig) = getimagesize($tmp_file_name);
    $width = $width_orig;
    $height = $height_orig;

    if($mime_type == "image/gif"){
        // create a new true color image
        if($image_p = imagecreatetruecolor($width, $height)){

            // create a new image from file
            if($image = imagecreatefromgif($tmp_file_name)){

                // copy and resize part of an image with resampling
                if(imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig)){

                    if(imagepng($image_p, $actual_file_name, 0)){
                        // image is successfully uploaded
                        // free resources
                        imagedestroy($image_p);
                        imagedestroy($image);

                        // perform the insert operation and get the last inserted id
                        // $lastinsertID = XXXX

                        // new file name
                        $filename = $dir . $lastinsertID . basename($_FILES['image']['name'], "." . $ext) . ".png";

                        //move the file to your desired location
                        if(rename($actual_file_name, $filename)){
                            echo "success";
                        }else{
                            echo "error";
                        }

                    }else{
                        //Destroy both image resource handler
                        imagedestroy($image);
                        imagedestroy($image_p);
                        echo "Error";
                    }
                }else{
                    //Destroy both image resource handlers
                    imagedestroy($image);
                    imagedestroy($image_p);
                    echo "Error";
                }
            }else{
                //destroy $image_p image resource handler
                imagedestroy($image_p);
                echo "Error";
            }
        }else{
            echo "Error";
        }
    }elseif($mime_type == "image/png"){
        // the uploaded image is already in .png format
        if(move_uploaded_file($tmp_file_name, $actual_file_name)){

            // perform the insert operation and get the last inserted id
            // $lastinsertID = XXXX

            // new file name
            $filename = $dir . $lastinsertID . $_FILES['image']['name'];

            //move the file to your desired location
            if(rename($actual_file_name, $filename)){
                echo "success";
            }else{
                echo "error";
            }

        }else{
            echo "error";
        }
    }elseif($mime_type == "image/jpeg"){
        // create a new true color image
        if($image_p = imagecreatetruecolor($width, $height)){

            // create a new image from file
            if($image = imagecreatefromjpeg($tmp_file_name)){

                // copy and resize part of an image with resampling
                if(imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig)){

                    if(imagepng($image_p, $actual_file_name, 0)){
                        // image is successfully uploaded
                        // free resources
                        imagedestroy($image_p);
                        imagedestroy($image);

                        // perform the insert operation and get the last inserted id
                        // $lastinsertID = XXXX

                        // new file name
                        $filename = $dir . $lastinsertID . basename($_FILES['image']['name'], "." . $ext) . ".png";

                        //move the file to your desired location
                        if(rename($actual_file_name, $filename)){
                            echo "success";
                        }else{
                            echo "error";
                        }

                    }else{
                        //Destroy both image resource handler
                        imagedestroy($image);
                        imagedestroy($image_p);
                        echo "Error";
                    }
                }else{
                    //Destroy both image resource handlers
                    imagedestroy($image);
                    imagedestroy($image_p);
                    echo "Error";
                }
            }else{
                //destroy $image_p image resource handler
                imagedestroy($image_p);
                echo "Error";
            }
        }else{
            echo "error_An unexpected error has been occured. Please try again later.";
        }
    }else{
        echo "Only JPEG, PNG and GIF images are allowed.";
    }

}else{
    echo "Bad image format";
}   
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
  • Wow this is great! Thank you! I will work on implementing and get back to you. Thank you so much! It may take me a few days to get back to it. – mreynol Dec 23 '15 at 18:35
  • @mreynol You're welcome. Let me know about the progress. – Rajdeep Paul Dec 23 '15 at 18:37
  • Okay I was able to give it a shot and it got much further. It converted the image to PNG!! :). It also stored the new image name in the database but it had appended the directory name where I want it moved to, to the file name in the database. Additionally, it didn't move the file to my $dir location. Lastly, I would like the resulting image to be (lastinsertID)image1.png (e.g. 12345image1.png). – mreynol Dec 23 '15 at 19:14
  • @mreynol Use `basename()` function to get only the file name, and then insert it to database. – Rajdeep Paul Dec 23 '15 at 19:21
  • correction! sorry. I had a mistake in my file path for my directory. It now worked! It converted the file and moved it to my directory. Only issue is that it appended the name of the directory onto the filename in my database entry and it need it to still be a name like: (lastinsertID)image1.png (e.g. 12345image1.png). – mreynol Dec 23 '15 at 19:23
  • so the entry for the filename in my database is showing: /php/upload/BBNL9Ho.png – mreynol Dec 23 '15 at 19:25
  • @mreynol Like I said use `basename($actual_file_name)` to get the file name, and then perform your insert operation. – Rajdeep Paul Dec 23 '15 at 19:26
  • Closer! But it wants to trim off the lastinsertID too. The lastinsertID needs to be included in the base. Can you help with that? – mreynol Dec 23 '15 at 19:31
  • 1
    @mreynol You can do like this, `$lastinsertID . basename($actual_file_name)` to get the updated file name. – Rajdeep Paul Dec 23 '15 at 19:35
  • When you can, my only last question is how to rename the base file name to "XXXXimage1.png" instead of "XXXXBBnL9Ho.png". I have another function where I will increment that number to make sure the names are always unique. This is because they can upload more than one file at a time. – mreynol Dec 23 '15 at 19:48
  • @mreynol Is image1.png the original name of your image or you want to rename it like this way? – Rajdeep Paul Dec 23 '15 at 19:52
  • It is not the original name. But I am making it so the user can upload multiple files and I want to ensure uniqueness in their names. I can maybe try to POST the file name that way and change it as the form is submitted instead of here. Does that make sense? – mreynol Dec 23 '15 at 20:13
  • 1
    @mreynol If I was you, I would create a function that generate random numbers. And when user upload multiple images then for each image I would append a random number with a simple file name like this, `random_number . "image.png"` and insert the new file name(`random_number . "image.png"`) in the database. That way it will ensure uniqueness. – Rajdeep Paul Dec 23 '15 at 20:24
  • Okay, I will give that a shot. Thank you again for all your help! – mreynol Dec 23 '15 at 20:26