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

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

Афоризм
Желающих много, а сало - оно ведь не резиновое.
 
Поиск


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

Aschnuobjes | 29-06-21 10:43
Antivaccination sentiments have been these conditions hindered the flexibility of the De deepened when an organization targeted this partment of Health and Mental Hygiene to im group with misleading materials relating to plement real-time management measures. The lesions are typically solitary, unilateral, irregular, exhausting, nonmobile, and painless. This chapter addresses psychosocial burdens in epilepsy and focuses on topics which have had less coverage in different sections <a href=https://fecetc.org/wp-content/docs/order-lopinavir-no-rx/> medicine 5513 buy lopinavir 250mg lowest price</a>.
Courtesy of Sarah Caney Figure 8 Multiple sources of fresh water are essential for maintaining hydration. A3388 P1107 Systematic Review of Intravenous Acetaminophen After P202 Clinical Significance of Desaturation During a 6-Minute Walk Cardiac Surgery/M. After the completion of the six months examine period, the sufferers’ therapy card will be screened to hint comply with-up default or readmission <a href=https://fecetc.org/wp-content/docs/order-cheap-lioresal/> spasms on left side of body purchase lioresal uk</a>. No phone, fax or computer-generated prescriptions for Lotronex might be crammed. Overgaard, Risk Factors of Arm Lymphedema in Breast Cancer Patients, Acta Oncologica 39 (2000): 389 92. The concept of maintaining a higher physique temperature is controversial given Raymond Pearl's "rate of living" principle (discussed in chapter three), which, when you recall, displays


KamakAgebykece | 23-06-21 13:03
However, as discussed later, in ischemic tissues such because the myocardium, sure structural changes. Intestinal and age and sex distribution of various Pathology of cholangiocarcinoma. In actuality, the connection is made between the fantastic fiber matrix across the sarco lemma and the loose connective tissue in the instant neighborhood of the muscle fibers <a href=https://grupatrakcja.com/principles/class37/> erectile dysfunction injections side effects purchase discount viagra capsules on line</a>.
These criteria are designed to guide each providers and reviewers to essentially the most appropriate services based on a patient’s distinctive circumstances. Isolation of fungi or potential bacterial pathogens such Day 1 Day 14 as Staphylococcus aureus and Stenotrophomonas maltophilia in sputum samples of sufferers didn't improve after 14 days of Figure 1. Contraindications for surgery Mild deformities with adequate help for the hand (Type zero or 1) do not require surgical procedure <a href=https://grupatrakcja.com/principles/class31/> symptoms in early pregnancy discount ropinirole</a>. Arch Gen Psychiatry tion of a behavioral quantitative trait locus exhibits that Rgs2 2001; 58:1015 1024 modulates anxiousness in mice. Jesus said to him, If I need him to stay (survive, live) till I come, what's that to you. In some circumstances, the choice to make use of low-voltage X-ray from an orthovoltage or other low-voltage machine may be made as a result of such a unit is availa


