3

I'm adding a profile picture feature to my site, and for security I would like to convert images server-side to PNG format, and strip extra information out of the file. It should be a pixel to pixel conversion if that is possible. I don't need to accept every format, just PNG and JPEG are fine.

Phoenix Logan
  • 1,238
  • 3
  • 19
  • 31

2 Answers2

2

This one checks filetype, retains transparency in images and outputs max quality:

// the uploaded image
$file = $_FILES[0]['tmp_name'];

// Get file info
$data = getimagesize($file);
$mimetype = $data['mime'];

// Creat the image
switch($mimetype){
    case("image/png"):
        $image = imagecreatefrompng($file);
        imagealphablending($image, false);
        imagesavealpha($image, true);
        break;
    case('image/jpeg'):
    case('image/pjpeg'):
    case('image/x-jps'):
        $image = imagecreatefromjpeg($file);
        break;
    case('image/gif'):
        $image = imagecreatefromgif($file);
        imagealphablending($image, false);
        imagesavealpha($image, true);
        break;
    default:
        throw new Exception("Invalid image type. Only excepts PNG, JPG, and GIF. You entered a {$mimetype} type image.");
}

// Output to browser with maximum quality
imagepng($image, null, 9);

// Or save the image as a file
//imagepng($image, "SavedImageFilename.png", 9);
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
1

the core of the functionality is:

$data = file_get_contents($sourceImagePath);

$im = null;
if(!empty($data)){
    $im = imagecreatefromstring($data);
}

imagepng($im,$saveImageToPath);
imagedestroy($im);

If you need more info let me know

volkinc
  • 2,143
  • 1
  • 15
  • 19