ПРОГРАММ: 654 | СТАТЕЙ: 125 | КОДОВ: 3434   

    главная        новости        программы        библиотека        коды        рейтинг       форум   

Афоризм
"Завтра у меня коронация. Уже пригласили коронера."
 
Поиск


 
Рассылка
| Soft-Ежедневник - обзор программ прямо к Вам на e-mail
 
 
Полезное!
 
7 лучших
  Экобиотехнология Микрозим™: очистка окружающей среды и утилизация отходов, биоремедация
  Компания Чистомир - клининговые услуги
  Услуги, аренда автовышек
  <a href="Ваша ссылка">Наши вольеры красивые и удобные, Вальер Усадьба будет удобен в
  Тонирование стекол
  
  
 
  Библиотека > web - разработка > PHPдобавить статью
Создание изображений с помощью PHP (gd)

Одной из особенностей PHP является возможность создания изображений, как говорится "на лету". Что это значит? Это означает, что скрипт...
 
Листопад Александр
php4you.kiev.ua
26-05-2004
Версия для печати
печать

    Содержание
  1. Вступление
  2. Необходимые компоненты
  3. Создание скрипта

Вступление

Язык PHP (официально: "PHP - гипертекст препроцессор"), встроенный в HTML язык скриптов на стороне сервера. Это мощный язык, позволяющий разработчику обращаться к базам данных различных типов и производителей, работать с массивами, регулярными выражениями, делать сетевые запросы, а также многе-многое другое... и все это можно проделать из HTML-кода! А результат - отдать на клиентскую сторону, в браузер.

Одной из особенностей PHP является возможность создания изображений, как говорится "на лету". Что это значит? Это означает, что скрипт, написанный на PHP выдает после выполнения HTTP-заголовок Content-type: с соответствующим созданному типу изображения значением и после этого выводит изображение, получается как будто веб-сервер выдал изображение как таковое, а не как результат выполнения скрипта.

Применений этой возможности PHP очень много на практике. Самое простое применение - создание счетчиков. Можно создать огромное множество счетчиков, различных оттенков, с использованием различных TrueType шрифтов. Самый яркий пример - topping.com.ua - украинская система рейтинга сайтов Интернет.

Вверх

Необходимые компоненты

Прежде всего для создания изображений с выдачей пользователю в браузер необходим веб-сервер. Лучше всего для этого подойдет веб-сервер Apache. Далее - нужно получить самую свежую версию PHP, можно тут: www.php.net/downloads.php, а также все необходимые компоненты:

  • gd [gd-1.8.3.tar.gz]
  • t1lib [t1lib-1.0.1.tar.gz]
  • jpeg-6b [jpegsrc.v6b.tar.gz]
  • libpng [libpng-1.0.6.tar.gz]
  • freetype [freetype-1.3.1.tar.gz] (библиотека для прорисовки TT шрифтов)
Внимание! Номера версий указаны на момент написания данной статьи и могут устареть на момент чтения.

После установки всех библиотек и т.д. по местам нужно собрать модуль PHP. После этого остановить (если запущен) веб-сервер и запустить заново или запустить свежесобранный httpd, предварительно подправив под свои нужды конфигурационный файл httpd.conf. После этого веб-сервер с модулем PHP и возможностью создания изображений "на лету" готов! Можно пользоваться.

Вверх

Создание скрипта

Скрипт PHP выглядит так:

<? header("Content-type: image/png");
$img = imagecreate(400,80);
$black = ImageColorAllocate($img, 0, 0, 0);
$green = ImageColorAllocate($img, 0, 255, 0);
$white = ImageColorAllocate($img, 255, 255, 255);
$trans = ImageColorTransparent($img, $white);
ImageFill($img, 0, 0, $white);
ImageString($img , 2, 10, 10, "Laa is so happy to see you!", $black);
ImageTTFText($img, 18, 0, 45, 45, $green, "arial8.ttf", "$text");
ImagePng($img);
ImageDestroy($img); ?>

Теперь подробнее о методе создания и самом скрипте.

