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

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

Афоризм
С чувством хорошо выполненного обеда
 
Поиск


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

Ramonordewly | 24-02-23 16:51
The two nearest analogies in terms of alternative courtroom techniques are the juvenile justice system and the so-called пїЅproblem-fixing courts,пїЅ corresponding to psychological health courts. The cost of all such repairs (besides repairs of structural defects) shall be included in Operating Expenses, besides as otherwise supplied herein. Grade 2 and 3 anemia was noticed in 7 and 6 therapy programs, respectively, though 7 of these patients had grade 2 anemia at examine entry erectile dysfunction girlfriend <a href=https://www.oett.org/buy-online/Avanafil/>avanafil 200 mg purchase on line</a>.
The examina in these sufferers to maintain serum potassium tion, nevertheless, would not be consistent with a ranges. Myth: Only older people get diabetes Fact: Diabetes is aware of no boundaries and afects all of the individuals throughout the board. Cough Suggested by: sudden loss of consciousness after severe bout syncope of coughing gastritis and diarrhea <a href=https://www.oett.org/buy-online/Renagel/>buy 400 mg renagel amex</a>. The Guidelines recognise that in establishing acceptable efficiency ranges, collaboration between proficiency testing providers and skilled bodies is important. Nightmare dysfunction (Dream Anxiety): this situation consists of repeated awakenings with detailed recall of extended and really frightening dreams. Graphically, vectors r may be added by placing the tail of 1 vector at the head of the other vector infection 2 migrant <a href=https://www.oett


Dawsonmop | 17-01-23 08:43
We opened six new funds in President 2015 to assist patients in a wide range of disease areas together with Pulmonary Fibrosis, Urea Cycle Disorders, Renal Cell Carcinoma, Cystic Fibrosis, Multiple Myeloma, and Hepatitis C. Composition and metabolism of the extracellular matrix within the periodontal liga lies impeded and unimpeded of rat incisors. More than one focus Anemia, leukopenia 2 in four mm is considered consistent with the salivary compo nent of SjogrenпїЅs syndrome spasms brain <a href=https://kampottourism.gov.kh/order-online/Skelaxin/>skelaxin 400 mg purchase free shipping</a>.
The chronic shortage of deceased donor organs has led to a extra general acceptance of dwelling-donor transplants. Endogenous Retrovirus-Like Genetic Elements: 5-10% of the mammalian genome consists of retrovirus-like 'retrotransposons'. This will allow laboratory personnel to take proper precautions when handling specimens and also will permit the optimum use of various diagnostic modalities treatment interventions <a href=https://kampottourism.gov.kh/order-online/Diamox/>250mg diamox cheap free shipping</a>. Simple syrup may be used as the idea for ?avored or medicated syrups coloring brokers, the therapeutic agent, and other and the right choice must be made to ensure necessary and fascinating elements. Histologically, there may be necrosis with smudging of the venous, and fewer generally, arterial blood circulate from tissue. Cattle are immunized in opposition to Salmonella neverthel


Tuwasuntoppy | 10-01-23 05:20
During the first seven days of NuvaRing use within the first cycle, an additional barrier technique, such as male condoms or spermicide, is really helpful. Such lesions are typically irregular, might involve one side greater than the other, and occur in any tooth. Codes for Record I (a) Septicemia A419 (b) Erythremia D751 (c) Polycythemia D45 Code to D45 antiviral quinazolinone <a href=https://concejoyumbo.gov.co/buy/Aciclovir/>order aciclovir 400 mg with visa</a>.
Covered steel versus plastic stents for postoperative surveillance after curative remedy of pancreatic most cancers: a malignant common bile duct stenosis: a prospective, randomized, price-effectiveness analysis. Saturated Fats Added Sugars Sodium & Trans Fats Choose a wide range of nutrient-dense foods from every meals group in beneficial quantities. This significant discrepancy between morphologic and functional findings is a crucial attribute in differential prognosis women's health group boca raton <a href=https://concejoyumbo.gov.co/buy/Aygestin/>order aygestin 5 mg free shipping</a>. Accessed 29 Aug 2018 (2016) Pen units for insulin self-administration in contrast with 24. National rare disease events in 2013 Rare Disease Day was marked on 28 February 2013 with occasions organised by the National Alliance of People fifty six with Rare Diseases. Lawrence River valleys) immunodiffusion antibody check Legionella pneumophila Exposure to contaminated water provide Culture or direct fuorescent assay of respirator


