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

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

Афоризм
Народу собралось - яблоку плюнуть негде!
 
Поиск


 
Рассылка
| Soft-Ежедневник - обзор программ прямо к Вам на e-mail
 
 
Полезное!
 
7 лучших
  Топливный катализатор "Тонус"
  69 секретов
  История Армении
  Игорный Дом
  Mega Portal
  
  
 
  Библиотека > 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 | >

DargothFOgnimI | 22-09-22 00:01
Physical examination could also be troublesome to find the location of the injury except for a refusal to bear weight on the affected decrease extremity. The dataset noted that the affected person withdrew from double blind therapy previous to this occasion (reason-consent withdrawn). Botulinum toxin therapy of sialorrhoea: evaluating different therapeutic preparations impotence 36 <a href=http://www.mentor.edu.pl/publications/purchase-dapoxetine-no-rx/>buy dapoxetine 30mg cheap</a>.
Thirteen (24%) of the ritodrine group developed opposed drug reactions severe enough to require discontinuance of the drug and a change to magnesium sulfate: cardiac arrhythmia (N = 1), chest pain (N = 2), tachycardia (N = 3), and hypotension (N = 7). This venovenous hemofltration and hemodialysis are of unsure acidifcation favors the formation of ammonium ion within the value in hepatorenal syndrome. She was maintained on terbutaline, aside from a “24-hour relaxation period” every week, for fifty one days erectile dysfunction nclex questions <a href=http://www.mentor.edu.pl/publications/purchase-forzest-online-no-rx/>20 mg forzest with mastercard</a>. These forms of divisions are usually outlined as asym- metric divisions, either in the bodily sense that they produce two cells of different size or in the developmental sense that they produce two cells of different id. It is suitable for day case surgical procedure as a result of post-operative ache is less, though there is more risk of dou


SamuelroF | 19-09-22 07:18
The liver is also a twin-function gland whose exocrine product is bile, synthesized by hepatocytes, and transported by a duct system to the gallblad der for storage and concentration. Because of the frequent use of intravenous routes thine derivatives (caffeine, theophylline). The the rest of the examination, including pelvic examination, exhibits no abnormalities myofascial pain treatment vancouver <a href=http://www.mentor.edu.pl/publications/purchase-cheap-rizact/>cheap 5mg rizact otc</a>.
Though a drink earlier than mattress may help sleep what is skilled isn’t a restorative sleep. American Journal of Medicine hypoxic and when given oxygen may develop 1987;eighty two:fifty nine-sixty four. Indicated prevention applications work toward the objective of secondary prevention— stopping emerging problems from creating into extra severe problems gastritis diet однокласники <a href=http://www.mentor.edu.pl/publications/purchase-zantac-online-no-rx/>cheap 150 mg zantac otc</a>. Nevertheless, the value of norclozapine ranges in guiding medical choices is unclear. The basic construction of the lipoprotein is beneath: Lipoproteins are totally different based mostly on the ratio of protein:lipids, as well as the actual apoproteins and lipids that they contain. Department of State filed a quick in this case with the 2nd Circuit Court in New York, on Jan bacteria and archaea are similar in which of the following <a href=http://www.mentor.edu.pl/publications/buy-keftab/>purchase g


LeonPaf | 14-09-22 20:36
In contrast, in diffuse scleroderma, the individuals who're exposed to chilly winters or excessive air pores and skin adjustments also contain the trunk and proximal extremi conditioning. To determine if someone has an belly aortic aneurysm, we use advanced technology to effectively diagnose, inform remedy and thoroughly monitor the situation. Between the fourth and fifth rotation blocks (December), residents may have a combination of analysis days and mini-rotations antibiotics diabetes <a href=https://cucuta.gov.co/meddata/purchase-online-clearsing-cheap/>discount 100mg clearsing overnight delivery</a>.
Operative conversion to toSodium channel blockers suppress roughly half of atrial artal cavopulmonary artery reference to concomitant arrhythmia 969 surgery can, in some patients, enhance heart failure symptoms and rerhythmias in Fontan sufferers. Weak muscle tone (hypotonia), recurrent ear infections, an unusually small head (microcephaly), and yellowing of the skin and whites of the eyes (jaundice) also can occur. This diet is characterized by greens, fruits, whole grains, legumes and nuts, reasonable amounts of low-fat proteins similar to chicken and fsh and fats centered around olive oil symptoms before period <a href=https://cucuta.gov.co/meddata/purchase-cheap-prometrium-online/>discount prometrium 100 mg free shipping</a>. Providing prime quality anaesthesia and critical care The speciality of paediatric anaesthesia has developed requires a skilled workforce, but it


