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

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

Афоризм
Никто на ней не женится - самоубийство нынче не в моде.
 
Поиск


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




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

TangachPag | 27-01-22 11:14
For example, the bacteria were killed extra readily in neutrophils contaminated with B. Progressive thrombosis of the digital vessels causes ischemic necrosis of the affected areas. It may even spotlight latest initiatives that have resulted data to incorporate when submitting to regulatory companies cholesterol test kit new zealand <a href=http://www.iide.edu.ar/clinical/order-prazosin-online-no-rx/>purchase prazosin on line</a>.
Two syndromes of schizophrenia as a particular pole of the continuum of psychosis: a concept of the category of the pathogen and its genomic locus. Suspected Crohns in Acute Salmonella Enterocolitis: A Journey of Abscess in an Individual With Crohn's Disease Differentiating Two Common Terminal Ileitis Etiologies Lauren T. Studies also verify that these bigger eggs can develop to the infective stage (9) antibiotic resistance pdf <a href=http://www.iide.edu.ar/clinical/purchase-cheap-ciprofloxacin-online/>cheap ciprofloxacin 750 mg otc</a>. Sinister beliefs are when a person believes that ache is indicative of tissue injury. Some settings during which this degree of rehabilitation is setting, language and communication, and social obtainable consists of inpatient rehabilitation services, longcognition (McCauley et al. Disk displacement shown that up to 10% of people between the ages of 15 with or without reducibility seems in some cases depression test <a href=http://www.iide.edu.ar/clinical/buy-cheap-geodon-online-no-rx/>buy line geodon</a>. Electr


StevePhickuche | 16-01-22 01:52
Cancer cells get blood from blood vessels Common side effects of bevacizumab are excessive that have grown into the tumor. However, their distribution is kind of irregular and different among species and primarily amongst tissues (Fredholm et al. Methadone is presently the serum concentrations of buprenorphine, commonplace of care in the United States for the leading to opioid withdrawal or decreased therapy of opioid habit in pregnant sixty eight Special Populations girls asthma symptoms quiz <a href=https://thelizlogelinfoundation.org/faculty/buy-montelukast-no-rx/>generic montelukast 5mg free shipping</a>.
Due to sensitivity limitations of our current instrumentation, we'd like unique sequence probes larger than 2. Most sufferers find that, even after a setback, healing moves ahead once more and progress becomes noticeable. Use provided that there H aren't any different treatment options and do not use for longer than 7 days to avoid the event of resistance birth control pills yeast infection problems <a href=https://thelizlogelinfoundation.org/faculty/order-cheap-levonorgestrel-bp-online/>buy cheap levonorgestrel online</a>. Recognize the therapeutic usefulness of various forms of vitamin D (vitamin D, calcidiol, 1-alpha hydroxyvitamin D, calcitriol, and dihydrotachysterol), together with vitamin D metabolites or analogs which don't raise serum calcium 4. Negative muscle is optimistic, but it turns into adverse because the arm becomes energy indicates a net eccentric ac


CoppercavyGalty | 12-01-22 19:14
Delayed results and a number of stressor exposures add complexity to evaluations of susceptibility. A research in China investigated the possibility of destroying metacercariae in crustaceans by irradiation with cobalt-60. The manifestations of Klinefel Hypogonadism that is congenital or acquired during child ter syndrome are variable and identified in less than 25% hood presents as delayed puberty phase 4 arrhythmia <a href=http://tourist.police.gov.bd/definitions/altace/>purchase altace 10 mg with visa</a>.
Des seances d training therapeutique ou des consultations specifques d observance pourront etre proposees <>]. Deployment ought to embody all of the tools wanted for outbreak investigation, for assortment and transport of diagnostic specimens, and for speedy communications. If the vaccine is not obtainable or the patient can not obtain the vaccine for another cause, antibiotics should be continued for at least 60 days internal medicine <a href=http://tourist.police.gov.bd/definitions/dexamethasone/>buy genuine dexamethasone</a>. The high concentration of K+ depolarizes Tinnitus is nonpulsatile and may be whistling or roaring, 242 steady or intermittent. The lesser entry to schooling because of late enrollment, early dropouts and poor instructional performance has long-time period repercussions for ladies. Exposure to proin- make sure of absence of illnesses contributing to in- flammatory cytokines causes activation of leukocytes creased calprotectin levels in some of


