skip to Main Content

I’ve built a CMS for a client and he’s trying to upload an screenshot image he took with his android tablet. The image is in png format, and uploads fine, but when I try to convert it to jpg with PHP (like I do with all images on the site) and create a thumbnail, the file isn’t converted. My conversion code works perfectly on every other image.

When I downloaded the image to my computer and tried to open it with photoshop it said “Could not complete your request because the file-format module cannot parse the file.” So I changed the file extension to .jpg and photoshop opened the file perfectly, and it then also uploaded and converted perfectly, generating the correct thumbnail. I’m guessing the file is encoded as a jpg, but somehow the android tablet labeled it as a png? My question is, is there any way in PHP to check the encoding of the image and then change the file extension appropriately?

3

Answers


  1. You can check out the inner structure of a file by using finfo_file(). This will allow you to retrieve the MIME type of a file. While it’s not 100% foolproof, for images, it should work out fine.

    Login or Signup to reply.
  2. Use php function getimagesize. This function will return also image format details.

    $size = getimagesize($filename);
    if (is_array($size)) {
      echo 'width: '.$size[0].' height: '.$size[1].' type: '.$size[2];
       // check type as IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP
    } else {
      echo 'unknown image format.';
    }
    
    Login or Signup to reply.
  3. I believe if you do something like the following:

    $extension = explode('.', $_FILES['file']['name']);
    $extension = end($extension);
    if($extension=="gif" && $_FILES['file']['type']=="image/gif") {
    //Continue
    } else {
    //Rename file here
    }
    

    That should get you started, hopefully you understand what I’m going for.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search