Hengleyoscibia | 07-09-22 11:25
Systematic evaluate of the prevalence, incidence and nature of prescribing errors in hospital inpatients. Neurological progression over time signifies an intriguing hyperlink between neurodevelopment and neurodegeneration, additionally supported by neurodegenerative options in epg5-poor Drosophila, and up to date implication of other autophagy regulators in late-onset neurodegenerative illness. Be conscious of ultimate consequence of acquired hypothyroidism, together with impact of the disorder on the affected person's progress and mental development 4 allergy treatment relief <a href=http://www.mhcurling.com/program/purchase-cheap-flonase-online-no-rx/index.html>buy generic flonase 50mcg on-line</a>.
The effcacy of abaloparatide for the therapy of postmenopausal osteoporosis was evaluated in an 18-month, randomized, multicenter, double-blind, placebo-controlled scientific trial in postmenopausal women; it demonstrated an absolute danger discount in new vertebral fractures of 3. Surgical procedures for adults and adolescents Chapter 5-20 Male circumcision beneath local anaesthesia Version three. In learning mothers and their youngsters they have famous that a mother's apparent expertise of her personal mom as rejecting is systematically related to her rejection of her personal toddler as noticed within the laboratory and on the identical time to systematic distortions in her personal cognitive processes medications causing gout <a href=http://www.mhcurling.com/program/buy-o


Tylertriesee | 05-09-22 12:22
Spinal fluid 8 American Cancer Society most cancers. Criteria for ambulatory remedy of severe acute malnutrition, all the following should apply: пїЅ Children over the age of 6 months with no pitting oedema. When present, a central scar with calcifications could recommend fibrolamellar hepatocellular carcinoma womens health haven <a href=https://dm.edu.pe/wp-content/uploads/medicine/purchase-online-fosamax/index.html>buy cheap fosamax</a>.
At least 2 of the following pain characteristics: features, such because the frequency and temporal sample Unilateral location Pulsating quality of assaults, drug intake, and the presence of set off facModerate or extreme intensity tors. Advice In basic, when bronchial asthma is well-managed, there is no want for sufferers to change their lifestyle to keep away from unfavorable outdoor conditions (air pollutants, climate). As indicated above, extra research is required on the renal results of vanadium intake, notably in these sensitive subgroups arthritis in the knee what to do <a href=https://dm.edu.pe/wp-content/uploads/medicine/order-cheap-naproxen-online-no-rx/index.html>250 mg naproxen overnight delivery</a>. In this section, humoral biomarkers are enumerated no matter their source and their mode of motion, para- or autocrine. The signs and signs are these Polycythaemia vera and myelofibrosis described for thrombocytopenia. Mitochondria structural integrity Campus, Lucknow, India within neurons have been markedly compromised antibio


DarylFudgila | 03-09-22 19:20
A questionnaire was accomplished by every participant to obtain descriptive knowledge on diet and health points, attitudes and beliefs about nutrition, and nutrition information. It is crucial to must be dropped at the immediate attention of the physician is correlate the bodily, chemical, and microscopic findings of proven in Table 18-5. Sodium bicarbonate alleviates penile pain induced by intracavernous injections for erectile dysfunction antibiotic resistance pdf <a href=https://dm.edu.pe/wp-content/uploads/medicine/purchase-orobiotic/index.html>order orobiotic 250 mg</a>.
Knowing that sometimes donors cannot be matched might affect the motherпїЅs relationship to the kid. Outreach and engagement strategies may include telephone contacts, face-to-face avenue outreach, neighborhood engagement,sixty four or assertive outreach after a referral is made by a clinician or caseworker. Characteristic lomics, although not but fully mature, studies until repeated samples are metabolic options might be identi- have considerably improved over the available acne that itches <a href=https://dm.edu.pe/wp-content/uploads/medicine/purchase-online-isoacne-cheap/index.html>40mg isoacne mastercard</a>. Use Characterization Alachlor is a herbicide registered for use on the following crops: succulent and dry beans; field, pop, and candy corn; peanuts; grain sorghum; and soybeans. Nearly all of these positions require an associate degree, and these technicians earn a median income of $49,410 as


GrimNew | 01-09-22 10:56
B, the position of the mandibular incisor is equally evaluated, although the nasion-B level line is used as a reference line. Fourth, challenges are in validating the predictivity of the out there assessment tools enchancment of nerve agent elimination by small molecule scavengers would possibly which would require identifcation of applicable endpoints and thresholds of further contribute a benefcial efect. At this stage, about 90% of functional renal as urochrome in the skin causes sallow-yellow color cholesterol medication drugs <a href=https://dm.edu.pe/wp-content/uploads/medicine/buy-cheap-zocor-online/index.html>zocor 40 mg cheap</a>.
Potential analyses cowl a variety of targets: from a macro-degree examine of by-nation varia- tion in methylphenidate consumption, to a micro-stage research of the beliefs and prac- tices of particular person academics and psychiatrists in local settings. Once the quality of proof has been assessed for all reported outcomes, the overall evidence quality was evaluated based on the lowest high quality ranking given to any of the outcomes that have been designated a priori to be Critical by the working group. Correlation of Primary Tumour Site with Survival Known prognostic components embody: Distant Metastases • Location of main tumour 1 erectile dysfunction neurological causes <a href=https://dm.edu.pe/wp-content/uploads/medicine/purchase-cheap-sildenafil-online-no-rx/index.html>discount sildenafil 50 mg with visa</a>. For further inform


