php get image width
PHP: Get the width and height of an image.
In this tutorial, I will be showing you how to get the width and height of an image using PHP. Thankfully, PHP has a handy built-in function called getimagesize, which will do most of the tough work for us.
Let’s look at a simple example:
In the code snippet above:
Getting the dimensions.
In my case, the array looked like this:
As you can see, there are six elements in the array:
Taking the above information into account, you can print out the dimensions of the image like so:
In my case, PHP printed out “272 X 92” onto the page.
WebP files.
Support for Google’s WebP format was not added until PHP version 7.1. As a result, the getimagesize function will return a boolean FALSE value if you are using an earlier version than that.
ico files.
Furthermore, .ico files may also fail as PHP only added support for icon files version 5.3.
Can getimagesize be used to validate image files?
This is not recommended, as the getimagesize function does not attempt to validate the format of the image. In the past, I have come across examples that showed how a GIF file containing PHP code was accepted by the function.
Failed to open stream.
If you receive a “failed to open stream” warning, then it means that geimagesize was unable to locate the file that you gave it. To fix this, you will need to make sure that the path you specified is correct.
getimagesize
(PHP 4, PHP 5, PHP 7, PHP 8)
getimagesize — Получение размера изображения
Описание
Функция ожидает, что filename является корректным файлом изображения. Если будет передан файл не содержащий изображения, он может быть некорректно интерпретирован как изображение и функция завершится успешно, но массив при этом будет содержать бессмысленные значения.
Не используйте getimagesize() для проверки того, что файл является изображением. Для этих целей используйте модуль Fileinfo.
Замечание: Сведения об иконках извлекаются из иконки с наибольшим битрейтом.
Список параметров
Этот аргумент задаёт файл, сведения о котором будут извлекаться. Это может быть локальный или удалённый (зависит от конфигурации) файл. Передача данных удалённого файла должна осуществляться одним из поддерживаемых потоков.
Возвращаемые значения
Возвращает массив из 7 элементов. Не все типы изображений содержат элементы с каналами ( channels ) и битрейтом ( bits ).
Индексы 0 и 1 содержат ширину и высоту изображения.
Некоторые форматы файлов могут хранить несколько изображений или не содержать изображения вообще. В таких случаях getimagesize() не сможет определить размер изображения. getimagesize() вернёт нули в качестве значений высоты и ширины.
Индекс 2 содержит одну из констант типа изображения IMAGETYPE_XXX.
Пример #1 getimagesize() и MIME типы
channels принимает значение 3 для RGB картинок и 4 для CMYK.
Ошибки
Список изменений
Версия | Описание |
---|---|
7.1.0 | Добавлена поддержка WebP. |
Примеры
Пример #2 Пример использования getimagesize()
Пример #3 getimagesize (URL)
// если в имени файла есть пробелы, учтите это должным образом
$size = getimagesize ( «http://www.example.com/gifs/lo%20go.gif» );
Пример #4 getimagesize() возвращающая IPTC
Примечания
Этой функции не требуется библиотека GD.
Смотрите также
User Contributed Notes 24 notes
As noted below, getimagesize will download the entire image before it checks for the requested information. This is extremely slow on large images that are accessed remotely. Since the width/height is in the first few bytes of the file, there is no need to download the entire file. I wrote a function to get the size of a JPEG by streaming bytes until the proper data is found to report the width and height:
There’s a code snippet for getting JPEG image dimensions by getting only first few bytes of the file, but it doesn’t work for PNG files, so I wrote one. It will download only the first 24 bytes instead of the whole image, and thus being much faster than getimagesize() and it will save bandwidth at the same time:
Get Image Height and Width as integer values?
I’ve tried to use the PHP function getimagesize, but I was unable to extract the image width and height as an integer value.
How can I achieve this?
6 Answers 6
getimagesize() returns an array containing the image properties.
to just get the width and height or
to get some more information.
PHP’s getimagesize() returns an array of data. The first two items in the array are the two items you’re interested in: the width and height. To get these, you would simply request the first two indexes in the returned array:
For further information, see the documentation.
getimagesize(‘image.jpg’) function works only if allow_url_fopen is set to 1 or On inside php.ini file on the server, if it is not enabled, one should use ini_set(‘allow_url_fopen’,1); on top of the file where getimagesize() function is used.
Not the answer you’re looking for? Browse other questions tagged php or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
getimagesize — Получение размера изображения
Описание
Замечание: Обратите внимание на тот факт, что отдельные части JPC и JP2 изображений могут иметь различную глубину цвета. В этом случае в параметре «bits» будет стоять максимальное значение из всех обнаруженных. Также JP2 файлы могут содержать несколько JPEG 2000 кодовых потоков. В таком случае getimagesize() вернет значения для первого такого потока, который будет обнаружен функцией в корне файла.
Замечание: Сведения об иконках извлекаются из иконки с наибольшим битрейтом.
Список параметров
Этот аргумент определяет файл, сведения о котором будут извлекаться. Это может быть локальный или удаленный (зависит от конфигурации) файл. Передача данных удаленного файла должна осуществляться одним из поддерживаемых потоков.
Возвращаемые значения
Возвращает массив из 7 элементов или меньше. Не все типы изображений содержат элементы с каналами (channels) и битрейтом (bits).
Индексы 0 и 1 содержат ширину и высоту изображения.
Некоторые форматы файлов могут хранить несколько изображений или не содержать изображения вообще. В таких случаях getimagesize() не сможет определить размер изображения. getimagesize() вернет нули в качестве значений высоты и ширины.
Индекс 2 содержит одну из констант типа изображения IMAGETYPE_XXX constants.
Индекс 3 содержит строку со значениями ширины и высоты изображения height=»yyy» width=»xxx», которая может быть использована внутри IMG тэга.
Пример #1 getimagesize() и MIME типы
channels принимает значение 3 для RGB картинок и 4 для CMYK.
Ошибки
Список изменений
Примеры
Пример #2 Пример использования getimagesize()
Пример #3 getimagesize (URL)
// если в имени файла есть пробелы, учтите это должным образом
$size = getimagesize ( «http://www.example.com/gifs/lo%20go.gif» );
Пример #4 getimagesize() возвращающая IPTC
Примечания
Этой функции не требуется библиотека GD.
Смотрите также
Php get image width
Описание
array getimagesize (string filename [, array imageinfo])
Возвращает массив из 4 элементов. Индекс 0 содержит ширину/width изображения в пикселах. Индекс 1 содержит высоту/height. Индекс 2 это флаг, указывающий тип изображения.1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(байтовый порядок intel), 8 = TIFF(байтовый порядок motorola), 9 = JPC, 10 = JP2, 11 = JPX. Индекс 3 это текстовая строка с корректной строкой height=»yyy» width=»xxx», которая может использоваться непосредственно в тэге IMG.