@DTPlayer

Почему выдает ошибку при конвертировании файла?

<?php

$dir = $_GET['dir'];
$compression = $_GET['compression']; // 0 - самое худшее; 100 - наилучшее
function AllFiles($dir)
{
    $files = glob($dir."/*.*",GLOB_NOSORT);
    do{
        $dir = $dir."/*";
        $files2 = glob($dir."/*.*",GLOB_NOSORT);

        $files = array_merge($files,$files2);
    }while(sizeof($files2)>0);

    return $files;
}

function getExtension($filename) {
    $format = preg_replace('/^.*\.(.*)$/U', '$1', $filename);
    $file = basename($filename, '.'.$format);
    return array('name' => $file, 'format' => $format, 'path' => $filename);
}
$jpeg_formats = ['jpg', 'jpeg'];
foreach (AllFiles($dir) as $filename){
    $fileinfo = getExtension($filename);
    if (in_array($fileinfo['format'], $jpeg_formats)) {
        $img = imagecreatefromjpeg($fileinfo['path']);
        imagepalettetotruecolor($img);
        imagealphablending($img, true);
        imagesavealpha($img, true);
        imagewebp($img, $dir . $fileinfo['name'] . '.webp', $compression);
        imagedestroy($img);
        $file = $fileinfo['path'];
        echo "$file - complete<br>";
    } 
}


?>

При попытке выполнить код получаю ошибки:
Warning: imagecreatefromjpeg(): gd-jpeg: JPEG library reports unrecoverable error: Not a JPEG file: starts with 0x52 0x49 in \index.php on line 34

Warning: imagecreatefromjpeg(): "img/123123/depositphotos_2983099-stock-illustration-grunge-design.jpg" is not a valid JPEG file in \index.php on line 34

Fatal error: Uncaught TypeError: imagepalettetotruecolor(): Argument #1 ($image) must be of type GdImage, bool given in \index.php:35 Stack trace: #0 \index.php(35): imagepalettetotruecolor(false) #1 {main} thrown in \index.php on line 35

С чем связаны ошибки и как их можно решить?
  • Вопрос задан
  • 644 просмотра
Решения вопроса 1
Compolomus
@Compolomus Куратор тега PHP
Комполом-быдлокодер
$dir = realpath('./img');

$ext = ['jpeg', 'jpg'];

$fileSPLObjects =  new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::CHILD_FIRST);
foreach($fileSPLObjects as $fullFileName => $fileSPLObject ) {
    if ($fileSPLObject->isFile()) {
        $info = new SplFileInfo($fullFileName);    
        if (in_array($info->getExtension(), $ext)) {
            $image = new Imagick($fullFileName);
            $image->setFormat('webp');
            $image->writeImage('webp:' . $fullFileName . '.webp');
            // тут можно удалить старое, unlink($fullFileName);
        }
    }
}

Вариант через Imagick, плюс покороче
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
Rsa97
@Rsa97
Для правильного вопроса надо знать половину ответа
Открываем список сигнатур и смотрим комбинацию 0x52 0x49 или RI.
Получаем один из трёх вариантов - wav, avi или webp.
А то, что у файла расширение jpeg, так это просто кто-то криво его задал.
Проверяйте тип через mime_content_type, Для JPEG должен возвращаться тип image/jpeg.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
18 апр. 2024, в 21:56
2000 руб./за проект
18 апр. 2024, в 21:00
150 руб./за проект