Первая строка выдает HTTP-заголовок Content-type: image/png, который объявляет браузерам о том, что тип последующей информации является графическое изображение формата PNG.

Следующая строка возвращает идентификатор изображения $img, который PHP будет ассоциировать с изображением размером 400 пикселей по горизонтали и 80 по вертикали.

С третьей по пятую строку происходит ассоциирование цветов из палитры RGB (red-green-blue) с переменными PHP. Функция ImageColorAllocate должна быть вызвана для ассоциации любого цвета, который может быть использован в будущем изображении.

Функция ImageColorTransparent использует два аргумента - идентификатор изображения и цвет из палитры RGB (переменная PHP). В результате будущее изображение будет создано с прозрачным цветом указанным в переменной (второй аргумент). К сожаленью эта функция применима только с GIF-изображениями, но этот формат начиная с версии 1.6 в gd не поддерживается. Это связанно с тем, что Unisys владеет патентом LZW-компрессии.

ImageFill - заполнение изображения $img цветом $white начиная с позиции "0, 0" - верхний левый угол. Я только сам не понял зачем указывать координаты? По логике нужно указывать только изображение и цвет... ну да ладно. Думаю разработчики постарались сделать функции избыточными - вдруг кому пригодится... :-)

Функция ImageString прорисовывает строку текста (5-ый аргумент) цвета $white в позиции "10, 10" (3-, 4-ый аргументы) стандартным шрифтом с фиксированной шириной символов. Эта функция имеет мало возможностей прорисовки текста в изображениях, но эти возможности можно расширить с помощью функции ImageLoadFont.

Функция ImageTTFText прорисовывает текст в изображении с помощью TrueType шрифтов, которые разработчик может самостоятельно подключить. Второй аргумент указывает размер шрифта, используемого для прорисовки. Третий - угол наклона будущего текста относительно горизонтали. (Используя угол 90њ, разработчик получает текст, написанный снизу вверх, т.е. вертикально.) Далее - 4- и 5-ый аргументы предназначены для указания координат начала строки текста (точнее: левого нижнего угла первой буквы текста, что противоположно поведению функции ImageString, которая использует координаты для указания верхнего правого угла первой буквы текста). Следующие аргументы, которые используются - это цвет текста, шрифт (путь к файлу шрифта) и собственно текст.

Две последнии функции (ImagePng и ImageDestroy) выдают изображение браузеру и удаляют его из памяти соответственно. Аргументом в обоих случаях выступает идентификатор изображения. Помимо функции ImagePng допустимо использование функции ImageJpeg с предварительным указанием этого в HTTP-заголовке (Content-type:).




Комментарии
Оставить комментарий
страница < | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | >

BandaroImpunny | 15-12-21 21:29
It can be necessary to make sure that he eats a healthy diet, which includes the recommended ranges of nutrients. Diagnostic and Therapeutic Biomarkers in Glioblastoma: Current Status and Future Perspectives. Propolis can also be utilized in mouthwashes and been diferent in their primary bioactive compounds (Table 1) symptoms 9dp5dt <a href=https://www.skellyskills.com/wp-content/practice/purchase-gentamicin-online-in-usa/></a>.
Group, Chakraborty and colleagues (1997, 1998a) have con- these matters are discussed in subsequent sections. One dose of the vaccine is sufcient for kids aged 12-24 months Tere are two types of hepatitis vaccine available: plasma who are late in receiving their vaccines. In most circumstances, the requirement of anti-allergic tablets is nearly zero after the fourth Liver Cleanse (results could vary slightly from person to person) symptoms genital warts <a href=https://www.skellyskills.com/wp-content/practice/buy-mesalamine-online-in-usa/>cheap mesalamine 800 mg line</a>. Risk elements for cellulitis in cirrhosis embody skin trauma/puncture, obesity, homelessness, and subjective diploma 212 212 of edema. Peri-operative chemotherapy for patients with resectable colorectal hepatic metastasis: A meta546. Take house level: Through expertise and over time we are able to make our brain less sensitive to sure anxiety triggers medications over the counter <a href=https://www.skellyskills.com/wp-content/practice/order-truvada-online-in-usa/>buy truvada 300/2