JaredPrictaree | 04-01-23 21:34
Subsequent dilutions could be ready from the that entails administering a number of injections at increasing doses upkeep focus for the construct-up section or if the affected person (generally 2-three per visit) sequentially in a single day of therapy can not tolerate the upkeep concentrate. A minor variation within the structure of a virus (known as an antigenic drift) will result in an epidemic which is an outbreak of flu which will affect a big area in a number of international locations. Mediterranean diets and Western diets, entire meals and particular person nutrients, havebeen found to have an affect on asthma danger, at varied levels of the life cycle (Table 1) gastritis symptoms while pregnant <a href=https://cemalta.gov.mt/order/Reglan/>10 mg reglan buy with amex</a>.
Patients with a malignant pleural effusion are handled Alternatively, the prognosis can be established by tradition symptomatically for essentially the most half as a result of the presence of the pleural ?uid, needle biopsy of the pleura, or thora of the effusion indicates disseminated illness and most coscopy. As this lesion covers the eye and may obstruct the sunshine pathway, waiting for spontaneous decision might lead to everlasting vision loss in that eye. It has also been noticed in some sufferers with frontotemporal dementia; thefinding is cross-cultural, having been described in Christians, Muslims, and Sikhs acne 4 hour <a href=https://cemalta.gov.mt/order/Accutane/>5 mg accutane for sale<


AldobAitacy | 29-12-22 09:18
Children find out about nutritious foods, complying with no tobacco use management, fostered by adults who are involved with tact with children within the facility, together with eatingtact with youngsters within the facility, including consuming health and safety by experiencing threat taking and riskhealth and security by experiencing threat taking and danger insurance policies, and handwashing protocols. When an aldosterone-producing adenoma or unilateral adrenal hyperplasia is identified, the suitable remedy stays surgical resection. Treatment during this period presents chal- lenges due to the lack of knowledge from scientific trials infection trichomoniasis <a href=http://zpfeni.gov.bd/buy-online/Minocycline/>cheap minocycline 50 mg visa</a>.
She found that Selina had additionally returned, and was happily reunited with her good friend. There is far extra satisfaction and the case is much more complete if we will get a picture of the whole condition and of the one remedy to meet that condition. In infants most an infection is transmitted from mother to youngster, while in adolescents and adults, sexual transmission is the same old route bacteria zone <a href=http://zpfeni.gov.bd/buy-online/Azithromycin/>buy generic azithromycin 250 mg on line</a>. This could be as a result of a hundred and ten Acute Pancreatitis association of the raised gut permeability with alcohol consumption and the concomitant endotoxemia. Ultrasounds Routine ultrasounds in the third trimester us


BallockEnuch | 29-11-22 06:46
They also agreed, based mostly on their scientific experience, that it would be useful for healthcare professionals to tell folks with glioma that no evidence had been discovered to counsel that certain treatments are benefcial. Though oral bioavailability is low, the phenytoin and probenecid: displace warfarin anticoagulant effect is constant, and no laboratory monitoring from plasma protein binding. Acute inhalation of phosgene leads to a sequence of occasions, together with an preliminary bioprotective phase, a symptom-free latent interval, and a terminal part characterised by pulmonary edema (Schneider and Diller, 1989; Diller, 1985) pulse pressure 37 <a href=https://www.museyokutawato.gov.ph/order/Aldactone/>cheap aldactone 25 mg otc</a>.
Protocols for case management vary across settings and degree and inhabitants(s) served. Vasopressin is diluted with saline as 10 items of vasopressin for each a hundred ml of saline. Which one of the listed organisms is more than likely to have produced her signs and symptoms erectile dysfunction treatment natural food <a href=https://www.museyokutawato.gov.ph/order/Vardenafil/>vardenafil 10 mg cheap with amex</a>. Exposures to rodent excreta, especially aerosolized infectious urine, recent necropsy materials, and animal bedding are presumed to be associated with danger. As a resuscitation software, suction comes second solely to a self-inflating bag and masks. The genital in origin and come up from sinusoidal 4 connective tissue ele


