Задача возникла, когда делал клиенту сайт с электронным магазином. Картинки товаров на страницах должны выводиться единообразно; сам же клиент имеет картинки всех возможных размеров и пропорций. Чтобы освободить его от редактирования изображений, было решено вписывать их в контейнер - блок <div> фиксированного размера, обрамленный рамкой. Вытянутые по горизонтали имиджи вписываться будут по ширине, вытянутые по вертикали - соответственно, по высоте. Сами изображения должны быть кликабельны.

В принципе, задача довольно типичная и имеет существующие варианты решений, например, только через CSS-стили. Однако, когда в руках такое мощное оружие как серверный код, грех им не воспользоваться, когда ты сам не дизайнер, а программер. Поэтому я написал функцию, охватывающую все возможные соотношения сторон контейнера и вписываемого изображения. Ее и предлагаю на суд общественности.

Назовем нашу функцию out_adjusted_link_image. Ее определение будет иметь такой вид:

function out_adjusted_link_image($img_file, $img_alt, $img_title,
                                 $a_href, $div_wd, $div_ht,
                                 $div_more_style = '', $a_more = '')

Параметры:

Имя
Тип
Описание
$img_file
string
путь и имя файла изображения
$img_alt, $img_title
string
атрибуты alt и title тега имиджа
$a_href
string
URL, открываемый по клику на картинке
$div_wd, $div_ht
int
ширина и высота контейнера
$div_more_style
string
дополнительные атрибуты CSS-стиля контейнера (опционально)
$a_more
string
дополнительные атрибуты тега анкора (опционально)

Возвращаемое функцией значение - строка, содержащая HTML-скрипт нашей конструкции контейнер - линк - имидж.

Строим тело функции. Пошагово:

1. Определяем константы, задающие оба измерения, по которым будем вписывать:

define('ALIGN_BY_WD', 0);
define('ALIGN_BY_HT', 1);

2. Выясняем размеры имиджа. Для этого воспользуемся функцией getimagesize(). В качестве параметра эта функция требует имя файла образа, включая путь к нему. Возвращает она массив из 7 элементов, из которых нас интересуют первые 2 (т. е. с индексами 0 и 1), содержащие соответственно ширину и высоту имиджа.

$size = getimagesize($img_file);
$img_wd = $size[0];
$img_ht = $size[1];

3. Определяем, по какому измерению вписывать. Если контейнер более "сплющен" по вертикали, чем имидж, то после подгонки по размеру имидж впишется по высоте, в обратном случае - по ширине. Данная логика реализуется следующим фрагментом кода PHP:

if ($div_wd / $div_ht > $img_wd / $img_ht)
  $align = ALIGN_BY_HT;
else
  $align = ALIGN_BY_WD;

Частный случай равенства пропорций обоих прямоугольников, когда выравнивать можно по любому измерению, обрабатывается в блоке else.

4. Вписываем нашу картинку в контейнер. Для этого вычисляем ширину и высоту вписанного имиджа - $new_img_wd и $new_img_ht. Для последующего центрирования определяем также переменные $rel_edge и $abs_edge - края для относительного и абсолютного позиционирования по соответствующим измерениям, и $new_img_dim - размер, который будем использовать для установки отступа. Присваиваем им значения в соответствии с направлениями выравнивания.

if ($align == ALIGN_BY_HT) {
  $new_img_ht = $div_ht;
  $new_img_wd = $new_img_ht * $img_wd / $img_ht;
  $rel_edge = 'left';
  $abs_edge = 'top';
  $new_img_dim = $new_img_wd;
}
else {
  $new_img_wd = $div_wd;
  $new_img_ht = $new_img_wd * $img_ht / $img_wd;
  $rel_edge = 'top';
  $abs_edge = 'left';
  $new_img_dim = $new_img_ht;
}