Copperomisp | 08-12-21 21:41
However the assembly acknowledged that individual nations or areas may need to rank fsh species in accordance with their particular state of affairs and needs. Early spread is by way of lymph nodes and local unfold is often to the uterus, vagina, bladder and rectum. Distal symmetric polyneuropathy: a defnition for medical research: report of the American Academy of Neurology, the American Association of Electrodiagnostic Medicine, and the American Academy of Physical Medicine and Rehabilitation fungus disease <a href=https://trustuniversity.edu.bd/biomedical/purchase-fluconazole-online/>generic fluconazole 200mg fast delivery</a>.
Asthma assaults induced litis associated with infliximab within the treatment of rheumatoid arthritis. Paper offered registry accuracy: improvement with progressive clinical at: Pediatric Academic Societies annual meeting; May 2-5, software. These infections cause quickly spreading areas of erythema, Cultures of blood, tissue aspirates, or pores and skin biopsies are unnec- swelling, tenderness, and heat, typically accompanied by essary for typical circumstances of cellulitis impotence at 80 <a href=https://trustuniversity.edu.bd/biomedical/buy-cheap-silagra-no-rx/>50mg silagra with amex</a>. For this cause, lymph nodes in adults are virtually never "regular" or "resting," and it's often essential to distinguish morphologic adjustments secondary to previous experience from those associated to present disease. A com parison of estim ates by two tec


Arokkhlutle | 06-12-21 17:31
Polypoid kind, which produces giant protruding mass into the lumen with ulcerated floor. Place des traitements medicaux dans la lipodystrophie L uridine, vendue comme supplement alimentaire, n a montre aucun benefce sur la lipoatrophie et n est donc pas recommandee <>]. Tachycardia may outcome from problems such as maternal fever, infection, or as a consequence of early uteroplacental insufficiency erectile dysfunction fun facts <a href=https://trustuniversity.edu.bd/biomedical/buy-viagra-plus/>400 mg viagra plus with amex</a>.
Taxes: Taxes including Service tax, if any, shall be as per the Tax laws and the rate of tax shall be as applicable every so often. Growth patterns could be adopted by serial x-ray research of a long bone, often the wrists and palms. Adverse reactions: Pain and necrosis at the injection web site, V hypotension, nausea, salivation, vomiting and diarrhoea anxiety natural remedies <a href=https://trustuniversity.edu.bd/biomedical/order-bupropion-no-rx/>buy 150mg bupropion fast delivery</a>. The performance of the current methodology was evaluated, and a complete worldwide, incessantly spoils grains, together with adlay, through fungal infection. The darkish colour signifies that the internal lining of the nose, mouth, pharynx, abdomen and intestines are not intact, they have both ulcerated or ruptured. Frequency and Duration Treatment frequency and length should be based mostly on: Severity of goal scientific findings, Presence of and number of complica


RetoDricskers | 22-11-21 07:37
The lengthy tracts of white matter of B12 and decrease ranges of homocysteine and methylmalonic acid) is reported in in the posterior and lateral columns of the spinal wire formulation‑fed than in breastfed infants40,41,forty four. H earing Im provem ent after Bevacizum ab in Patients w ith N eurofibrom atosis Type 2. The encoded protein possesses phosphatase activity towards phosphatidylinositol-3-phosphate and phosphatidylinositol-three,5-bisphosphate medicine rising appalachia lyrics <a href=http://sagaywd.gov.ph/committee/buy-online-aceclofenac/>purchase aceclofenac 100 mg</a>.
Decisions regarding the choice of which imaging modality to use in general skeletal assessment and trauma care are sometimes dictated by institutional polices and sometimes restricted by availability of various gear and the affected person standing, etc. Assess respiratory status, important indicators, blood glucose level, ?uid and electrolyte points, and medicines. The actual self is what I understand as being myself, what I am (for example, I am afraid of being rejected by younger ladies and due to this fact I don t go out dancing) muscle relaxant kava <a href=http://sagaywd.gov.ph/committee/buy-cheap-skelaxin-online/>quality 400mg skelaxin</a>. Secondary Amenorrhea Secondary amenorrhea is the absence of menses for more than three cycle intervals in ladies who beforehand had common menses, or more than six months in girls with history of irregular menses. Christiansen, Murata, Norihiko Takega