BuffordPraniam | 07-06-21 09:42
Important mor Disease presentation can differ widely across the nephritic phologic information is gleaned from mild, electron, and spectrum from asymptomatic glomerular hematuria (espe immunofuorescent microscopy. Renal transplant is the therapy of alternative for renal alternative remedy in sufferers with renal failure (adults or children). Also, Davis and Greger (1992) could not demonstrate that women given 15 mg/day of manganese throughout a one hundred twenty five-day supplementation period excreted extra manganese in urine than girls consuming 1 <a href=http://musicfirstcoalition.org/wp-content/records/purchase-online-diarex/> chronic gastritis flatulence 30 caps diarex with visa</a>.
Before switching, remaining treatment options in case of potential Defnition of virologically suppressed virological failure of the brand new routine ought to be considered. Controlling the cardiovascular manifestations of thyroid storm is significant, massive doses of. For essentially the most part, transplant centers don’t send patients house till they meet the next criteria (Why Are Stem Cell Transplants Used as Cancer Treatment? <a href=http://musicfirstcoalition.org/wp-content/records/order-cheap-caduet/> cholesterol ratio canada buy caduet cheap online</a>. Prevention and control of raised blood strain is likely one of the cornerstones of those efforts. Their similarity is clear; a number of studies have proven that the same measurements used in normal evaluation can be used equal


Yorikodomi | 05-06-21 15:59
Electrocautery or laser therapy needed for large lesions not responding to topical agents; liquid nitrogen additionally used as cryotherapy. Glucose Prolonged organ hypoperfusion results in growing Serum glucose ranges are inclined to rise in pathologically hypoxia and elevated lactate manufacturing. We would also prefer to make clear that the dialysis new enrollee relative components are applied in cost only to enrollees who wouldn't have 12 months of Part B enrollment within the data collection period cholesterol ratio definition <a href=https://www.fastmap.com/wp-content/laboratory-practice/buy-online-atorlip-10/>10mg atorlip-10 for sale</a>. Admitted candidates who have a disability and need accommodations should initiate discussions with the Program Director as quickly as the provide of admission is obtained and accepted. The occurrence and implications of antibiotic residues in the surroundings is an rising concern.
If you have an interest, they're described in Chapter 8 3 Note: these are all substitutions this one is an insertion 4 Missense mutation: changes an amino acid to another amino acid. Inammation could be superimposed on areas of mechanical trauma or ulceration, leading to a varied colour from one examination to the next. Oral topical doxepin rinse: anesthetic tensity and interference with high quality of life in paeffect in regular topics managing diabetes in dogs <a href=https://www.fastmap.com/wp-content/laboratory-practice/buy-cheap-pioglitazone-online/>


Treslottviose | 03-06-21 16:58
We embrace the instances that got higher, since they had been cases at a while throughout interval B. Implications of a negative test result A variety of points may be mentioned depending on Explanation of the window interval the individual involved and his or her risks. However, some for mood stabilisers to be prescribed in addition to people get discontinuation results in the event that they cease their antidepressants myofascial pain treatment center watertown ma <a href=https://www.russhhospital.com/wp-content/practice/case367/>cheap elavil 75mg without prescription</a>. Williams (4) reported that distilled water launched into the intestine triggered abnormal modifications in epithelial cells of rats, probably because of osmotic shock. This requires information on mattress hospitals with specialist items corresponding to intensive care models utilisation.
When present, facial behavioral issues related to alcohol use or previous fractures are often associated with other extreme medical historical past. The child's ability to use fuoride dentifices increases throughout this period, although restraint in the amount of toothpaste used at each brushing should continue. The mia: analysis of 1065 patients entered into the dence of 11q23 chromosomal translocations women's health of central ma <a href=https://www.russhhospital.com/wp-content/practice/case363/>buy arimidex with visa</a>. I suggest that you simply learn the chapter on web page 178 to realize a background understan


Jarolltor | 24-05-21 00:33
The prevalence of bulimia nervosa is much less sure, but surveys point out that 10 to 50 % of young females interact in periodic self induced vomiting or binge eating. Patients had been randomised 1:1 to both Repatha (140 mg every two weeks or 420 mg once every month) or matching placebo; the imply period of patient observe-up was 26 months. Detection of sperm antibodies in sem en using the Im m unobead take a look at: a survey of 813 consecutive patients <a href=http://www.politicoscope.com/wp-content/journal/buy-cheap-nemasole-online/> antivirus windows 8 purchase 100mg nemasole with mastercard</a>.
Beta blockade can also be a priceless remedy system discharges occur due to recurrent repetitive that can stop many undesirable gadget interven arrhythmias. Of the forty one patients, 13 (32 %) had drainage that required surgical intervention and 14 (34 %) developed a deep an infection. Source of an infection The individual, animal, object or substance from which an infectious agent passes to a bunch <a href=http://www.politicoscope.com/wp-content/journal/order-online-serophene-no-rx/> breast cancer 3 day 2014 san diego 50mg serophene with mastercard</a>. There is the neurotransmitter serotonin or 5-hydroxytrypevidence that the immune system, in flip, in uences neu34 tamine (5-H T) probably also plays a task within the stress roendocrine function. Identification A group of zoonotic bacterial ailments with protean manifestations. Trends in national incidence, life- Placebo-cont


Copperneilm | 17-05-21 00:30
The frst and most important piece of recommendation is to hunt help from professionals who understand your state of affairs and who know the foundations about incapacity benefts in your province. In the early Nineteen Fifties, experimental psychology researchers began sensory deprivation or perceptual isolation studies. Relaxin from the corpus luteum also inhibits uterine contractions and relaxes the pelvic ligaments acne after shaving <a href=http://nicklemortuary.com/docs/pharmacology30/purchase-cheap-cleocin-gel-online/>order cleocin gel 20gm line</a>.
For this analysis, interviews 14 shall be performed with dad and mom who've children who have been or still are at school as they will have skilled their youngster being absent from college for long intervals of time and the difficulties related to their kids and education. Tsetse Flies (African Trypanosomiasis) An estimated 60 million people are in danger for African trypanosomiasis, with 300,000 to 500,000 new cases Medically Important Arthropods 681 Figure 24. The apocrine skin or hair and acts as a barrier glands develop throughout puberty in order that solely a certain amount of and produce sweat during times moisture can depart our bodies acne x-ray treatments <a href=http://nicklemortuary.com/docs/pharmacology30/buy-accutane-no-rx/>purchase 40 mg accutane free shipping</a>. The method to cardiovascular collapse attributable to bradyarrhythmias, asystole, or pulseless electrical activity is proven in. The quantity of


LaresLat | 26-04-21 18:01
However, at excessive concentrations, ketone bodies are poisonous, particularly to the mind. The sort and amount of anti-nausea medicine shall be based on your child’s treatment plan and response to the therapy. The solutions have been transferred to (amber) microvi- assessed at 24 h, 72 h, 7 days and 14 days blood pressure medication classes <a href=https://technowhy.com/clinical/discussion-group-6/buy-online-plendil-cheap-no-rx/>effective plendil 5 mg</a>.
For the comfort of constructing a desk, the geneticist organizes the info as if all 11 pairs of genes had the same designation—a and b—as proven below. Because of greater airway pliability in kids, airway obstruction from mediastinal lymphadenopathy is extra widespread in youngsters. In the genital examination of the toddler, who had a low fontanel and dry mouth, it was noticed that the testicles had been in the scrotum and the penis size was 4 allergy symptoms of wasp stings <a href=https://technowhy.com/clinical/discussion-group-6/purchase-seroflo-online-no-rx/>generic seroflo 250 mcg with visa</a>. It have to be remembered that its convulsions unfold from the centre in direction of the periphery. Because there have been no requests for return of youngsters and no court docket selections relating to the issue of parental abduction which have been reported, one may conclude that this concern isn't regarded as of great importance in Georgia. The worst (90:10) created from typical wheat had been firmer than accepti


Gunnarwem | 18-04-21 16:06
Equipment: a) Distillation apparatus for optimized Monier-Williams method (commercially available) b) Burette, 10 ml capacity, designed to maintain carbon dioxide free ambiance over the contents (sodium hydroxide) c) Chilled water circulator d) Heating mantle, 1 litre capacity e) Gas regulator for nitrogen provide, with oxygen absorbing lure Reagents: a) Hydrochloric acid, four mol/litre b) Hydrogen peroxide solution c) Sodium hydroxide resolution, zero. Calculate publish-mortem hours for incoming donors whereas including 24 hours for serology outcomes. The lesion appears as a yellow-white gingival Cho H-H, Kim S-H, Seo S-H et al: Oral furry leukoplakia which tumescence with an associated erythema ure three-70) <a href=https://www.ktunaxa.org/council/pharmacology/buy-online-provestra-no-rx/> erectile dysfunction johannesburg provestra 30pills without prescription</a>.
The research chosen in the vignette, a fiberoptic endoscopic evaluation of swallowing, uniquely allows the otolaryngologist and speech and language pathologist to instantly visualize the trail of oral secretions and/or feedings. They are separated by and or by one other connecting time period that doesn't suggest a due to relationship: and with accompanied by precipitated by additionally predisposing (to) related to superimposed on sophisticated by complicating according to Q. The patient scientific condidecisions based mostly solely on custom are not advisable <a href=https://www.ktunaxa.org/council/pharmacol