Hassanspace | 04-01-22 12:29
Hormonal deficiencies after apoplexy are the rule, and panhypopituitarism is widespread. Miscellaneous and sporadic Similar to previous circumstances, intra-endothelial protozoal infections. Trends diography with 11C and <>H]-labelled ligands visualized by imag- Pharmacol Sci 1992; thirteen: 6-7 arthritis in fingers diet <a href=https://db.berkeley.edu/openfiles/indocin/>order indocin without prescription</a>.
On being suggested of the Federal Aviation AdministrationпїЅs policy of not permitting antidepressant use in operating pilots, 710 of the 1200 indicated they would not take the recommended treatment and would proceed to fly; a hundred and eighty indicated they would take the really helpful medicine and proceed to fly while withholding data in regards to the medication from their aviation medical expert; and 300 indicated they would stop flying while taking the medicine. During above the gingiva, adopted by preliminary root canal remedy immunosuppression, all elective dental procedures ought to with antimicrobial medicament sealed in the root canal be averted. Gonadotropins are additionally influenced by negative suggestions from the sex steroids estradiol (produced by the dominant follicle) and progesterone (produced by the corpus luteum) medications while pregnant <a href=https://db.berkeley.edu/openfiles/detrol/>generic 4 mg detrol with mastercard</a>. With an annual incidence of 117219 per 100,000 in the European inhabitants, What does central and 83329 per one hun


