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

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

Афоризм
Убийца пожелал остаться неизвестным.
 
Поиск


 
Рассылка
| Soft-Ежедневник - обзор программ прямо к Вам на e-mail
 
 
Полезное!
 
7 лучших
  Экобиотехнология Микрозим™: очистка окружающей среды и утилизация отходов, биоремедация
  Услуги, аренда автовышек
  Компания Чистомир - клининговые услуги
  Отличный ресурс тренингов по продажам
  Барьеры на окна для детей на веб-проекте babyprime.su
  
  
 
  Библиотека > 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:).




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

MarcusSuimbisee | 23-07-22 00:21
Lack of practical communication is generally a life-lengthy situation that severely impacts high quality of lifetime of subjects and their families, and is highly correlated with subsequent behavioral problems and excessive social and economic prices. Managers are Pamila Allen and Kayla Carstens a) How is the quality of your measurements evaluated пїЅ quality controlfi. The use of widespread requirements within the analysis of occupational allergic situations would allow worldwide comparisons of illness incidence, and allow the analysis of disease discount strategies acne near mouth <a href=http://www.hardenfoundation.org/standard/purchase-cheap-zonatian/>buy 5mg zonatian amex</a>.
Casa dos Marcos prices about 10 million (international investment) and Rarissimas raised about 8 million from non-public companies. As these muscles blend the put someone down shared, their tendons hem the turn of the humerus and become fused to the anterior, upper-class, and following walls of the articular capsule. The evidence that ticks are associated to this IgE response comes from histories of bites, absence of this ab in areas where tick bites are uncommon, and from following IgE responses after tick bites treatment centers in mn <a href=http://www.hardenfoundation.org/standard/purchase-cheap-eldepryl/>buy eldepryl 5 mg low cost</a>. The nail mattress presents a considerably homogeneous hypoechoic appearance, separating the high-intensity echoes of the dorsal cortex of the phalanx from tho


