How to convert all images to JPG format in PHP?

前端 未结 1 408
Happy的楠姐
Happy的楠姐 2020-11-30 14:31

I am developing a website in PHP that let the user to upload images and then let him to decide how the image should be using jQuery - PHP integeration to select the area tha

相关标签:
1条回答
  • 2020-11-30 14:59

    Maybe it's not working with PNG because PNG only supports compression levels 0 to 9.

    I'd also rather modify the behaviour based on MIME type, not extension. And I guess you're checking your POST user input before using it in code ;)

    Here's my variant of the code:

    $path = "../images/DVDs/";
    
    $img = $path . $_POST['logo_file'];
    
    if (($img_info = getimagesize($img)) === FALSE)
      die("Image not found or not an image");
    
    
    switch ($img_info[2]) {
      case IMAGETYPE_GIF  : $src = imagecreatefromgif($img);  break;
      case IMAGETYPE_JPEG : $src = imagecreatefromjpeg($img); break;
      case IMAGETYPE_PNG  : $src = imagecreatefrompng($img);  break;
      default : die("Unknown filetype");
    }
    
    $tmp = imagecreatetruecolor(350, 494);
    imagecopyresampled($tmp, $src, 0, 0, intval($_POST['x']), intval($_POST['y']),
                       350, 494, intval($_POST['w']), intval($_POST['h']));
    
    
    $thumb = $path . pathinfo($img, PATHINFO_FILENAME) . "_thumb";
    switch ($img_info[2]) {
      case IMAGETYPE_GIF  : imagegif($tmp,  $thumb . '.gif');      break;
      case IMAGETYPE_JPEG : imagejpeg($tmp, $thumb . '.jpg', 100); break;
      case IMAGETYPE_PNG  : imagepng($tmp,  $thumb . '.png', 9);   break;
      default : die("Unknown filetype");
    }
    

    For every filetype you want supported, you only have to add two lines of code.

    0 讨论(0)
提交回复
热议问题