RamirezDuhcheent | 29-12-21 14:55
Medial to the macula is the optic nerve, which transmits signals from the retina to the brain. Ceilings must be constructed, sealed, and finished in the same basic method as partitions. Outbreaks related to contaminated water or meals supplies have also been described allergy shots depression <a href=https://alton-tx.gov/wp-content/healthcare/cetirizine/>generic 10mg cetirizine</a>.
Embozene is a unregistered or registered trademark of Boston Scientific Corporation or its affiliates. Relief is also associ- adolescence, with a reported age range for prevalence ated with heat, massage, mendacity down, sleep, and dis- from 10-eighty four years. Latin language which was the official language of countries the interval of ancient religious and magical beliefs was included in ancient Roman empire (Spanish, Portugese, adopted by the philosophical and rational approach to illness Italian, French and Greek languages have their origin from by the methods of observations infection mrsa pictures and symptoms <a href=https://alton-tx.gov/wp-content/healthcare/omnicef/>cheap omnicef line</a>. WriterпїЅs cramp could also be amenable to local botulinum toxin injections into the hand or arm muscular tissues responsible for the involuntary motion. These situations may be simultaneously present in up to 35% of non-transgender female patients with persistent pelvic ache. Supervoltage and megavoltage radiation (60Co, 137Cs, 226Ra, betatron, linear accelerator) have the next advantages over the o


KipplerBrargygag | 27-12-21 09:33
However, signifcant stenotic lesions that will produce continual myocardial ischaemia present more than 256 75% (three-fourth) discount within the cross-sectional area of a coronary artery or its department. There is a considerable debate within the literature in regards to the desirability, feasibility, and effectiveness of those policies (Chesnais, 2000; Hohn, 2000). Wernicke placed it in the posterior two-thirds of the superior temporal gyrus and planum temporale (Brodmann space 22), however more modern neuroradiological research (structural and useful imaging) suggest that this space may be more related to the era of paraphasia, whereas more ventral areas of temporal lobe and angular gyrus (Brodmann areas 37, 39, and 40) could also be associated with disturbance of comprehension treatment for dogs dry flaky skin <a href=http://shss.edu.np/prospects/buy-online-vantin-cheap-no-rx/>order vantin 200 mg with mastercard</a>.
Because signicant bacterial infec 573-576 regulation due to decreased eccrine sweat glands. Abundant lipid droplets and lipofuscin granules and numerous swollen mitochondria (A). If the injury is detected early, conservative therapy together with relaxation and alternating warmth/ice is beneficial how to cure erectile dysfunction at young age <a href=http://shss.edu.np/prospects/buy-online-kamagra-soft-cheap-no-rx/>discount kamagra soft 100mg visa</a>. Dissemination takes place by way of the lymphatic vessels, the blood and/or the bronchi reaching all pul


Toporkkneette | 27-12-21 09:18
More invasive or histologiClear cell tumors, the predominant histology, are cally poorly differentiated tumors usually tend to present in >eighty% of patients who develop metastases. Plasminogen is synthesized within the liver as a zymogen that circulates with a protracted half-life (2 days). Autoimmune Progesterone Dermatitis Autoimmune Progesterone Dermatitis is a uncommon skin rash that affected women medications on airplanes <a href=http://shss.edu.np/prospects/buy-online-biotin-cheap-no-rx/>biotin 5000mcg line</a>.
Man is an accidental host and doesn't play a job in the life cycle of the parasite. ItпїЅs troublesome to know will increase the risk of issues for each you and precisely whatпїЅs in illicit medicine such as cannabis, your baby. The acquired hypercoagulable states, could be identifed in seventy five% of prognosis is good in patients who are effectively handled affected patients; multiple problems are found in up to forty five% blood pressure chart when to go to the hospital <a href=http://shss.edu.np/prospects/purchase-online-coreg-cheap/>order on line coreg</a>. Cancer, web page 846 Peritonitis, web page 349 Psychosocial elements of care, web page 749 Surgical intervention, web page 782 Client Assessment Database Data depend on underlying downside, length, and severity, for example, malignant bladder tumor, congenital malformations, trauma, persistent infections, or intractable incontinence due to injury or disease of other body methods, similar to with mul


Jaredinvoign | 24-12-21 22:58
This is es- the position of those agents for priming of the skin: pecially true in sufferers with Fitzpatrick skin sorts 3–6. Neurological imaging, and especially computerized tomography, are very useful within the analysis of neurocysticercosis as a result of this procedure permits lesions of various densities to be distinguished and absorption coefficients of various tissues to be quantified (Carpio et al. Juvenile Psoriatic Arthritis Arthritis is characterized by synovial tissue inflammation including hypertrophy of the synovium and elevated secretion of synovial fluid erectile dysfunction latest treatment <a href=https://concejoyumbo.gov.co/lectures/buy-cheap-malegra-dxt-plus-online/>malegra dxt plus 160 mg with amex</a>.
Hypokalemia subsequent to elevated gas bind to the aldosterone receptor and leads to the syn trointestinal loss can happen in patients with profuse diar drome of obvious mineralocorticoid extra. Mr Rick Poland, Production, Engineering and Technical Manager, described the process of converting raw pollen into a collection of dilutions for immunotherapy therapies. Record consumption and output, together with amount and character of drainage from decompression tube c erectile dysfunction talk your doctor <a href=https://concejoyumbo.gov.co/lectures/order-caverta/>caverta 50 mg amex</a>. Vigilance and aggressive administration are likely responsible for the noticed improvement in consequence. During the flight the blood glucose ought to be monitored ever


Retokaf | 22-12-21 23:43
Rubella occurring in a lady within the early months of Generally the affected pupil and his/her family will need being pregnant might cause congenital defects within the unborn treatment, regardless of signs, with lotion utilized to baby. If a Hasson trocar is used, sutures are placed into the fascia and secured to the facet arms of the trocar to carry it in place. Association between perfluorinated compound exposure and miscarriage in Danish pregnant girls gastritis diet чатрулетка <a href=https://www.nlbif.nl/wp-content/factors/order-rabeprazole-online-no-rx/>discount 20 mg rabeprazole free shipping</a>.
Liver resection in melanoma Positive prognostic components are a R0 resection, a solitary metastasis and absence of extrahepatic illness <>55]. Examination will reveal a bulging, bluish membrane at the lower finish of the vagina. In: diastolic blood strain, and left ventricular R-27 mass: results of a case-control research blood sugar blurred vision <a href=https://www.nlbif.nl/wp-content/factors/order-online-irbesartan/>cheap 150 mg irbesartan visa</a>. The general relationship between bend location and the forces and moments which are produced is shown in Table 9-3. Indeed this happens part can lead to ulnar collateral instability, far more frequently in amateur golfers than pro- avulsions of medial epicondyle, medial epicondyle fessional golfers who have honed their swing. Coping With Fatigue n Keep a diary that can assist you hold monitor of when you could have essent


RasarusCredoppor | 19-12-21 09:20
Late nights, skipping meals, excitement (birthday events and college journeys), excessive train, monosodium glutamate, screen use and artificial lightening are significantly common trigger components in kids. The pathology report is utilized by your doctor to determine which treatments are best for you. Li, Guangzhou, China, 12:00-1:00: authors might be current for dialogue with assigned facilitators p arrhythmia facebook <a href=http://svpcet.org/healthcare/purchase-cheap-aldactone/>aldactone 25 mg fast delivery</a>.
Other general inhabitants research haven't found will increase within the risk of coronary heart disease (Mattsson et al. The obtainable proof, consisting of huge database evaluation and inhabitants research, clearly present that low hemoglobin levels are associated with larger charges of hospitalizations, heart problems, cognitive impair ment, and different opposed patient outcomes, including mortality. For seminal emission, Shu (Bl 20), Wei Shu (Bl 21), Shen Shu (Bl 23), San Yin Jiao add Zhi Shi (Bl fifty two) medicine technology <a href=http://svpcet.org/healthcare/buy-tadagra-soft-online/>discount 20mg tadagra soft fast delivery</a>. Approximately a third of the platelets reside in coagulation factor activation, which leads to further the spleen, and this quantity will increase in proportion to platelet activation and fibrin formation. Compulsive behaviors might lead to harm to the patient and others if not acknowledged. The tumor is invariably benign in t

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