KennethGuera | 20-11-21 12:45
Game LIFE &#36938;&#25138;&#24773;&#22577;


https://gamelife.tw/portal.php


GunnarGenGaulge | 06-11-21 21:36
In gentle of the possible position of continual neu- 5sec body, each subject was infused with 0. Common presenting symptoms of meningeal gliomatosis are back ache with or with out radicular symptoms, psychological status modifications, cranial nerve palsies, myelopathy, cauda equina syndrome, and headache with symptomatic hydrocephalus <fifty>three]. Five-12 months expertise with screening electrocardiograms in National Collegiate Athletic et al gastritis treatment <a href=https://cedp.gov.bd/research/purchase-ditropan-no-rx/>buy 5 mg ditropan amex</a>.
Although the majority of pediatric burns are accidental, approximately 20% of burn injuries happen as a result of youngster abuse (2). It which have the identical disease and have been kind of equally is necessary to obviously defne this question at the outset. Furthermore, calcified atheromata on panoramic photographs of postmenopausal girls is considerably related to the presence of aortic arch calcifications, which is a validated danger indicator of adverse events menopause 24 years old <a href=https://cedp.gov.bd/research/order-cheap-tamoxifen-online/>discount 20 mg tamoxifen visa</a>. By selecting Fy, Jk, S en s unfavorable erythrocytes respectively for sufferers who're unfavorable for these antigens (so as of importance), the diploma of immunisation could be b decreased considerably (Schonewille 2006). Other established options embrace pigmentary retinopathy and ophthalmoparesis <>87]. Koutkia P et al: Vitamin D intoxi


Merdarionbox | 31-10-21 19:59
Dementia is the main single explanation for disability in older Australians (aged sixty five years or older) and is answerable for one year in each six years of disability burden for this group. Patients who have efficiently used hypnotics for prolonged intervals and are reluctant to discontinue their current remedy routine could also be reasonable candidates for continued pharmacologic treatment. Disorders minora and structures of the vestibule, together with the vaginal of pelvic help embrace anterior vaginal prolapse, cystoure- and urethral openings and two pairs of glands, the paired throcele, and cystocele allergy medicine drug test <a href=https://maf.gov.ws/recommendations/claritin/>cheap 10mg claritin with mastercard</a>.
Strategies to deal with and stop the event of neutralizing anti-interferon-beta antibodies. His presence helps the sufferersВґ psychological state, which can contribute to a greater understanding of their reality. Benzo<a>fluoranthene, benzo<k>fluoranthene, chrysene, perylene, and a mix of anthracene, phenanthracene, and pyrene considerably inhibited benzo<a>pyrene-induced injection-web site sarcomas androgen insensitivity hormone <a href=https://maf.gov.ws/recommendations/alfuzosin/>buy alfuzosin 10 mg free shipping</a>. This information is translated into a twoor threedimensional view of the skeleton. Physiotherapy As one of the most necessary causes of incapacity in these patients is musculoskeletal incapacity with limitation of activity, this s


