1

So I have an image upload script. It uploads the image and saves it to the space on the server. What I can't seem to get my head around is say, when the user uploads a .png, by the time it saves on my server i want it to be a jpg.

Can anyone help with this, and please don't just direct me to another question as I havent had anything work yet. Here is an example of my code.

$name = addslashes($_FILES['image']['name']);
$ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION); 
$size = $_FILES['image']['size'];
$temp = $_FILES ['image']['tmp_name'];
$error = $_FILES ['image']['error'];

if ($error > 0)
    die("Error uploading file! Code $error.");
else


if ($password == "" || $size > 2000000) {
    move_uploaded_file($temp, $images.$name);   
    mysql_query("INSERT INTO image_approval VALUES ('','$description','','$images$name','',NOW())");

    echo "Upload complete!";
    }else{
echo "Error uploading file";
    }
  • you have to 'save' (in temp) it then convert –  Jan 21 '13 at 01:38
  • well what I was meaning was, I'm unsure on how I would do that... nabil - I must have missed that when cutting it down from actual code, It works fine just now, just cant convert – Robbie Seath Jan 21 '13 at 01:41

2 Answers2

1

Using GD, and assuming $images is the directory where you store your images (with ending slash), and $name - the file name of the original image:

$destinationPath = $images . basename($name, $ext) . '.jpg';
$source = imagecreatefrompng($images . $name);
imagejpeg($source, $destinationPath, 75);
imagedestroy($source);

Or with Imagick:

$image = new Imagick($images . $name);
$image->writeImage($destinationPath);
$image->destroy();
nice ass
  • 16,471
  • 7
  • 50
  • 89
0

Use this function to convert the uploaded image

// http://stackoverflow.com/a/1201823/358906
// Quality is a number between 0 (best compression) and 100 (best quality)
function png2jpg($originalFile, $outputFile, $quality) {
    $image = imagecreatefrompng($originalFile);
    imagejpeg($image, $outputFile, $quality);
    imagedestroy($image);
}

Then delete old image with unlink().

Your code will be something like:

// After the upload
png2jpg($the_jpg_file_path, $the_png_file_path, 80);
unlink($the_jpg_file_path);
Nabil Kadimi
  • 10,078
  • 2
  • 51
  • 58