5. Центрируем имидж. Вписанный по ширине - по вертикали, вписанный по высоте - по горизонтали. Для этого используем технику выравнивания, описанную в предыдущей статье. Помещаем искомую строку стиля в переменную $img_style:

$img_style = 'position:absolute; ' . $rel_edge . ':50%; width:' .
             $new_img_wd . 'px; height:' . $new_img_ht . 'px; margin-' .
             $rel_edge . ':-' . ($new_img_dim / 2) . 'px; ' .
             $abs_edge . ':0';

Теперь можно выстроить всю конструкцию контейнер - анкор - имидж, строку с которой и будет возвращать наша функция:

return '<div style="position:relative; width:' . $div_wd .
       'px; height:' . $div_ht . 'px; border:1px solid silver;' .
       $div_more_style . '"><a href="' . $a_href . '" '. $a_more .
       '><img src="' . $img_file . '" alt="' . $img_alt . '" title="' .
       $img_title . '" style="' . $img_style . '" /></a></div>';

Вот как она (конструкция то бишь) выглядит в браузере:

Monkey

Достигли ли мы желаемого результата? Не совсем. Попробуйте навести курсор на наш блок и убедитесь, что поля между имиджем и границами контейнера не попадают в ссылку. Чтобы ссылка охватывала весь блок, сделаем следующее:

  1. Наш вписанный и отцентрированный имидж расположим перед анкором ссылки.
  2. Вместо него внутрь анкора поместим прозрачный PNG-имидж, размеры которому зададим равными размерам контейнера.

Таким образом, наша картинка перекроется прозрачным имиджем и останется видимой. Зона же действия линка растянется до границ контейнера.

Модифицированный фрагмент кода, возвращающий значение функции, примет следующий вид:

return '<div style="position:relative; width:' . $div_wd .
       'px; height:' . $div_ht . 'px; border:1px solid silver;' .
       $div_more_style . '"><img src="' . $img_file . '" style="' .
       $img_style . '" /><a href="' . $a_href . '" '. $a_more .
       '><img src="images/Transparent.png" alt="' .
       $img_alt . '" title="' . $img_title . '" width="' .
       $div_wd . '" height="' . $div_ht .
       '" style="position:absolute; top:0px; left:0px;" /></a></div>';

Наведите курсор теперь и почувствуйте разницу:

Monkey

Собрав воедино все вышеприведенные части кода, получим функцию в окончательном виде:

function out_adjusted_link_image($img_file, $img_alt, $img_title,
                                 $a_href, $div_wd, $div_ht,
                                 $div_more_style = '', $a_more = '') {
  define('ALIGN_BY_WD', 0);
  define('ALIGN_BY_HT', 1);
 
  $size = getimagesize($img_file);
  $img_wd = $size[0];
  $img_ht = $size[1];
 
  if ($div_wd / $div_ht > $img_wd / $img_ht)
    $align = ALIGN_BY_HT;
  else
    $align = ALIGN_BY_WD;
 
  if ($align == ALIGN_BY_HT) {
    $new_img_ht = $div_ht;
    $new_img_wd = $new_img_ht * $img_wd / $img_ht;
    $rel_edge = 'left';
    $abs_edge = 'top';
    $new_img_dim = $new_img_wd;
  }
  else {
    $new_img_wd = $div_wd;
    $new_img_ht = $new_img_wd * $img_ht / $img_wd;
    $rel_edge = 'top';
    $abs_edge = 'left';
    $new_img_dim = $new_img_ht;
  }
 
  $img_style = 'position:absolute; ' . $rel_edge . ':50%; width:' .
               $new_img_wd . 'px; height:' . $new_img_ht . 'px; margin-' .
               $rel_edge . ':-' . ($new_img_dim / 2) . 'px; ' .
               $abs_edge . ':0';
 
  return '<div style="position:relative; width:' . $div_wd .
         'px; height:' . $div_ht . 'px; border:1px solid silver;' .
         $div_more_style . '"><img src="' . $img_file . '" style="' .
         $img_style . '" /><a href="' . $a_href . '" '. $a_more .
         '><img src="images/Transparent.png" alt="' .
         $img_alt . '" title="' . $img_title . '" width="' .
         $div_wd . '" height="' . $div_ht .
         '" style="position:absolute; top:0px; left:0px;" /></a></div>';
}

