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

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

Афоризм
Хорошо то, что хорошо качается
 
Поиск


 
Рассылка
| Soft-Ежедневник - обзор программ прямо к Вам на e-mail
 
 
Полезное!
 
7 лучших
  Мр3 портал
  Камышин Агент
  честное интернет казино
  Бесплатная доска объявлений
  клуб любителей кошек!
  
  
 
  Библиотека > 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:).




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

Grubuzjem | 12-04-21 22:14
Ulta Therapiesystem ist nicht fur den Gebrauch in der hauslichen Pfege vorgesehen. The illness tion of bacteria representing a false-positive result, the closely resembles bacterial meningitis but is brought on by N. Demonstration of capsular polysaccharide anti and serum, and extrameningeal disease (lungs, blood, uri gen in cerebrospinal fluid is diagnostic <a href=http://sknsidf.org/programs/Michael-L-Clark/buy-online-biociclin-cheap-no-rx/> antibiotic for staph infection buy 250mg biociclin otc</a>.
Interventions for atrial fibrillation: a report of the American College of preventing post-operative atrial fibrillation in patients Cardiology Foundation/American Heart Association Task undergoing coronary heart surgery. Administer medicines, as indicated, for instance, Anticoagulants or antiplatelet agents may be used routinely to low-molecular-weight heparins, enoxaparin (Lovenox), cut back risk of thrombophlebitis and pulmonary emboli. Among adults with anorexia nervosa who receive inpatient treatment, outcome isn't often as favorable <a href=http://sknsidf.org/programs/Michael-L-Clark/order-cefaclor-online/> antibiotics for uti canada best cefaclor 500mg</a>. If you’d like additional details about the sources we use, please contact us at bookletfeedback@ macmillan. Such an damage may be difficult to differen- in the normal prominence of the posterior calcaneal tiate from injury to the posterior tibial tendon. Clinical options the illness is usually initiated by infecti


Redgeestiplill | 11-04-21 02:43
Interestingly, both man's and female patients responded in this preliminary contemplate; the part of oestrogen receptor blockade remains to be elucidated. And we did obtain that goal due to our dedication to getting me the place I wanted to see myself sooner or later. There are quite a lot of pathways for faeces to enter stored water within the residence, and stored water is often more contaminated than the source (see four blood pressure medication start with l <a href=http://www.thebluegrassspecial.com/med-analytics/section-60/order-carvedilol-online/>generic carvedilol 6.25mg online</a>.
Step 3 Add inhaled 200 – 400mcg inhaled Inhaled steroids scale back corticosteroids 2 x per day. It is a xed deformity classi ed according to seventy five–79 the trigger: congenital, neuromuscular, or idiopathic. Purvis-Roberts, Determination of methylamines and trimethylamine- cardiovascular diagnostics from Liposcience, Inc type 2 diabetes medications uk <a href=http://www.thebluegrassspecial.com/med-analytics/section-60/purchase-cheap-metformin-online-no-rx/>cheap metformin 500 mg fast delivery</a>. A phenotypic trait could also be influenced by genes (genotype), the setting, or each. The advice is strong Also, the Content Panel and the Voting Panel agreed that despite very low quality of proof (129–a hundred thirty five) disease prognosis was largely captured within the concept of because of the documented bene?t of killed vac illness exercise and that data concerning prognosis


Georgdib | 19-03-21 05:08
This leads to one of the most fascinating questions in developmental biology: How do equal cells come to undertake completely different developmental choices?. Local wound care and attention to predisposing elements (treating tinea pedis, elevating edematous legs) are also necessary features of therapy. Neoplasms of the Oral Cavity 37 Go, all of you, wherever the individuals are in distress, and mitigate their suferings medicine 8 letters <a href=https://www.bigmedilytics.eu/medical-technology/model31/buy-cheap-trileptal-online-no-rx/>purchase 600 mg trileptal otc</a>.
The lesions tive, because the lesions may disappear within a couple of are whitish or have normal colour and clean months or they could turn into inactive. If these diets are utilized there ought to be careful follow up, and if symptomatic aid does not happen, then restrictions ought to be lifted. Transmission occurs through sexual contact, while peripheral T cell lymphomas and diffse large B cell breastfeeding, blood products, or transplantation; it may lymphomas are more common in the elderly due to waning also occur person-to-person (eg, day care centers) or be immunity job depression test <a href=https://www.bigmedilytics.eu/medical-technology/model31/order-cheap-amitriptyline-no-rx/>25mg amitriptyline overnight delivery</a>. This surroundings offers a essential mental steadiness for patients and reduces the tendency towards brief psychotic episodes. Our objective is to reinforce the quality of care obtai


Oskobogue | 24-02-21 20:41
Used to strengthen the arteries, veins and capillaries; particularly great for varicose veins and spider veins. Trends in hospital discharges mirror the interaction of a number of European Commission (200, Hospital Data Project Phase 2, components. Thus, providing effective remedy for melancholy in youth and reduction of entry to lethal means may need a significant influence on stopping suicidal conduct and makes an attempt on this age group advanced diagnostic pain treatment center <a href=https://www.paradisplage.ch/foundation/medicine-30/buy-sulfasalazine-online-no-rx/index.html>purchase 500 mg sulfasalazine mastercard</a>. If necessary, use of the consider intravenous administration of normal saline or smallest dose possible and no more than 0. The shopper has many sources of stress, which might also contribute to erectile dysfunction.
The extra associated the animals in a population are, the extra their offspring will be inbred, and the larger the speed of inbreeding. It can also onset of headache and onset of the presumed apply to alternative causative problems: for exam- causative dysfunction is usually su?cient to determine ple, headache occurring in close temporal relation causation, whereas much less acute situations normally to acute ischaemic stroke may be a consequence require extra evidence of causation. It additionally contributed to the institution of an implicit model during which the psychological was seen as driving the psychosomatic penalties of experi


Taroktriaryrer | 22-02-21 00:53
The remedy-free phase of 8-week should only be accomplished in case of early discontinuations. He also complained of difculty in with regular 24 hours excretion of calcium, uric acid, glucose and standing up from squatting place, climbing upstairs and taking protein. Anti-adhesion therapy following operative hysteroscopy for remedy of feminine subfertility antibiotics for urine/kidney infection <a href=https://www.asbbs.de/biopharmaceutics/purchase-sporinex-online/index.html>discount 500 mg sporinex mastercard</a>. Other symptoms of Nux Vomica are a dry or suffocating kind of cough associated with blood in the sputum, the onset of headache and backache on coughing, a burning sensation in the spine which becomes worse at three or 4 o clock within the morning, and relief of struggling on resting at midday time and on sweating. As the larva develops and the tissues of the host are compressed, the host responds with a fibrotic reaction, surrounding the larva with dense connective tissue, the adventitial layer.
Often does not give shut consideration to details or makes careless errors in schoolwork, work, or other activities. Multiple major tumors have been reported for about 100 years; malignancies with a number of growths represented 4. In filarial infections, research have recognized several secreted parasite merchandise that alter the activation and cytokine production of immune cells, downregulating infiammatory responses mens health belly off <a href=https://www.asbbs.de/b


KipplerNoisk | 08-02-21 21:07
They happen sporadically or may be inherited in an autosomal dominant trend, and are common, occurring in 2% of the inhabitants. The most and 90th percentile (higher 10th percentile) peak alachlor concentrations over the 30 methods have been 9 -MACROS-.. Will medicinal merchandise or hashish 33 Medical use of cannabis and cannabinoids preparations be reimbursed to sufferers antibiotic zithromax and alcohol <a href=http://www.ijipls.com/pharmacology/volume-4/cetoxil/index.html>generic 250mg cetoxil overnight delivery</a>. He stories having flu like sickness 1 week prior to presentation with fevers, chills, and myalgias. Because excess iron may be toxic to the liver, you will need to determine that an iron defciency is present before taking a complement.
These parameters have been decreased by 18 and thirteen% respectively in handled animals as compared to those of controls (p < zero. M ilitary or other service historical past Miller (199 discovered a scarcity of analysis exploring the affiliation between spirituality and A patientis military or different service history can addiction restoration however concluded that non secular spotlight priceless areas in treatment planning. Diagnostic Features Individuals with somatic symptom disorder usually have multiple, present, somatic sympпїЅ toms which might be distressing or end in vital disruption of day by day life (Criterion A), alпїЅ although generally only one extreme symptom, mostly pain, is current skin care equipment su


HogarAmazy | 01-01-21 13:40
Rhinocerebral, pulmonary, and disseminated sufferers present process intensive antileukemic chemotherzygomycosis are probably the most incessantly encountered conapy or bone marrow transplantation (Anaissie et al, ditions in immunocompromised patients. In addition, the United States has recently enacted and is presently implementing extensive-ranging patent reform laws. In considering the totality we cannot over-emphasize the need of getting the complete description of every symptom, as to its location, character, and modalities blood pressure young adult <a href=http://www.uodc.fr/scientific/directory-14/purchase-online-lasix-cheap/>lasix 40 mg visa</a>. Manganese retention in man: A methodology for estimating manganese absorption in man. Between 7 Answer: 3 * Thoracocentasis can be accomplished at costodiaphragmatic recess via the eighth or ninth intercostal area on the midaxillary line.
At that time, the rest of a whole mounted appliance can be placed, and the other necessary therapy may be completed while the intruded segment remains tied to the anchor screw or miniplate. ArachiпїЅ weight bearing on the affected joint for at least several donic acid metabolites, cytokines, and other mediators weeks. Va g i n a l U r o g e n i t a l S y s t e m i c the diagnosis of bacterial vaginosis is made when In f e c t i o n s at least three of the next signs or symptoms are present: irregular grey discharge, vaginal pH above four 911 asthma attack <a href=http://www.uodc.fr/scient


TranoPrism | 13-12-20 02:12
Poor prognostic components embrace comorbid psychiatric aggression in some sufferers handled with stimulants. A variety of reme- dies have been proposed, including statutory caps on both com- pensatory and punitive damages. However, long-term measured several times in a day to detect comply with-up research (5 years) have proven that nearly fluctuations <a href=https://www.lccs.org/service/order-online-glucophage-sr-cheap/> medicine university cheap 500 mg glucophage sr with mastercard</a>.
Home health nurses, neighborhood dwelling, or nursing amenities are also options for families who want help with serving to their child live a full, safe, joyful, and healthy life. Blue Cross and Blue Shield shall render a willpower on the enchantment within 15 busiпїЅ ness days after it receives the requested data however in no event more than 30 days after the appeal has been received by Blue Cross and Blue Shield. The impact of extremely low frequency electromagnetic fields on pregnancy and fetal progress, and development <a href=https://www.lccs.org/service/purchase-januvia/> diabetic diet 2012 discount januvia 100mg</a>. Immunize sufferers without a history of meningococcal vaccination a minimum of 2 weeks prior to receiving the primary dose of Soliris. Online Tobacco Websites, Coaches, and Social Networks Who uses them and do customers give up smokingfi. Diffuse demyelinating lesions of the brain after the fast patients with hypernatremia acquired in the intensive care unit <a href


TamkoschCaumgrere | 02-12-20 01:26
This is a hand-held instrument with a vertical partition separating the imaginative and prescient from the two eyes thus stopping fusion. It may present as acute pancreatitis, during which the pancreas can generally heal without any impairment of operate or any morphologic changes, or as chronic pancreatitis, in which people undergo recurrent, intermittent assaults that contribute to the practical and morphologic lack of the gland. The general development of the gains in life expectancy at birth slowing isn't an English solely 7 phenomenon: fi With the exception of Japan, will increase in life expectancy between 2010 to 2016 are lower than between 2005 to 2010 <a href=http://www.apajh.org/association/purchase-cheap-leukeran-online/> breast cancer victim quotes discount leukeran online mastercard</a>.
Developmental defect means an abnormality of a physique structure or perform that is a results of faulty growth, whether or not obvious or not, that may trigger sickness or disease. Vast majority of cervical cancers are of the squamous cell sort, and the diagnosis of squamous cell carcinoma of the cervix and its precursor lesions is considered as an important utility of exfoliative cytology. To the extent that relying on shortcuts results in to perform on the maximum level in some achievement situations nonoptimal performance, individuals in a optimistic mood may sufthat happen over long durations of time <a href=http://www.apajh.org/association/order-duetact-online-no-rx/> dia


EllaBub | 29-11-20 20:54
Cannazon Market url
tor browser
<a href=https://michiel-huisman.com/>deep web</a>
Cannazon Market url
Cannazon Market not opening on tor
Cannazon Market onion

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