Flector 5
Это маленький, но весьма полезный плагин, чьей единственной функцией является перегенерация миниатюр в блоге. Любое изменение размера миниатюр в настройках блога коснется лишь новых залитых вами картинок, а все старые картинки останутся с прежними размерами. А что делать, если вы сменили шаблон блога на тот, в котором дизайн заточен под определенный размер миниатюр? Вот тут то вам и понадобится данный плагин. Установили плагин, перегенерировали миниатюры в нужном размере и все, плагин можно удалять. И не стоит бояться экспериментировать с новыми шаблонами и разными размерами миниатюр – плагин создает новые миниатюры, не удаляя при этом старые. Таким образом, вы всегда можете откатиться на свой изначальный шаблон без какого-либо ущерба (ну кроме лишних картинок в папке загрузок) для своего блога.
1 Распаковываем архив.
2 Копируем папку regenerate-thumbnails в /wp-content/plugins/ .
3 Заходим в админку блога на вкладку "Плагины " и активируем плагин.
Никаких настроек в плагине нет. Так что не забываем сначала зайти в "Параметры\Медиафайлы " и установить нужные вам размеры миниатюр.
После этого у нас есть два варианта:
1 Перегенерация всех картинок сразу. Зайдите в "Инструменты\Regen. Thumbnails " и нажмите кнопку "Regenerate All Thumbnails ":
Теперь вам остается лишь ждать, пока плагин пересоздаст все миниатюры. Это может занять от нескольких секунд до десятков минут в зависимости от количества картинок. Сотня картинок пересоздается примерно одну минуту.
2 Перегенерация избранных картинок. Можно пересоздать лишь выбранные картинки, для этого зайдите в библиотеку медиафайлов. Там вы сможете перегенерировать или несколько картинок сразу или каждую по отдельности:
В шаблоне миниатюры могут выводиться или с относительными размерами или с точно определенными размерами. Относительные размеры (миниатюра, средняя, крупная) означают, что шаблон выведет картинки ровно в тех размерах, которые указаны в настройках блога. Независимо от того, впишутся ли картинки в этих размерах в дизайн шаблона или нет.
Функция the_post_thumbnail (которую вы можете найти в файле index.php в папке шаблона) при этом выглядит примерно так:
the_post_thumbnail("thumbnail"); // миниатюра (150 на 150) the_post_thumbnail("medium"); // средняя (300 на 300) the_post_thumbnail("large"); // большая (640 на 640) the_post_thumbnail("full"); // полная (без ограничений)
Если этот код похож на тот, который есть в файлах вашего шаблона, то вам придется вручную подбирать те размеры миниатюр, которые будут хорошо выглядеть в новом шаблоне блога. Но, как правило, если указаны относительные размеры, то автор шаблона рассчитывает на то, что размеры картинок установлены со значениями по умолчанию.
the_post_thumbnail( array (500 , 150 ) ) ; // 500 на 150 |
the_post_thumbnail(array(500,150)); // 500 на 150
Именно эти размеры вы и должны указать в настройках блога, а потом пересоздать картинки именно с этими размерами. Только в таком случае шаблон будет выглядеть именно так, как задумал его автор. Если вы не укажите эти размеры в настройках блога, то будет выведена картинка максимально близкая к указанным размерам. На деле это означает, что вместо этого:
Будет выведено вот это:
Пример, конечно, надуманный. Но, тем не менее, он наглядно показывает, что дизайнер мог иметь ввиду одно, а получается совсем другое только потому, что у вас миниатюры заданы не тех размеров, которые использовал автор шаблона. В данном случае записи вообще налезают друг на друга и портят дизайн напрочь. Многие шаблоны так и отбрасываются пользователями, которые просто не могут понять, что кривизна дизайна этих шаблонов вызвана неправильными размерами миниатюр, а вовсе не кривыми ручками их авторов.
На многих блогах рядом с описанием постов можно встретить небольшую (большую) миниатюру, которая должна передавать содержание поста. До некоторых пор создать такое было нелегко. С появлением же Wordpress 2.9 осуществить такое стало намного легче.
В этом уроке я покажу Вам как добавить подобный функционал к Вашим шаблонам оформления Wordpress.
Включение Post-Thumbnail функции в шаблонах
Включение происходит очень просто. Все что от Вас требуется - добавление одной строки в файле functions.php:
Add_theme_support("post-thumbnails");
Вставка миниатюр к постам
Когда Вы заходите в администраторской панели в раздел написания нового поста, Вы должны увидеть новый отдел сбоку страницы.
Заметьте, что новый отдел может находится вне видимости и Вам придется опуститься немного ниже. После нажатия Set thumbnail появляется новое диалоговое окно
Нажмите Use as thumbnail и миниатюра будет добавлена к Вашему сообщению:
Отображение миниатюр
После того как мы написали новость, давайте добавим ее. Для того, чтобы миниатюра отображалась необходимо добавить строку в цикл Wordpress. Откройте файл index.php и добавьте следующее:
Это позволит вывести изображение используя классы attachment-post-thumbnail и wp-post-image. C помощью этих классов мы сможем оформить внешний вид миниатюр с помощью CSS. В картинке ниже мы можем увидеть миниатюру с границей и отступом.
На картинке выше миниатюра довольно большая. Ее размер можно менять из админки Settings > Media.
Другой способ определение размеров миниатюры - это изменение файла functions.php. Для этого нам понадобится добавить еще одну строку:
Add_theme_support("post-thumbnails"); set_post_thumbnail_size(588, 250, true);
Теперь нам необходимо сообщить Wordpress, чтобы использовался именно этот размер. Требуется немного видоизменить наш цикл в index.php:
Теперь Wordpress точно знает какую версию миниатюры использовать. Вот что у нас получилось:
Теперь добавим еще немного PHP в файл single.php, чтобы при открытии сообщения миниатюра была в самом верху:
Добавление больше размеров миниатюр
Если Вы хотите, чтобы на главной странице миниатюры были одного размера, а на самой странице сообщения другого - нужно делать следующее.
Смысл заключается в следующем: мы хотим, чтобы на странице сообщения было большое изображение, а на главной - маленькое. Для этого нам необходимо добавить еще один размер миниатюры в файл функций:
Add_image_size("loopThumb", 588, 125, true);
Описание аргументов:
Loopthumb - название нового размера миниатюр
- 588 - ширина в пикселях
- 125 - высота
-
true - настройка, которая сообщает
Wordpress следует ли использовать средства движка для изменения размеров изображения
Нам необходимо будет изменить наш код в файле index.php:
Также следует заметить, что у нас появятся два новых стиля для управления внешним видом миниатюры нового размера: attachment-loopThumb и wp-post-image. Может быть полезно обращаться к классу wp-post-image в таблице стилей или же добавить собственный класс при обращении к миниатюре:
"loopyThumbs")); ?>
Это выдаст тег img со следующими классами: loopyThumbs и wp-post-image.
Допустим мы хотим сделать квадратные миниатюры, тогда нужно создать новый размер:
Add_image_size("squareThumb", 125, 125, true);
Также, возможно, Вы захотите, чтобы миниатюры была слева и был небольшой отступ справа:
Attachment-post-thumbnail { float: left; margin-right: 10px; }
Теперь мы меняем код в index.php для отображения нашего квадрата:
Вот что у нас получится:
Если Вы будете добавлять ранее загруженные изображения в качестве миниатюр, у Вас могут быть не совсем ровные квадраты. Это происходит из за того, что при загрузке изображений Wordpress не мог предвидеть, что в будущем Вы захотите использваоть квадратные миниатюры.
Но есть выход и в этой ситуации. Нам поможет плагин Regenerate Thumbnails . После установки плагина - зайдите Tools > Regen и сгенери руйте новые миниатюры (Regenerate all Thumbnails). После этого у нас будут ровные квадраты.
И помните - для отображения миниатюр у Вас должен стоять Wordpress 2.9.
Надеюсь, Вам понравился урок. До следующих встреч!
Convenient way to create post thumbnails on the fly without server overload.
The best alternative to scripts like «thumbnail.php».
Supports Multisite.
Применение
The plugin for developers firstly, because it don’t do anything after install. In order to the plugin begin to work, you need use one of plugin function in your theme or plugin. Example:
Using the code in the loop you will get ready thumbnail IMG tag. Plugin takes post thumbnail image or find first image in post content, resize it and create cache. Also creates custom field for the post with URL to original image. In simple words it cache all routine and in next page loads just take cache result.
You can make thumbs from custom URL, like this:
The URL_TO_IMG must be from local server: by default, plugin don’t work with external images, because of security. But you can set allowed hosts on settings page: Settings > Media .
All plugin functions:
// return thumb url URL echo kama_thumb_src($args, $src); // return thumb IMG tag echo kama_thumb_img($args, $src); // return thumb IMG tag wraped with . A link of A will leads to original image. echo kama_thumb_a_img($args, $src); // to get image width or height after thumb creation echo kama_thumb($optname); // ex: echo "";
w | width
(int) desired width.h | height
(int) desired height.if parameters w and h not set, both of them became 100 — square thumb 100х100 px.
notcrop
(isset) if set crop parameter become false — crop=false .crop
(isset) Control image cropping. By default always true .To disable cropping set here false/0/no/none or set parameter "notcrop" . Then image will not be cropped and will be created as small copy of original image by sizes settings of one side: width or height — here plugin select the smallest suitable side. So one side will be as it set in w or h and another side will be smaller then w or h .
Cropping position
Also, you can specify string: "top" , "bottom" , "left" , "right" or "center" and any other combinations of this strings glued with / . Ex: "right/bottom" . All this will set cropping area:
- "left", "right" — horizontal side (w)
- "top", "bottom" — vertical side (h)
- "center" — for both sides (w and h)
When only one value is set, the other will be by default. By default: "center/center" .
// image will be reduced by height, and width will be cropped. // "right" means that right side of image will be shown and left side will be cut. kama_thumb_img("w=200 &h=400 &crop=right"); // image will be redused by width, and height will be cropped. // "top" means that the top of the image will be shown and bottom side will be cut. kama_thumb_img("w=400 &h=200 &crop=top"); // you can specify two side position at once, order doesn"t matter kama_thumb_img("w=400 &h=200 &crop=top/right");
Reduce image by specified side
In order to get not cropped proportionally rediced image by specified side: by width or height. You need specify only width or only height, then other side will be reduced proportional. And no cropping will appear here.
Kama_thumb_img("w=200");
So, width of our image will be 200, and height will be as it will…
Теперь ширина всегда будет 200, а высота какая получится… And the picture will be always full, without cropping.q | quality
(int) jpg compression quality (Default 85. max.100)stub_url
(string) URL to no_photo image.alt
(str) alt attr of img tag.title
(str) title attr of img tag.class
(str) class attr of img tag.style
(str) style attr of img tag.attr
(str) Allow to pass any attributes in IMG tag. String passes in IMG tag as it is, without escaping.a_class
(str) class attr of A tag.a_style
(str) style attr of A tag.a_attr
(str) Allow to pass any attributes in A tag. String passes in A tag as it is, without escaping.no_stub
(isset) don’t show picture stub if there is no picture. Return empty string.yes_stub
(isset) show picture stub if global option in option disable stub showing, but we need it…post_id | post
(int|WP_Post) post ID. It needs when use function not from the loop. If pass the parameter plugin will exactly knows which post to process. Parametr ‘post’ added in ver 2.1.attach_id
(int) ID of wordpress attachment image. Also, you can set this parametr by pass attachment ID to ‘$src’ parament — second parametr of plugin functions: kama_thumb_img("h=200", 250) or kama_thumb_img("h=200 &attach_id=250")allow
(str) Which hosts are allowed. This option sets globally in plugin setting, but if you need allow hosts only for the function call, specify allow hosts here. Set ‘any’ to allow to make thumbs from any site (host).
$args
(array/string)
Arguments to create thumb. Accepts:
$src
(string) URL to any image. In this case plugin will not parse URL from post thumbnail/content/attachments.
If parameters passes as array second argument $src can be passed in this array, with key: src или url или link или img:
Echo kama_thumb_img(array("src" => "http://yousite.com/IMAGE_URL.jpg", "w" => 150, "h" => 100,));
Примечания
- src parameter or second function argument is for cases when you need create thumb from any image not image of WordPress post.
You can pass $args as string or array:
// string kama_thumb_img("w=200 &h=100 &alt=IMG NAME &class=aligncenter", "IMG_URL"); // array kama_thumb_img(array("width" => 200, "height" => 150, "class" => "alignleft" "src" => ""));
You can set only one side: width | height , then other side became proportional.
For test is there image for post, use this code:
If(! kama_thumb_img("w=150&h=150&no_stub")) echo "NO img";
Примеры
#1 Get Thumb
In the loop where you need the thumb 150х100:
Результат:
#2 Not show stub image
#3 Get just thumb URL
Result: /wp-content/cache/thumb/ec799941f_100x80.png
This url you can use like:
" alt="">
#4 kama_thumb_a_img() function
Результат:
#5 Thumb of any image URL
Pass arguments as array:
"http://yousite.com/IMAGE_URL.jpg", "w" => 150, "h" => 100,)); ?>
Pass arguments as string:
When parameters passes as string and «src» parameter has additional query args («src=$src &w=200» where $src = http://site.com/img.jpg?foo&foo2=foo3) it might be confuse. That’s why «src» parameter must passes as second function argument, when parameters passes as string (not array).
#6 Parameter post_id
Get thumb of post ID=50:
I don’t need plugin
This plugin can be easily used not as a plugin, but as a simple php file.
If you are themes developer, and need all it functionality, but you need to install the plugin as the part of your theme, this short instruction for you:
- Create folder in your theme, let it be ‘thumbmaker’ — it is for convenience.
- Download the plugin and copy the files: class.Kama_Make_Thumb.php and no_photo.jpg to the folder you just create.
- Include class.Kama_Make_Thumb.php file into theme functions.php , like this:
require ‘thumbmaker/class.Kama_Make_Thumb.php’; - Bingo! Use functions: kama_thumb_*() in your theme code.
- If necessary, open class.Kama_Make_Thumb.php and edit options (at the top of the file): cache folder URL/PATH, custom field name etc.
- Conditions of Use — mention of this plugin in describing of your theme.
TODO
- Лог stub файлов — чтобы узнать какие файлы были не найдены и на каких страницах
- возможно очистить кэш отдельной картинки
- брать заглушку из медиабиблиотки в настройках
- указывать в альт название записи для kama_thumb_img(), если он пустой и есть ID записи? Но функция работате с URL поэтому альт не всегда можно указать правильно… Может юзать in_the_loop().
Скриншоты
Установка
Instalation via Admin Panel
- Go to Plugins > Add New > Search Plugins enter «Kama Thumbnail»
- Find the plugin in search results and install it.
Instalation via FTP
- Download the .zip archive
- Open /wp-content/plugins/ directory
- Put kama-thumbnail folder from archive into opened plugins folder
- Activate the Kama Thumbnail in Admin plugins page
- Go to Settings > Media page to customize plugin
Отзывы
Участники и разработчики
«Kama Thumbnail» - проект с открытым исходным кодом. В развитие плагина внесли свой вклад следующие участники:
УчастникиЖурнал изменений
2.8.13
- NEW: фильтр pre_do_thumbnail_src .
- NEW: Обработка SVG — если для создания миниатюры преедана ссылка на SVG файл, эта ссылка просто будет возвращена.
2.8.12
- NEW: фильтр kama_thumb_src .
- NEW: параметр stub_url .
2.8.11
- FIX: Заметка в админке об очистке заглушек теперь показывается только админам.
2.8.10
- FIX: Баг с нестандартными доменами например: domain.academy .
2.8.9
- ADD: Хук kama_thumb_default_args .
2.8.8
- FIX: Проверка строки при получении картинки. Иногда по URL может вернуться HTML код вместо данных картинки.
- NEW: Авто-определение путей при интеграции плагина в тему или в MU плагины. Теперь для интеграции плагина в тему, плагин можно просто положить в папку темы и подключить в functions.php главный файл плагина.
- DEL: Удалил фильтр kama_thumb_allow_admin_options_page . Теперь его работа базируется на фильтре kama_thumb_def_options , если он используется, то страница опций плагина автоматически отключается и опции указываются через этот фильтр.
2.8.7
- FIX: Мелкие правки кода.
- NEW: для kama_thumb_img() автоматически прописывается alt (бурется у вложения), если указан параметр attach_id .
- NEW: Фильтр: kama_thumb_def_options — позволяет изменить опции по умолчанию (когда плаг ставиться не как плаг)
- NEW: Фильтр: kama_thumb_allow_admin_options_page — позволяет отключить страницу опций в админке (когда плаг ставиться не как плаг)
- NEW: Опция: auto_clear_days — каждые сколько дней очищать кэш
2.8.6
- BUG: wrong resizing when rise_small option enabled and specified size smaller then the image one is.
2.8.5
- BUG: on save of any type of post was created empty postmeta ‘photo_URL’, but it must be cleared only if it was exist before.
2.8.4
- CHG: create_function() replaced with lambda function, in order to support PHP 7.2+
2.8.3
- NEW: parameter ‘rise_small’. If set to false, when thumbnail will not become bigger if it size (width/height) is smaller than the specified size. Default: true — small thumbnails size increases.
2.8.2
- IMP: function parse_main_dom() now understand localhosts and IP.
2.8.1
- FIX: incorrect display on options page starting from WP 4.9.0
2.8.0
- Bugfix: there was error if pass post object (WP_Post) in ‘post’ parameter…
2.7.9
- CHG: rename filter start with ‘kmt_’ to ‘kama_thumb_’: ‘kmt_set_args’, ‘kmt_is_allow_host’, ‘kmt_img’, ‘kmt_a_img’ become ‘kama_thumb_set_args’, ‘kama_thumb_is_allow_host’, ‘kama_thumb_img’, ‘kama_thumb_a_img’.
- minor fixes
2.7.8
- ADD: hook ‘kama_thumb_inited’.
- FIX: little logic confuse about trigger_error()
2.7.7
- ADD: support for multisite — in MU plugin has it’s own options page in network settings menu. Child sites don’t have plugin options — it manages globally from network.
- ADD: now all files creates in sub folders of main cache folder, to avoid folder overflow. SEO redirect from old location to new.
- IMP: minor fixes: ‘meta_key’ option insurance. ‘debug’ option works only in WP_DEBUG mode. Code improvements.
2.7.6
- FIX: if set ‘kama_thumb_a_img(‘w=200″, $src)’ where $src is empty. Plugin was tried generate image of current post, but in this case better to show ‘no_photo’ stub.
2.7.5
- ADD: new parameters for adding attributes to A tag: ‘a_class’, ‘a_style’, ‘a_attr’ — kama_thumb_a_img("w=200 &a_class=foobar &a_style=display:block; &a_attr=") .
2.7.3 — 2.7.4
- ADD: ‘crop’ parameter…
- ADD: ‘attach_id’ parameter — ID of wordpress attachment image. Also, you can set this parametr by pass attachment ID to ‘src’ parament or in second parametr of plugin functions: kama_thumb_img("h=200", 250) or kama_thumb_img("h=200 &attach_id=250")
- FIX: ‘class.Kama_Make_Thumb.php’ changes and fixes
2.7.2
- ADD: ‘style’ parameter for ‘kama_thumb_img()’ and ‘kama_thumb_a_img()’ functions.
2.7.0 — 2.7.1
- ADD: new function echo kama_thumb("width") — it allows to get real ‘width/height’ of image if width/height is empty. Or if we set ‘notcrop’ parameter and small image side will be resized proportionally and we don’t know the size beforehand.
- CHG: default no_photo image changed.
2.6.3
- CHG: confusing option ‘debug’ in class.Kama_Make_Thumb now turn on/off on settings page…
- ADD: options sanitization on save for protection reasons…
2.6.1
- NEW: languages dir removed from plugin
2.6.0
- ADD: ‘yes_stub’ parameter for functions ‘kama_thumb_*()’. Useful when ‘no_stub’ set in option, but in special place we need the stub (no photo image)
- ADD: New button on options page to clear all cache and delete metafields at once.
- FIX: bug fix with ‘no_stub’ option. Right after plugin activation it worked incorrectly.
2.5.8
- FIX: To support URL with HTML entity input src noe decodet with html_entity_decode() — ‘it`s-image.jpg’ > ‘it`s-image.jpg’
2.5.7
- FIX: Supports to URL without protocols: //site.com/folder/image.png
2.5.6
- FIX: removed two underscore ‘__’ from all classes methods. Because it reserved by PHP.
2.5.5
- ADD: WP HTTP API to get IMG from URL.
- ADD: ‘width’ & ‘height’ attributes for ‘kama_thumb_img()’ function for images with not specified ‘width’ or ‘height’ parameter (uses with ‘notcrop’ attribute)
- BUG: If set ‘notcrop’ parameter and not set ‘height’ — PHP dies with fatal error…
2.5.4
- ADD: thumb img in post content: now consider ‘srcset’ attribute if it’s set
2.5.3
- FIX: regular about ‘mini’ class in IMG tag and now you can change ‘mini’ class
2.5.2
- FIX: some minor fixes for plugin activation and uninstall
2.5.1
- ADD: Cyrilic domain support — such URL will wokr ‘http://сайт.рф/img.jpg’.
- ADD: ‘allow’ parameter from single function call fix — not work correctly.
2.5
- ADD: New filters for Kama_Make_Thumb class: ‘kmt_set_args’, ‘kmt_is_allow_host’, ‘kmt_img’, ‘kmt_a_img’
- ADD: Is allow host now checks for only main domain (not subdomain). Ex: now plugin works if you try create thumb of ‘http://site.com/img.png’ from ‘foo.site.com’ host
- ADD: New parameter ‘allow’ — set allowed hosts for only current function call. Ex: kama_thumb_img(«w=200 &h=200 &allow=any», ‘http://external-domain.com/img.jpg’);
2.4.4
- IMPROVE: Get file from remote domain not work properly if there were redirects…
2.4.3
- FIX: mini class for IMG in content. Was output error if IMG inside and not inside A tag.
2.4.2
- CHANGE: Kama_Make_Thumb class::get_src_and_set_postmeta() become publik. In order to just original get img url of post.
- FIX: search img url in post content not worked with relative url like: «/foo.jpg», and not worked if img extension «jpeg»;
- FIX: many times faster treatment in post content (regular expression fix);
2.4.1
- FIX: parsing parametrs if it given as string. ex: «h=250 ¬crop &class=aligncenter» notcrop becomes «notcrop_»
2.4
- FIX: If place second function parameter $src (img url) — it didn’t work correctly, because stupid mistake.
- FIX: when use class ‘mini’ in post content and IMG already wrapped with A tag, plugin made double A wrap.
- IMPROVE: Now self hosted images firstly parses as absolute path, and if there is error, it parses as URL. This method is much stable in some cases.
- ADD: Place ‘any’ in alowed hostes string on settings page, and plugin will make thumbs from any domain.
2.3
- Great Bug: Now if parameters passes as string ‘src’ parameter better pass as second argument of functions kama_thumb_*(«w=200 &h=300», ‘http://site.com/image.jpg’).
2.2
- ADD: ‘attr’ parameter. Allow to pass any attributes in IMG tag. String passes as it is, without escaping.
2.1
- ADD: aliases for passed parameters: src = url|link|img, post_id = post (can be passed as post object), q = quality, w = width, h = height
- FIX: when parameters passes as string and «src» parameter has aditional query args («src=$src &w=200» where $src = http://site.com/img.jpg?foo&foo2=foo3) it might be confuse, that’s why «src» parameter must passes in the end of string, when parameters passes as string (not array).
- CHG: some code refactoring in class.Kama_Make_Thumb.php file.
- FIX: no_stub worked only for images from posts. When ‘src’ is setted parameter ‘no_stub’ had no effect;
2.0
- ADD: notice message when no image library instaled on server (GD or Imagic)
- ADD: diferent names for real thumb and nophoto thumb. And possibility to clear only nophoto thumbs from cache. All it needed to correctly create IMGs from external URLs (not selfhosted img) — sometimes it can’t be loaded external imges properly.
1.9.4
- FIX: ext detection if img URL have querya rgs like *.jpg?foo
1.9.3
- CHG: DOCUMENT ROOT detection if allow_url_fopen and CURL disabled on server
1.9.2
- FIX: trys to get image by abs server path, if none of: CURL || allow_url_fopen=on is set on server
1.9.1
- FIX: getimagesizefromstring() only work in php 5.4+
1.9.0
- ADD: Images parses from URL with curl first
1.8.0
- ADD: Images parses from URL. It FIX some bugs, where plugin couldn’t create abs path to img.
- ADD: Allowed hosts settings. Now you can set sites from which tumbs will be created too.
1.7.2
- CHG: Back to PHP 5.2 support 🙁
1.7.1
- CHG: PHP lower then 5.3 now not supported, because it’s bad practice…
1.7
- FIX: refactor — separate one class to two: «WP Plugin» & «Thumb Maker». Now code have better logic!
1.6.5
- ADD: EN localisation
1.6.4
- ADD: now cache_folder & no_photo_url detected automatically
- ADD: notcrop parametr
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
exif_thumbnail — Retrieve the embedded thumbnail of an image
Description
exif_thumbnail (mixed $stream [, int &$width [, int &$height [, int &$imagetype ]]]) : string
exif_thumbnail() reads the embedded thumbnail of an image.
If you want to deliver thumbnails through this function, you should send the mimetype information using the header() function.
It is possible that exif_thumbnail() cannot create an image but can determine its size. In this case, the return value is FALSE but width and height are set.
Parameters
The location of the image file. This can either be a path to the file or a stream .
The return width of the returned thumbnail.
The returned height of the returned thumbnail.
Imagetype
The returned image type of the returned thumbnail. This is either TIFF or JPEG .
Return Values
Returns the embedded thumbnail, or FALSE if the image contains no thumbnail.
Examples
Example #1 exif_thumbnail() example
$image = exif_thumbnail ("/path/to/image.jpg" , $width , $height , $type );
if ($image
!==
false
) {
echo
$image
;
exit;
} else {
// no thumbnail available, handle the error here
echo
"No thumbnail available"
;
}
?>
Changelog
Version | Description |
---|---|
7.2.0 | The filename parameter was renamed to stream and now supports both local files or stream resources. |
Notes
If the stream is used to pass a stream to this function, then the stream must be seekable. Note that the file pointer position is not changed after this function returns.
require_once("../PEL/PelJpeg.php"
);
require_once("../PEL/PelIfd.php"
);
$fullpath
=
"images/DSC_0013c.JPG"
;
# path of source image (does not contain an exif thumbnail)
$jpeg
= new
PelJpeg
($fullpath
);
$exif
=
$jpeg
->
getExif
();
$tiff
=
$exif
->
getTiff
();
$ifd0
=
$tiff
->
getIfd
();
# need this so that we can later link it to the new IFD
$ifd1
=
$ifd0
->
getNextIfd
();
if (!
$ifd1
) {
# Only create thumbnail if one doesn"t exist (i.e. there is no IFD1)
$ifd1
= new
PelIfd
(1
);
$ifd0
->
setNextIfd
($ifd1
);
# point ifd0 to the new ifd1 (or else ifd1 will not be read)
$original
=
ImageCreateFromString
($jpeg
->
getBytes
());
# create image resource of original
$orig_w
=
imagesx
($original
);
$orig_h
=
imagesy
($original
);
$wmax
=
160
;
$hmax
=
120
;
If ($orig_w
>
$wmax
||
$orig_h
>
$hmax
) {
$thumb_w
=
$wmax
;
$thumb_h
=
$hmax
;
if ($thumb_w
/
$orig_w
*
$orig_h
>
$thumb_h
)
$thumb_w
=
round
($thumb_h
*
$orig_w
/
$orig_h
);
# maintain aspect ratio
else
$thumb_h
=
round
($thumb_w
*
$orig_h
/
$orig_w
);
}
else {
# only set the thumb"s size if the original is larger than "wmax"x"hmax"
$thumb_w
=
$orig_w
;
$thumb_h
=
$orig_h
;
}
# create image resource with thumbnail sizing
$thumb
=
imagecreatetruecolor
($thumb_w
,
$thumb_h
);
## Resize original and copy to the blank thumb resource
imagecopyresampled
($thumb
,
$original
,
0
,
0
,
0
,
0
,
$thumb_w
,
$thumb_h
,
$orig_w
,
$orig_h
);
# start writing output to buffer
ob_start
();
# outputs thumb resource contents to buffer
ImageJpeg
($thumb
);
# create PelDataWindow from buffer thumb contents (and end output to buffer)
$window
= new
PelDataWindow
(ob_get_clean
());
If ($window ) {
$ifd1
->
setThumbnail
($window
);
# set window data as thumbnail in ifd1
$outpath
=
$fullpath
;
# overwrite original jpg file
file_put_contents
($outpath
,
$jpeg
->
getBytes
());
# write everything to output filename
# Show thumbnail in file:
echo
".
$outpath
.
"" border=0 alt="If you see this, it did not work">
"
;
}
}
else {
echo
"ifd1 already exists! (IFD1 is where the thumbnail is stored)
"
;
}
?>
# This is the code in thumb_exif.php:
$imgdat
=
exif_thumbnail
($_REQUEST
[
"image"
],
$width
,
$height
,
$type
);
header
("Content-type: "
.
image_type_to_mime_type
($type
));
echo($imgdat
);
?>
If you have a lot of such files, you can easily make a script that searches them out and adds thumbnails to their exif.
12 years ago
If you want to convert from TIFF to JPG you can use ImageMagick if it is installed in your server.
$exec
=
"convert /path/to/file.tiff /path/to/file.jpg 2>&1"
;
@
exec
($exec
,
$exec_output
,
$exec_retval
);
//possible error
print_r
($exec_output
)
?>
$post_id (целое число ) ID поста, миниатюру которого нам нужно получить, по умолчанию — ID текущего пост из цикла. $size (строка|массив ) в этом параметре указываем размер миниатюры. Может принимать следующие значения:
- thumbnail / medium / large — одно из стандартных размеров изображений, зарегистрированных в WordPress по умолчанию, данные размеры можно настроить в Параметры > Медиа,
- full — оригинальное разрешение изображения — таким оно было загружено на сайт,
- Можно указать собственные параметры ширины и высоты миниатюры в виде массива, например array(50, 30) . Обратите внимание, WordPress не будет создавать дубликат картинки под этот размер — вместо этого будет использоваться наиболее близкий по разрешению зарегистрированный размер картинки, подогнанный под ваши параметры с сохранением оригинальных пропорций.
Чтобы было понятнее, приведу пример. Предположим, в качестве этого аргумента мы указали array(50, 30) . У меня самый близкий размер будет 125×125 (thumbnail) — URL этой картинки и будет вставлен в атрибут src . Окей, а что с пропорциями? Так как 125×125 — это квадрат, то и наша миниатюра будет квадратной, она впишется по наименьшему параметру, т.е. результат будет 30×30.
- Один из собственных размеров изображений, зарегистрированных через функцию .
- src — если вам надо, можете даже заменить URL картинки.
- class — класс тега , по умолчанию имеет следующие классы wp-post-image и attachment-{размер изображения} .
- alt — по умолчанию trim(strip_tags($attachment->post_title)) — указывается в админке при загрузке/редактировании медиафайла.
- title — по умолчанию trim(strip_tags($attachment->post_excerpt)) .
Пример 1
Простой пример — просто выведем миниатюру поста с ID = 5:
echo get_the_post_thumbnail( 5 , "thumbnail" ) ; // |
Пример 2. Как сделать миниатюры с ссылками на пост?
Предположим, мы хотим реализовать это на страницах категорий. Давайте немного доработаем цикл:
while ( have_posts() ) : the_post() ; if ( has_post_thumbnail() ) : echo "ID ) . "">" . get_the_post_thumbnail( $post ->ID , "thumbnail" ) . "" ; endif ; echo "ID ) . "">" . $post ->post_title . "" ; endwhile ; |
В этом примере я также использовал функцию для того, чтобы в случае отсутствия миниатюры код не выводил лишний тег .
Пример 3. Как сделать, чтобы при клике на миниатюру, открывалась полная версия картинки?
Код из этого примера отлично подойдет для использования в каком-нибудь плагине jQuery, например fancybox или pretty photo. В таком случае вам возможно также понадобится добавить класс для ссылки.
Вы также можете ознакомиться с документацией функций и на моем блоге.
Пример 4. Используем третий параметр $attr для изменения класса миниатюры
Давайте добавим на наши миниатюры класс align-left типа для того,чтобы они обтекались текстом слева:
Фильтр post_thumbnail_size
Фильтр позволяет задать размер миниатюр, используемых на блоге (везде на блоге).
А теперь пример со следующим условием: для всех миниатюр на блоге, которые выводятся через функцию get_the_post_thumbnail() с параметром $size равным thumbnail заменяем размер на medium , остальные размеры миниатюр не трогаем:
Количество параметров данного фильтра не может не радовать, это означает, что мы можем творить с возвращаемым HTML-кодом всё, что нам угодно.
$html (строка ) HTML-код, возвращаемый функцией по умолчанию, $post_id (целое число ) ID поста, миниатюру которого нужно получить, $post_thumbnail_id (целое число ) ID миниатюры, $size (строка|массив ) размер миниатюры, $attr (массив ) массив HTML-атрибутов, которые были заданы при вызове функции, если не заданы, то пустой массив;
А теперь несколько интересных примеров.
Пример 1. Автоматическое проставление ссылок на пост
Фишка в том, что каждый раз при использовании функции get_the_post_tumbnail() миниатюры уже будут возвращаться с автоматически проставленными ссылками на пост.
function true_auto_linking( $html , $post_id , $post_thumbnail_id , $size , $attr ) { return "" . $html . "" ; } add_filter ("post_thumbnail_html" , "true_auto_linking" , 10 , 5 ) ; |
Круто, да? А главное — всё очень просто.
Пример 2. Возвращаем только URL миниатюры
Миша Рудрастых
Если вам нужна помощь с вашим сайтом или может даже разработка с нуля - .