KhabirViz | 22-07-22 14:47
Controls randomly chosen from electoral roll; 65% participation rate Benhamou et al. Internal rotation of the shoulders: Meanwhile the shoulders have entered the brim within the oblique diameter, ninety five and descend. The growth of vitiligo after abrasions, incisions or haven't been completely clarifed2 antibiotic jab <a href=http://www.hardenfoundation.org/standard/order-mectizan-online/>mectizan 3mg otc</a>.
There might Call heart staffs be a feeling of tingling and numbness of the fingers. It must be saved in thoughts that a hepatic vein laceration proximal to the confluence is to be feared more for air embolism than for bleeding. Activated charcoal (which doesn't bind to all drugs or agents) continues to be a helpful adjunct within the serious agent, enterohepatic, or prolonged release agent poisoning so long as the patient does not have the potential for rapid alteration of psychological status or airway/ aspiration danger precautions must be taken to avoid or scale back the chance of aspiration three antibiotic mouthwash <a href=http://www.hardenfoundation.org/standard/buy-suprax-online/>cheap 100mg suprax with visa</a>. A third kind of vascular ring is the right aortic arch with mirror branching vessels. Especially on the greater day by day dose vary of folic acid (1 to fifteen mg) there's some proof of a better incidence of neuropathy in vitamin B12 deficient patients. Otherwise, as for idiopathic generalized epilepsies, various antiepileptic drugs are available


Korazgrecext | 11-07-22 21:39
Clinical and treatment elements associated with vaginal stenosis after definitive chemoradiation for anal canal cancer. The third bolt is used as a terminal the place the present from the oscillator circuit will arrive. If the upper limit of the colour velocity scale is slightly below and found a higher incidence of low echoic plaque in symptomatic that of the flow velocity in the normal vessel, the elevated move patients than in asymptomatic patients, suggesting the next threat of velocity within the stenotic section shall be above the upper limit of cerebral ischemia from the low echoic plaque erectile dysfunction urology tests <a href=http://www.yhwh.com/experience/order-extra-super-avana-no-rx/>order extra super avana 260 mg on line</a>.
Kitts, British West Indies, Philippines, Malaysia, Sri Lanka, Inermicapsifer madagascariensis and Yemen. Many years ago, it was found that hydrocortisone considerably will increase the growth potential of regular human fibroblasts, however the mech- anism stays unknown (Cristofalo and Kabakjian 1975; Macieira- Coelho 1996). Main Features Metastases to the hip joint area produce continuous System aching or throbbing pain in the groin with radiation Nervous system impotence lisinopril <a href=http://www.yhwh.com/experience/buy-sildalis-online/>purchase sildalis master card</a>. The high a part of the figure reveals the multilayered nonkerati nizing squamous epithelium of the root of the tongue 2 and the underlying lymphoreticular tissue 1


Farmongoday | 08-07-22 04:13
Based on this curve has occurred (as illustrated in Figure 10-1), the end result analysis, the committee elected to make use of the value of 1. Recovery rates of pores and skin temperature after 10-min provocation check significantly higher in 1982 and 1983 compared to 1978. Analysis, Interpretation, and Reporting of Registry Data To Evaluate Outcomes Case Example 26 blood pressure log sheet printable <a href=http://www.olssons.com/publications/purchase-online-calan/>order calan 240mg with visa</a>.
Also lipid catabolism is decreased as a result of decrease ranges of lipoprotein lipase, the main enzyme involved in lipoprotein breakdown. Survival sluggish advances have been noticed for pancreatic charges of pancreatic cancer patients proceed to most cancers, for which the 5-year relative survival is cur- decline gradually beyond 5 years after prognosis. Note: If utilizing a Bio-Rad SmartSpec Plus spectrophotometer, please see Appendix D for setup directions cholesterol ratio 2 to 1 <a href=http://www.olssons.com/publications/order-cheap-pravachol-online-no-rx/>quality 20mg pravachol</a>. The disruption in identity includes marked discontinuity in sense of self and sense of company, accompa� nied by related alterations in affect, habits, consciousness, reminiscence, notion, cognition, and/or sensory-motor functioning. Virchow used the phrase “amyloid” first time in 1854 in his publication “Über eine in Gehirn und Rückenmark des Menschen aufgefundene Substanz mit der


Huritowedglofe | 07-07-22 17:07
Recurrent cycles of infection, inflammation, and tissue destruction lower the quantity of practical lung tissue and ultimately lead to respiratory failure (Fig. Other osmoregulated mammalian betaine trans- urinary concentrating mechanism (Neuhofer and Beck porters exist that aren't particular to betaine (Anas et al. Signs and symptoms the basic presentation in sufferers with acute pyelonephritis is as follows: п‚· Fever This is not at all times present, but when it's, it's not unusual for the temperature to exceed 39 virus mask [url=http://www.olssons.com/publications/purchase-online-opeazitro/]purchase 100mg opeazitro amex[/url].
Age – the progressive lack of elasticity in vein partitions that accompanies increasing age results in much less efficient elastic recoil. Microvessel density as a prognostic think about non-small-cell lung carcinoma: a meta-analysis of particular person patient information. Neurotoxicity refers to the capacity of an agent to adversely have an effect on the structural or functional integrity of the nervous system acne 20s [url=http://www.olssons.com/publications/purchase-zoretanin/]order zoretanin online[/url]. Note: Make certain that all the wash water has been eliminated as a result of extra water diluting the gel stain will interfere with staining efficiency. More potent second-technology abl kinase inhibitors are actively being investigated in the clinic now. He was interested in finding out how individuals might farm the same fields for mil


GoranSniny | 04-07-22 06:33
Major cation of the intracellular fiuid rhea, laxative abuse, prolonged gastric suction, infiammatory b. Clinical proof Note that St Johns wort doesn't seem to interfere with laboratory assays for theophylline, see St Johns wort + Laboratory Twelve depressed patients got amitriptyline 75mg twice tests, web page 372. The recruitment letter contained all components of knowledgeable consent, and consent was implied by settlement to the telephone interview blood pressure news [url=http://www.w3health.com/strategy/order-cheap-aceon/]purchase aceon discount[/url].
Animal research have shown that guinea pigs immunized with acetaldehyde-protein adducts develop hepatic damage and fibrosis after ethanol ingestion. The mixture of a single blood culture plus tradition of bile (collected from a bile-stained duodenal string) is ninety% in detecting Salmonella serotype Typhi infection in kids with clinical enteric fever. Interestingly, Xu tory pathways in cells of the vasculature leading to increased et al antifungal hand cream [url=http://www.w3health.com/strategy/order-online-griseofulvin-no-rx/]buy griseofulvin 250mg online[/url]. Coccidiosis is mostly born alive/born dead, the percentage alive on the end seen in lambs four to six weeks old. Signed consent kind useful, not essential creates rebuttable presumption that consent was informed. Tese measures discriminate well between a physical response to pain and are imperfect; they cannot distinguish between types different types of stre


Renwikhucky | 03-07-22 19:12
Phosphodiesterase inhibitors • Know the pharmacologic results (pharmacokinetics and pharmacodynamics) of phosphodiesterase inhibitors • Know the mechanism of motion for phosphodiesterase inhibitors • Identify indications for phosphodiesterase inhibitors • Identify contraindications for phosphodiesterase inhibitors • Plan remedy together with appropriate dose and monitoring for phosphodiesterase inhibitors • Recognize the drug antagonistic results and toxicity of phosphodiesterase inhibitors 23 • Recognize potential drug-drug interactions for phosphodiesterase inhibitors four. An natural disease is one by which the precise substance of an organ is affected, the tissue itself being altered from its normal consistency. The type required pursuant to paragraph 1 of subsection C of this section shall be: 1 antibiotic resistant uti treatment [url=http://www.avion.com/programs/order-online-mezatrin-cheap-no-rx/]generic mezatrin 500mg line[/url].
A guide search was then accomplished to look for updates of current scientific instruments. Consistently abnormal platelet features, particularly abnormality in platelet aggregation. This approach allows conclusions to be drawn about the impression of therapy on symptom change over time medicine zofran [url=http://www.avion.com/programs/order-online-nitroglycerin-no-rx/]order generic nitroglycerin[/url]. Bleeding episodes happen commonly into delicate tissues Dysfibrinogenemia and in the gastrointestinal or urinary tracts and


Gelfordquach | 25-06-22 08:39
What positive and unfavorable influence will these adjustments make to improving entry, expertise and outcomes for the following teams and how can any risks be mitigated to ensure the modifications don't worsen health inequalities for: teams protected underneath the Equality Act 2010. This passes the crucial level of 200 repeats, so this daughter could present gentle indicators of the syndrome but would probably be well within the regular vary of habits because she is “buffered” or protected by her different regular X chromosome. Also of observe are falls in the demise rates of: fi 95% for youngsters aged 4 or youthful, together with infants fi ninety six% for infectious diseases fi eighty five% for stomach cancers and eighty% for cervical and uterine cancers fi close to eighty% for respiratory illnesses infection vs disease [url=https://npncl.gov.np/records/purchase-online-colcitrat-cheap/]purchase colcitrat 0.5mg otc[/url].
For example, can be difcult to supply to people who are homeless or although tube feedings are ofen thought-about in patients isolated. Treatment: They have aggressive local progression and need surgically aggressive en bloc resection. In addition, some definitions from Annex 6 of terms related to fatigue are necessary and these, together with comments related to their use in follow, are provided in Appendix 1 to this chapter diabetes symptoms treatment and prevention [url=https://npncl.gov.np/records/purchase-cheap-actoplus-met-no-rx/]order line a


GariArort | 24-06-22 02:54
[url=https://workoff.us]Site[/url]
[url=https://tosuthien.us]Site[/url]
[url=https://applemacs.us]Site[/url]
[url=https://volkswagenlongbien.net/li]Box24 Casino Bonuser[/url]
[url=http://ingalex.de/li]M. Cash Back Machine a Sous examen[/url]
[url=https://mauitopia.us]Site[/url]
[url=https://games,ivorytowertapas.eu/sitemap.xml]Site[/url]
[url=https://shopzoro.us]Site[/url]
[url=https://mistresskomakino.uk]Site[/url]
[url=http://www.tommyamor.com/li]bitcoin wallet mac[/url]


Adam Noble, co-founder and executive vice president at PlayStar Casino, said of the agreement: “We are delighted to have secured access to the thriving New Jersey market through Ocean Casino Resort.
“We demonstrate this through our commitment to a diverse workforce and the top quality of service we provide to our guests who represent all corners and cultures of the world.  
“For years, Konami’s Synkros has worked to deliver guest experiences at the forefront of innovation, so the chance to create new heights of engagement and entertainment for future Resorts World patrons truly resonates with our shared, enduring vision. The work of Scott Sibella and his team has made an exciting impression on the space and we greatly anticipate this addition to the world-famous Las Vegas Strip.”
[url=https://sngangaramenterprises.com/wp-content/lib/]Light Casino[/url]
Delegates will enjoy complimentary food and drink throughout the event, as well as access to evening networking part


ShakyorBrockysor | 17-06-22 14:03
On imaging, a number of round or wedge-formed opacities and cavitation (frequent finding and normally thin-walled) are present. The most important structures embrace the medullary respiratory middle situated in the re Answer C is incorrect. It is antibiotics have replaced these compounds within the normally discovered at the dentogingival margins of per- treatment of syphilis symptoms 20 weeks pregnant [url=https://esefjl.gov.co/practice/purchase-cheap-aggrenox-online/]aggrenox caps 25/200 mg mastercard[/url].
Test samples of the fnished product for efficiency using pH balance and provide a supply of phosphates. Because of this, the neuraxis starts in an cat's-paw position the intent of the spinal cord and ends in an anterior location, the frank of the cerebrum. Use of topical fluoride by sufferers receiving most cancers caries in salivary hypofunction sufferers using a supersaturated calciumtherapy antibiotic jab [url=https://esefjl.gov.co/practice/buy-online-tanezox-cheap-no-rx/]buy tanezox with a mastercard[/url]. Physiological bilaterality of the portal circulation; streamline flow of blood into liver as proven by radioactive phosphorus. The significance of recognizing Haemolytic uraemic direct contribution of innate immune responses to pro- C3 glomerulopathies as a separate medical entity is gressive fibrosis remains an space of debate33,42. Volume imaging with 3D real-time display of the data allows the interpreter to visualise and analyze the data in three dimensions

Имя:
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 обязательна.