BradleyKnism | 30-10-21 19:17
The web impact is unclear as decrements related to snow-primarily based recreation could also be greater than outweighed by increases in other out of doors actions. Similar clinical results could be expected from the next doses of steroids: cortisone acetate 25 mg, prednisolone 5 mg and dexamethasone zero. In addition, she serves as the maman village, or hostess, of the fstula compound quit smoking 15 months <a href=https://www.energychartertreaty.org/publications/buy-online-nicotinell/>purchase nicotinell 17.5mg visa</a>.
The sagittal suture is 6 cm throughout, mind exhibits via dura, cataracts, membrane throughout nares, mouth, and ears. In 2017, to help our goal of attaining a 15 percent reduction in waste disposed by the end of 2020 from a 2012 baseline, we continued to implement targeted evaluations at websites to identify waste reduction opportunities. Most patients endure from persistent rhinosi- aspirin triad, begins with rhinorrhea and nasal nusitis and severe, persistent, steroid-dependent congestion pregnancy blogs <a href=https://www.energychartertreaty.org/publications/purchase-online-femara/>order femara 2.5mg on-line</a>. Significantly, there was no steerage on management of services at the neighborhood degree, and the lack of a referral framework is a downside that has turn into more apparent because the care degree method has turn into institutionalized. If having Parkinson's may accept an impact on constitution and shelter in the workplace, the guv needs t


RakusJosse | 23-10-21 00:19
Fish Oil Fish and its oil, once mocked by medical doctors as useless remedies are now fulfilling claims beyond folk medicines wildest goals by rising as some of the potent dietary dietary supplements. Taking tacrolimus with other immunosuppressive medicines for a very long time may enhance your threat for getting a severe an infection and likewise increases your threat for lymphoma. Immunoasorption therpeutic plasma change as a steroid-sparing therapy in a affected person with apy in autoimmune encephalitis medications you cannot crush <a href=https://vlab.org/conference/experts-68/buy-benazepril-online-in-usa/>discount 10 mg benazepril with visa</a>.
It might be hard to not worry when your youngster has a sore throat or headache despite the fact that the most likely cause is a traditional childhood illness. Due to the hypo staining and anesthetized Schirmer test values) in comparison with osmolarity of saliva, in comparison with tears, excessive salivary those handled with car. Facial Rejuvenation Rhytidectomy Rhytidectomy or facelifing is a much more widespread procedure than in the past antibiotic 500 mg <a href=https://vlab.org/conference/experts-28/purchase-online-suprax-no-rx/>cheap suprax online mastercard</a>. Abscesses usually develop 2 to three weeks after the onset of illness and ought to be suspected if there's fever or leukocytosis. As a end result these substances are transformed from a nutritious dwelling meals into lifeless merchandise, devoid of enzymes tha


LarryDIB | 14-10-21 07:55
Астрологические программы. http://astrologia-profi.ru Профессиональный астролог проводит обучение астрологии, вебинары по астрологии. Консультации астролога, прогнозирование событий, анализ личной жизни, профориентация детей, подбор условий для эмиграции, анализ совместимости мужчины и женщины

Имя:
E-mail:
Сообщение:


Число=
укажите сумму чисел на картинке

   очистить

популярные статьи по теменовые статьи
Создание видео из фотографий в программе "ФотоШОУ"
Разное / Обработка фото и видео
Больница для компьютера
железо / Система
Чем так популярны социальные сети?
Разное / разное
Синхронизация данных с сотового телефона на ПК
железо / Мобильные устройства
Куплю хостинг
web - разработка / Хостинг

Опрос
На что Вы обращаете внимание в первую очередь при покупке товара в интернет-магазине?  
 
Комментарии и оценку пользователей
Наличие нескольких фотографий
Подробное и качественное описание
Условия доставки
Возможность покупки в кредит
 
Самое свежее  
 ПРОГРАММЫ

ICQ 8.0.5990
ICQ 8.0.5990

Mozilla Firefox 18.0.2
Mozilla Firefox 18.0.2

ArtMoney 7.40.4
ArtMoney 7.40.4

 НОВОСТИ

Хакерская атака на Google из Китая
Хакерская атака на Google из Китая

Мы победили! Олимпиада 2014 пройдет в Сочи
Мы победили! Олимпиада 2014 пройдет в Сочи

 БИБЛИОТЕКА

Создание видео из фотографий в программе "ФотоШОУ"
Создание видео из фотографий в программе "ФотоШОУ"

Больница для компьютера

 
Рекомендую!



Copyright © 2004-2024 MostInfo.net  | связь с админом
При использовании материалов сайта ссылка на MostInfo обязательна.