Пример вызова функции. Именно он рендерит в вашем браузере эту милую вписанную в кликабельный квадрат мартышку:

echo out_adjusted_link_image('images/monkey.jpg', 'Monkey', 'Monkey',
                    '#anchor', 200, 200,
                    'left:50%; margin-left:-100px', 'target="_blank"');

Здесь еще и сам контейнер отцентририрован по горизонтали внутри своего собственного родительского блока все по той же методике.

В одной из последующих статей я планирую описать, как я встроил приведенный здесь код в содержимое материала сайта на Joomla.

Комментарии  

accelerator startup
0 # accelerator startup 03.05.2023 22:20
Accelerators typically offer seed money iin change for fairness in the corporate.
In ine with current information, the average accelerator fairness deal wass $38,000
in 2018. So, how do startup accelerators generate income?
If the firswt profit you are on the lookout for is mentorship annd connections, sop binging onn accelerator promo videos and alumni interviews, and sujppose about
different methods you possibly can get access too tthe same advantages without giving up fairness.
Thus you may get a co-founder for your startup or a possibility to
hitch another business. Thus leveraging their
community will helpp to quickly accelerate the business.
A huge part of the startup accelerator journey is to
work with a network of mentors. The largest benwfit being a pawrt of an accelerator gives you, is access to proficient individuals who can provide youu with the useful produht and enterprise suggestions.
Based in 2011, Wayra is a part of the Telefonica model.

