Php file type image gif

imagegif

imagegif() создает GIF файл из изображения image . Аргумент image возвращается функциями imagecreate() или imagecreatefrom*.

Файл будет иметь формат GIF87a , если изображение не было сделано прозрачным функцией imagecolortransparent() . В этом случае форматом файла будет GIF89a .

Список параметров

Ресурс изображения, полученный одной из функций создания изображений, например, такой как imagecreatetruecolor() .

Путь для сохранения файла. Если не установлен или равен NULL , изображение будет выведено в поток вывода в бинарном виде.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Вывод изображения, используя imagegif()

// Создание изображения
$im = imagecreatetruecolor ( 100 , 100 );

// Создание белого фона
imagefilledrectangle ( $im , 0 , 0 , 99 , 99 , 0xFFFFFF );

// Рисование текста на изображении
imagestring ( $im , 3 , 40 , 20 , ‘GD библиотека’ , 0xFFBA00 );

// Вывод изображения в броузер
header ( ‘Content-Type: image/gif’ );

imagegif ( $im );
imagedestroy ( $im );
?>

Пример #2 Преобразование PNG в GIF, используя imagegif()

// Загрузка PNG
$png = imagecreatefrompng ( ‘./php.png’ );

// Сохранение как GIF
imagegif ( $png , ‘./php.gif’ );

// Освобождение памяти
imagedestroy ( $png );

// готово
echo ‘Преобразование PNG в GIF успешно завершено!’ ;
?>

Примечания

Замечание:

Поддержка GIF была исключена из GD библиотеки в версии 1.6 и возвращена обратно в 2.0.28. Эта функция недоступна в промежутке этих версий. За дополнительной информацией обращайтесь на сайт » Проекта GD.

Следующий пример кода позволит вам писать PHP приложения, которые будут проще портироваться на разные системы. В нем используется автоопределение типа GD поддержки доступной в данный момент. Замените строки: header («Content-Type: image/gif»); imagegif ($im); на более переносимые:

// Создание нового изображения
$im = imagecreatetruecolor ( 100 , 100 );

// Какие-либо операции с изображением

// Обработка вывода
if( function_exists ( ‘imagegif’ ))
// для GIF
header ( ‘Content-Type: image/gif’ );

imagegif ( $im );
>
elseif( function_exists ( ‘imagejpeg’ ))
// для JPEG
header ( ‘Content-Type: image/jpeg’ );

imagejpeg ( $im , NULL , 100 );
>
elseif( function_exists ( ‘imagepng’ ))
// для PNG
header ( ‘Content-Type: image/png’ );

imagepng ( $im );
>
elseif( function_exists ( ‘imagewbmp’ ))
// для WBMP
header ( ‘Content-Type: image/vnd.wap.wbmp’ );

imagewbmp ( $im );
>
else
imagedestroy ( $im );

die( ‘В этом PHP сервере нет поддержки изображений’ );
>

// Если не поддерживается ни один из форматов
// освободим память
if( $im )
imagedestroy ( $im );
>
?>

Замечание:

По состоянию на 4.0.2 вы можете использовать функцию imagetypes() вместо function_exists() для проверки, какие форматы поддерживаются:

Смотрите также

  • imagepng() — Вывод PNG изображения в броузер или файл
  • imagewbmp() — Выводит изображение в браузер или пишет в файл
  • imagejpeg() — Выводит изображение в браузер или пишет в файл
  • imagetypes() — Возвращает список типов изображений, поддерживаемых PHP сборкой
Читайте также:  Python номер буквы алфавита

Источник

imagegif

imagegif() создаёт GIF файл file из изображения image . Аргумент image возвращается функциями imagecreate() или imagecreatefrom* .

Файл будет иметь формат GIF87a , если изображение не было сделано прозрачным функцией imagecolortransparent() . В этом случае форматом файла будет GIF89a .

Список параметров

Объект GdImage , возвращаемый одной из функций создания изображений, например, такой как imagecreatetruecolor() .

Путь, или открытый потоковый ресурс (который автоматически закрывается после завершения функции), для сохранения файла. Если не установлен или равен null , изображение будет выведено в поток вывода в бинарном виде.

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Однако, если libgd не может вывести изображения, эта функция вернёт true .

Список изменений

Версия Описание
8.0.0 image теперь ожидает экземпляр GdImage ; ранее ожидался корректный gd ресурс ( resource ).

Примеры

Пример #1 Вывод изображения, используя imagegif()