IomarTrounda | 18-04-21 01:59
Submucous myomas enhance the risk of recurrent early of workplace hysteroscopy are low, a liberal strategy to early being pregnant loss. Studies measure core sickness symptoms, functioning, quality of life, relapse, and remedy retention. Clinical Features There is no lively extension and it should be handled as tendon accidents somewhat than fractures <a href=https://www.arfa-idf.asso.fr/lectures/topic31/order-online-forxiga-no-rx/> diabetes prevention 8 week plan purchase genuine forxiga on-line</a>.
Your surgeon will talk about with you whether or not you'll need a everlasting or momentary ostomy to treat your explicit most cancers. She opens a sterile drape and locations it excessive and sides of the desk, and thoroughly peels again the wrapping of several syringes and drops them on the desk. As in previous editions of the Red Book, really helpful dosage schedules for antimicrobial brokers are offered (see Section four, Antimicrobial Agents and Related Therapy) and may differ from these of the producer as provided in the package insert <a href=https://www.arfa-idf.asso.fr/lectures/topic31/buy-tadora-online-in-usa/> erectile dysfunction best pills 20mg tadora with mastercard</a>. The sufferers could have Genitourinary and rectovaginal fstula full restoration from the injuries however a considerable number tender perineal and vaginal scar might produce everlasting legacies which result in main gynecologic issues. To detect administration issues and fnd appropriate solution

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