0

I'm working on a project right now, where users can upload profile pictures to the server via php.

The file is automatically renamed according to their session-id. Now I want to convert all uploaded pictures automatically to JPGs.

Thought I'd try to just manipulate the file-extension to "jpg" while it uploads, but never thought that it would actually work. But it seems like it does, the file is uploaded to the server as a JPG (tried it with Chrome).

Is this a legit way to convert images or will there be any problems in other browsers?

[...]
   if ($uploadOk != 0) {
         $filetypetest = "jpg";
         $newfilename = $sessionid . '.' .$filetypetest;
         move_uploaded_file($_FILES["bild"]["tmp_name"], "uploads/" . $newfilename);
    }
weheri
  • 73
  • 8
  • Possible duplicate of http://stackoverflow.com/a/14549647/1238737 . A GIF is not a JPG just because of a file extension change. Not a recommended solution. – snkashis Jun 10 '15 at 15:19

3 Answers3

1

Changing the file extension doesn't convert it, it'll still be whatever file type it was uploaded as. Browser are able to display it as they get information from the file's MIME type, not the extension.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
0

Their is another post very similar to this that states how to convert to jpg: How to convert all images to JPG format in PHP?

Community
  • 1
  • 1
danielson317
  • 3,121
  • 3
  • 28
  • 43
0

Try something more like this:

function ConvertToJPG($originalImage, $outputImage, $quality)
{
    // determine if its jpg, png, gif or bmp...

    $exploded = explode('.',$originalImage);
    $ext = $exploded[count($exploded) - 1]; 

    if (preg_match('/jpg|jpeg/i',$ext))
        $imageTmp=imagecreatefromjpeg($originalImage);
    else if (preg_match('/png/i',$ext))
        $imageTmp=imagecreatefrompng($originalImage);
    else if (preg_match('/gif/i',$ext))
        $imageTmp=imagecreatefromgif($originalImage);
    else if (preg_match('/bmp/i',$ext))
        $imageTmp=imagecreatefrombmp($originalImage);
    else
        return 0;

    // quality is a value from 0 (worst) to 100 (best)
    imagejpeg($imageTmp, $outputImage, $quality);
    imagedestroy($imageTmp);

    return 1;
}
FlyFire5
  • 41
  • 6