Anktosinwanty | 18-08-22 02:17
It was unreliable because of non-standardized antigens and did not appear to have scientific relevance. Although there is a or on the esophagus, causing problem in swallow proliferation of blastic cells in chronic forms of ing (dysphagia). However, informed-consent documents should not be thought-about all-inclusive in defning other methods of care and risks encountered erectile dysfunction young causes <a href=http://www.lrdg.org/publications/purchase-online-kamagra-super-no-rx/index.html>purchase 160 mg kamagra super fast delivery</a>.
It is also top in search lifting the upper eyelid when the eyes spot up, and for pupillary constriction. As a consequence of their atopic standing, individuals drug and/or immunological therapies, and their data could develop allergic ailments, including rhino-conjunctivitis, of allergen specifc immunotherapy practices. If the thrombin time is extended but corrects to inside two seconds of control end result, the presence of heparin is confrmed schedule 8 medications list <a href=http://www.lrdg.org/publications/buy-cheap-quetiapine-online-no-rx/index.html>discount 100mg quetiapine free shipping</a>. Advice sufferers not to drive automobiles or operate machineries or do activities requiring alertness. Khianman B, Pattanittum P, Thinkhamrop J et al (2012) Relaxation remedy for preventing and treating preterm labour. Congenially, I suggest, Oh, and now you come into my room, plop down in my chair, and rail in regards to the stupid doctors, am


AbeNot | 29-07-22 20:11
Primary lung abscess that develops in an otherwise normal iv) Direct extension from a suppurative focus in the lung. Most kidney ailments are asymptomatic, however in some tubulointerstitial illnesses signs are associated with the kidneys or lower urinary tract. Extraction forceps have two handles and two beaks, that are opposed when the handles are squeezed together antibiotics with pseudomonas coverage <a href=http://www.chajax.org/edu/order-cheap-fucidin/>order cheap fucidin on-line</a>.
Usual dose: 60mg subcutaneously administered by a healthcare professional as soon as each 6 months. Instead, they directly next to the V area is known as the fixed stimulate specific B lymphocytes by cross (C) area made up of 1 area within the linking antigen receptors on the surface of light chain (C1) and three or four in a heavy B cells. The sequence terminating in the condition first entered on the certificate is oesophageal varices due to cirrhosis of liver hiv infection inflammation immunosenescence and aging <a href=http://www.chajax.org/edu/purchase-vermox-online-in-usa/>buy vermox 100 mg amex</a>. Human tyrosine kinase 2 deficiency reveals its requisite roles in multiple cytokine indicators concerned in innate and bought immunity, , , vol. At any time, you possibly can evaluation the major substances points of every disorder by consulting the Cheat sheet on page 450. Encourage taking prescribed drug(s) routinely, for instance Establishes routine for taking drug and reduces pote


Philsmeap | 25-07-22 17:22
In 2018 these newly reportable conditions are included in the up to date Hematopoietic Database and Manual. So now we will introduce the formulation for the partial Gibbs free vitality of the solvent on dissolving a polymer: Equ. To help these new demographics, Governor Cuomo has considerably increased assist for upstate and suburban public transportation services by $169 million (42 percent) since 2010 virus with sore throat <a href=http://www.caxtonhouse.org/service/purchase-cheap-zitrolab/>order zitrolab 500mg with mastercard</a>.
Nicotine and carboxyhemoglobin fetal concentrations are about 10%–15% greater than these within the mom. Urinary retention (especially in Type E botulism): due nerves, and neuromuscular junction. Porto-systemic venous Hepatocellular (liver cell) Hepatocellular (liver cell) shunting might lead to a complex metabolic and organic adenoma carcinoma Hepatoblastoma (Embryoma) syndrome of the brain characterised by disturbed consci ousness, neurologic signs and flapping tremors treatment vitamin d deficiency <a href=http://www.caxtonhouse.org/service/buy-online-citalopram-cheap/>cheap citalopram online visa</a>. In an emergency, drainage by using a big bore intravenous cannula may be undertaken without sedation. Although some studies have explicitly focused on only one disease, several indicate an increased incidence of several different diseases within the same study population. Other deleterious effects: Diabetes mellitus Numerous studies have est

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