// Создание изображения
$im = imagecreatetruecolor ( 100 , 100 );

// Создание белого фона
imagefilledrectangle ( $im , 0 , 0 , 99 , 99 , 0xFFFFFF );

// Рисование текста на изображении
imagestring ( $im , 3 , 40 , 20 , ‘GD библиотека’ , 0xFFBA00 );

// Вывод изображения в броузер
header ( ‘Content-Type: image/gif’ );

imagegif ( $im );
imagedestroy ( $im );
?>

Пример #2 Преобразование PNG в GIF, используя imagegif()

// Загрузка PNG
$png = imagecreatefrompng ( ‘./php.png’ );

// Сохранение как GIF
imagegif ( $png , ‘./php.gif’ );

// Освобождение памяти
imagedestroy ( $png );

// готово
echo ‘Преобразование PNG в GIF успешно завершено!’ ;
?>

Примечания

Замечание:

Следующий пример кода позволит вам писать PHP приложения, которые будут проще портироваться на разные системы. В нем используется автоопределение типа GD поддержки доступной в данный момент. Замените строки: header («Content-Type: image/gif»); imagegif ($im); на более переносимые:

// Создание нового изображения
$im = imagecreatetruecolor ( 100 , 100 );

// Какие-либо операции с изображением

// Обработка вывода
if( function_exists ( ‘imagegif’ ))
// для GIF
header ( ‘Content-Type: image/gif’ );

imagegif ( $im );
>
elseif( function_exists ( ‘imagejpeg’ ))
// для JPEG
header ( ‘Content-Type: image/jpeg’ );

imagejpeg ( $im , NULL , 100 );
>
elseif( function_exists ( ‘imagepng’ ))
// для PNG
header ( ‘Content-Type: image/png’ );

imagepng ( $im );
>
elseif( function_exists ( ‘imagewbmp’ ))
// для WBMP
header ( ‘Content-Type: image/vnd.wap.wbmp’ );

imagewbmp ( $im );
>
else
imagedestroy ( $im );

die( ‘В этом PHP сервере нет поддержки изображений’ );
>

// Если не поддерживается ни один из форматов
// освободим память
if( $im )
imagedestroy ( $im );
>
?>

Замечание:

Вы можете использовать функцию imagetypes() для проверки, какие форматы поддерживаются:

Смотрите также

  • imagepng() — Вывод PNG изображения в браузер или файл
  • imagewbmp() — Выводит изображение в браузер или пишет в файл
  • imagejpeg() — Выводит изображение в браузер или пишет в файл
  • imagetypes() — Возвращает список типов изображений, поддерживаемых PHP сборкой

User Contributed Notes 12 notes

read also RFC2557: http://www.ietf.org/rfc/rfc2557.txt
For handling inline images in email.
—-

I’ve been playing around with the «data» URL scheme as proposed by RFC 2397 which states how to perform inline, bas64 encoded images. A number of browsers support this format from some of my tests and would be an interesting way of removing overhead from multiple HTTP connections. Basically, the IMG tag would be:

Читайте также:  Java new random int

Something like that. Note also that I start the URI with «/-/» before the rest of the data scheme spec. If you don’t start it with this, it won’t work in a lot of the different browsers I tested (such as IE). Note this is useful for very small images only (as most browsers appear to have a limitation on the size of HTML element data of 1024). Browsers where this syntax worked that I tested are the following:

IE 6.x (windows)
Mozilla 0.97+ (linux)
Opera 5, 6 (windows)
Netscape 4.7+ (mac, windows)
IE 5 (macintosh)

This should work for other image types as well, such as PNG. JPEG files aren’t really suggested (usually, these files are too large). BTW — there is no advantage to this method if the image will appear more than ONCE in the page because you will be transmitting the same data multiple times as opposed to just once (most browsers realize that already downloaded data that has multiple references only requires one HTTP call).

Consider using this method if you want to make a single PHP program that outputs both text and an image AND you want to make only on HTTP call. Cheers.

apparently GD does not support animated GIFs.

instead, we’re stuck with the old fashioned way:
header ( ‘Content-Type: image/gif’ );
echo file_get_contents ( $destPathImage );
?>

Источник

Работа с MIME-типами в PHP

«Internet Media Types» или «Медиа типы» — является стандартом RFC 6838, который описывает формат файла. Причем браузеры используют MIME-типы в качестве основного критерия, не воспринимая расширения файлов.

MIME-тип состоит из типа и подтипа — двух значений разделённых « / », без использования пробелов и в нижнем регистре, например HTML страница:

Полный список MIME типов можно посмотреть тут.

К медиа типу может быть добавлен параметр для указания дополнительных деталей (например кодировка):

Как узнать MIME-тип загруженного файла

При загрузке файла через форму, MIME-тип файла доступен в массиве $_FILES , например:

Для определения MIME уже загруженного файла существует PHP-функция mime_content_type().

echo mime_content_type(__DIR__ . '/image.png'); // image/png echo mime_content_type(__DIR__ . '/text.txt'); // text/plain

При работе с изображениями, MIME-тип можно получить с помощью функции getimagesize():

$filename = __DIR__ . '/image.png'; $info = getimagesize($filename); print_r($info);

Результат:

Array ( [0] => 221 [1] => 96 [2] => 3 [3] => width="221" height="96" [bits] => 8 [mime] => image/png )

Важно помнить что при проверке файлов нельзя полагаться только на проверку MIME, т.к. его значение может быть скомпрометировано. Поэтому нужно проводить более детальную проверку (например по размеру изображения или его пересохранить в предполагаемом формате).

Отправка файлов из PHP

В PHP-скриптах, перед отправкой файлов клиенту, необходимо отправлять заголовок Content-Type , например файл XML:

$content = '. '; header("Content-Type: text/xml; charset=utf-8"); echo $content; exit();
$file = ROOT_DIR . '/market.zip'; header('Content-type: application/zip'); header('Content-Transfer-Encoding: Binary'); header('Content-length: ' . filesize($file)); header('Content-disposition: attachment; filename="' . basename($file) . '"'); readfile($file); exit();

Вывод изображения в зависимости от расширения файла:

$filename = __DIR__ . '/image.png'; $ext = mb_strtolower(mb_substr(mb_strrchr($filename, '.'), 1)); switch ($ext) < case 'png': header('Content-type: image/png'); break; case 'jpg': case 'jpeg': header('Content-type: image/jpeg'); break; case 'gif': header('Content-type: image/gif'); break; case 'wepb': header('Content-type: image/webp'); break; >readfile($filename); exit();

Источник

Читайте также:  Безопасность сервера безопасность php

Check if the Uploaded File is an Image in PHP

Most of us would have come across the common solutions in PHP to check if the uploaded file is an image, you might have tried the usual way of checking the extensions and accepting the file to be a valid image, what if someone sinister uploaded a malicious script just by changing the extension of the file to .jpg or .gif ? . I bet most of us would have used the following to validate the image uploaded in PHP.

Check if uploaded image is valid with getimagesize( ) in PHP

$imagesizedata = getimagesize($file); if ($imagesizedata ) < //do something >

but PHP docs says not to use getimagesize( ) to check that a given file is a valid image. it’s true that getimagesize( ) returns an array with some random values for image height & width, when the given file is not a valid image.

Check if uploaded image is valid by checking the extensions

$type=$_FILES[ 'image' ][ 'type' ]; $extensions=array( 'image/jpeg', 'image/png', 'image/gif' ); if( in_array( $type, $extensions ))< //do something >

but here you are checking only the extensions, like I said earlier, anyone can rename a file with a different content into jpg or gif and upload them without any problem.

Check if uploaded image is valid with exif data and fileinfo in PHP

Now let’s try something to check if the given image is valid, but before going into the example, let me tell you, even the following functions in PHP will not validate an image correctly.

All the above functions will return the mime/image type for the given image, but they will fail as well if we upload a file after changing the extension or cheat with the first few bytes of image headers. Here is the example I was talking about. I have the following content in a file and saved it as motion.gif

and used the following PHP code to check the validity of the image, you can see I have tried the four commonly recommended PHP functions to check if the given image is valid and each one of them failed.

"; echo $filename . ": " . mime_content_type( $filename ) . "
"; echo "exif: " . exif_imagetype( $filename ) . "
"; print_r( getimagesize( $filename ) ); finfo_close( $finfo );

this is the output of the above code

php output image

so all the above mentioned solutions to check if the uploaded files is a valid image will deceive us in the end, the only best solution is to use imagecreate function in PHP, we have separate functions for jpg, gif , png or to create image with the given string or content of the file. imagecreate function will return false when it fails to create an image with the given image file., so you can check if the given file is a valid jpg or gif or png.

here is the code I tried, to validate the uploaded image files.

You can experiment yourself with various images and cheating with the first few headers of jpg, gif or png.

Источник

Оцените статью