Based in 2010, BoomStartup is a high-rank startup accelerator program
in Utah. This can aloso be a Mountain View-based accelerator thazt was founded in 2010.The accelerator hhas hellped Twilio,
Canva, Udemy, Intercom, Talkdesk, Bukalapak, Seize, among others.
The Mountain View-based accelerator came alive in 2005 and remains both the best and the biggest accelerator
startup
.
Ответить | Ответить с цитатой | Цитировать
accelerator startup
0 # accelerator startup 03.05.2023 22:21
Fast Forward’s accelerator program takes place in San Francisco, CA during the summer season. Positioned in San Francisco, California,
500 Startups wass based in 2010 with a aim too help emerging entrepreneurs worldwide.
Beyond funding, UK’s startup accelerators and incubators also offer founders incredible valuable help for product development, ggross sales and marketing.
They offer a 4-month seed program with a $37000 partcipation charge which unlocks entry to networks, buyers, and
free workspaces. Alongside this, ass a result of these accelerators provide a relatively new manner of offering funding,
the very definition of what a startup accelerator startup is continues
to evolve over time. Tech Word For The Week is a weekly series where we look to clarify commonly
used phrases in the tech ecosystem in a easy, partaking manner.
Although nonprofits operate otherwise from corporate organizations,
there may be quite a bit to learn from the way in which for-profit organizations plan, ship
and evaluate their services. The Startup Accelerator offers several
excessive-worth engagement services together with strategic advisory,
business incubation, interim government management, govt search and leverages
its enterprise arm for company finance, merger & acquisition and fundraising
actions. Based in 2005, by Paul Graham, Y Combinators has funded 2000
plus startups including Dropbox, Stripe, Airbnb, Instacart, Twitch,
Coinbase, Reddit, and Weebly.
Ответить | Ответить с цитатой | Цитировать
accelerator startup
0 # accelerator startup 03.05.2023 22:21
Identical to going to varsity, university, and even high school, working for several months with a
startup accelerator startup
is about studying on a deep and profound degree.
Even with a single-minded entrepreneur with their properly-defined vision, you have to depend upon producers, designers,
marketers, or someone else different than just yourself
at some point alongside the availability chain. You
should be taught what you can and make strides, even when that is simply creating a far more effective pitch deck.
First-time entrepreneurs could be negatively affected if their
preliminary pitch fails. Also referred to as "learn by doing", entrepreneurs are inspired
to develop their expertise as they work on their business fashions.
By the end of every session, discover out what will work for your enterprise.
The faster you need to accomplish tasks throughout your
time with an accelerator means the harder you'll have to work.
With a purpose to succeed, entrepreneurs ought
to try to enter right into a stream state,
the place duties are accomplished with out stress and almost robotically.
This motivates entrepreneurs to do their finest.
What kinds of startups are best fitted to RAP? Accelerators are appealing to startups because they supply a wide network of traders
and mentors which help startups construct their enterprise and elevate future capital.
Ответить | Ответить с цитатой | Цитировать
accelerator startup
0 # accelerator startup 03.05.2023 22:22
If accepted, you may enter into the program alongside a gaggle oof other firms.
These people are willing to take on the danger and
effort to create optimistic change in society by their initiatives."In impact, these packages will not be open to all entrepreneurs like startup accelerators are, however ssolely to a select group of "social" entrepreneurs. In case you are turnhed down by an invcestor during a startup accelerator startup pitch, it isn’t the top of the world. TechTown is an entrepreneurship hub providing startup accelerator and incubation applications. It’s potential for a startup enterprise to not be successful on its own in the long term in terms of revenue, and the government nonetheless has reached some of its personal objectives via this system. Accelerators require startups to demonstrate development potential, have a minimum viable product and current traction in the meantime startups which might be still in the concept stage can be admitted to an incubator. Workspaces may be supplied at a separate location or as a part of a wider community (e.g., startup accelerator or enterprise incubator). The explanation for this is that the goals of a government-led startup accelerator are significantly completely different from both enterprise-backed accelerators and corporate-sponsored accelerators, which we'll discuss under in a second.
Ответить | Ответить с цитатой | Цитировать
accelerator startup
0 # accelerator startup 03.05.2023 22:24
Alongside studying by doing, entrepreneurs will discover
that thee time wanted to study elements of business growth, could be substantially copressed by being immersed on this course of.
For example, some founders acknowlkedged that they felt accelerators providing just a few workshops on specific matters was nnot sufficient when it comes to studying or steerage.

Most have a selected set of necessities, which vary relying on this system.
Each accelerator startup can have its own cycle, with its own features.
The faster you need to perform duties during your
time with an accelerator means the harder you'll have to work.

We're proud to have partnered with these organizations in order
to help them move their concepts forward. This contains
a range of occasions akin to mentor meetings, social meetings
with other founders, networking with silicon valley entrepreneurs, being given steering on what
to prioritize, and constructing up to the ultimate
demo day the place founders can pitch their concepts
to other buyers.
Ответить | Ответить с цитатой | Цитировать
bdsm
0 # bdsm 06.05.2023 07:53
I used to be able to find good info from your
blog articles.
Ответить | Ответить с цитатой | Цитировать
порно
0 # порно 11.05.2023 04:23
What's up mates, pleasant post and pleasant arguments commented at this place, I am actually enjoying
by these.
Ответить | Ответить с цитатой | Цитировать
зд забор
0 # зд забор 12.05.2023 22:50
3D заборы обладают рядом преимуществ.
Во-первых, они создают эффект объемности и глубины благодаря своей трехмерной структуре, что придает уникальный внешний вид
всему забору. Во-вторых, такие заборы обеспечивают дополнительную
приватность и безопасность, так как плотная
структура 3D забора предотвращает проникновение посторонних и обеспечивает ограниченный обзор снаружи.
Ответить | Ответить с цитатой | Цитировать

Добавить комментарий


Работая с этим сайтом, вы даете свое согласие на использование файлов cookie, необходимых для сохранения выбранных вами настроек, а также для нормального функционирования сервисов Google.