Not a valid PNG file

Asked by At

I have a code:

<?php
    $size = 2000000;
    $types = array('image/png', 'image/jpeg');
    if(isset($_POST['go'])){
    $newName = $id . '.' . $type;
    $directory = 'img/avatars/'; //path to folder with images
    $picture = $directory . basename($newName);

    if (!in_array($_FILES['picture']['type'], $types)) {
        die('Wrong type of file. <a href="../settings.php">Try another</a>');
    } elseif ($_FILES['picture']['size'] > $size) {
        die('File is too big. <a href="../settings.php">Try another</a>');
    } elseif (move_uploaded_file($_FILES['picture']['tmp_name'], $picture)) {       
        echo "Image was downloaded!"; 
    }
    $new_width = 66; //necessary width
    $size = getimagesize($picture); 
    $width = $size[0];
    $height = $size[1];
    if ($type == 'png') {
        $src=ImageCreateFromPng($picture);
    }
    if ($type == 'jpeg' || $type == 'jpg') {
        $src=ImageCreateFromJPEG($picture);
    }
    $coefficient = $width/$new_width;
    $new_height = ceil($height/$coefficient);
    $empty_picture = ImageCreateTrueColor($new_width, $new_height);
    ImageCopyResampled($empty_picture, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    if ($type == 'png') {
        ImagePNG($empty_picture, $picture, -1);
    }
    if ($type == 'jpeg') {
        ImageJPEG($empty_picture, $picture, -1);
    }
    imagedestroy($src); 
    }
?>

It returns an error:

imagecreatefrompng(): 'img/avatars/6.png' is not a valid PNG file in W:\domains\mysite\settings.php

I checked is it png image:

$finfo = finfo_open(FILEINFO_MIME_TYPE);
echo finfo_file($finfo, $picture); // image/png
finfo_close($finfo);

And it returns me: image/png (it is).

So I do not know what is wrong with this code. Would be grateful for any help!

0 Answers