Kapotthmah | 01-11-22 17:46
Code for Record I (a) Metastatic mesothelioma of mesentery C451 Code to mesothelioma of mesentery (C451). Staining high quality may be standardized through the produced in a reproducible fashion. I can also hearken to some stress-free music or go fishing, and distract myself or take pleasure in myself a bit symptoms wheat allergy <a href=http://www.dnahelix.com/04/rulide/>order rulide 150mg amex</a>.
Tonsillitis exacerbating existing illness such as febrile convulsions, guttate psoriasis, glomerulonephritis or rheumatic fever. Although the results of some studies counsel an extra mortality observed with standard antipsychotics compared with atypical antipsychotics, the report concluded that this might not be confirmed due to the methodological limitations of the studies. O970-O979 Sequela of obstetric cause Use this category for the classification of a direct obstetric trigger (situations in O00-O927) if: (a) A statement of a late effect or sequela of the direct obstetric cause is reported hypertension yahoo <a href=http://www.dnahelix.com/04/isoptin/>240 mg isoptin with mastercard</a>. Surgical ablation of solitary liver metastasis with a hepatic flexure main is coded to 2 (Site regional by stage). In this examine, multigraph K-method clustering1 was employed to reveal temporal evaluation of mind funcitonal atlases in 71 healthy youngsters longitudinally scanned at 1/3/6/9/12/18/24 months of age. The want arises be vations by totally different workers and the trade of trig


PotrosWat | 27-10-22 04:18
The hips, back, thighs, buttocks, penis, and the ocular stigmata of Fabry disease hardly ever if ever cause sig- scrotum are commonly affected, in addition to the oral mucosa and sixty seven nificant impairment of vision and, as a rule, do not require conjunctiva. However, there's a need to teach black bear hunters on how to establish and distinguish a black bear from a grizzly bear. During pedal joint capsule, the navicular bursa and the deep motion the digital cushion acts as a pump to facili- exor tendon sheath treatment lupus <a href=http://www.atpobtvs.com/order/chloroquine/>generic chloroquine 250 mg line</a>.
Monitoring of physical exercise could also be more relevant relating to prognosis than evaluating exercise 98 capability. Children residing in Nevadas two largest counties are mandatorily enrolled in one of two managed care plans, unless they meet certain exemption criteria. A systematic evaluate to calculate background miscar- riage charges utilizing life table evaluation treatment 7th feb cardiff <a href=http://www.atpobtvs.com/order/avodart/>discount avodart 0.5 mg with amex</a>. Thereafter Riddle et al (1933) reported that the crude extract might stimulate the production of “milk” by the crop sac of pigeons. L) might have additional nitrates and their use is contraindicated in patients who are profit and is an inexpensive goal for most patients with concurrently utilizing natural nitrates in any form. Non-viral causes of infectious encephalitis Viral cau


Sivertamuct | 25-10-22 21:23
Nevertheless, in some instances, extreme and continual compression of the fetal lungs can lead to pulmonary hypoplasia and neonatal demise. Since 2009, Stea is in charge of publish-advertising surveillance of orthopedic medical units. Evaluation of factors affecting start weight and preterm start in southern Turkey anxiety before period <a href=http://www.chelseastationeditions.com/meds/desyrel/>purchase desyrel 100mg without prescription</a>.
Both anthracyclines are ionic compounds they usually and their active metabolites are extremely protein bound, which might recommend less deposit into fats than into lean mass. Smokeless Tobacco Use within the Region of the Americas Smokeless Tobacco Products Tables, Figures, and Maps Table 9-1 Population and land area of countries within the Americas Region. Although present at birth, coarctation of the aorta might not cause signs until early childhood and typically not until late childhood, depending on the severity of the coarctation, and the presence of related cardiac lesions hair loss 50 year old woman <a href=http://www.chelseastationeditions.com/meds/dutas/>order dutas 0.5 mg mastercard</a>. Continuous entry to competing stimulation as intervention for self-injurious skin selecting in a baby with autism. Elective cholecystectomy during laparoscopic Roux-en-Y gastric bypass: is it well worth the wait. Certain threat factors, corresponding to DownпїЅs syndrome, have been iden- tified for childhood leukaemia, however general- ly


cindyfw4 | 06-10-22 18:20
Teen Girls Pussy Pics. Hot galleries
http://amandahot.com/?aria

kinky porn girls anna nicole smith porn dnny phantom porn mary carey porn movies free asinan porn

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