What is gd2 php

Introduction to GD

GD is a graphics library that is bundled with the PHP web scripting language, as of version 4.3.0. GD is an open source project, under the stewardship of Thomas Boutell, whose web site http://www.boutell.com/gd/ contains downloads and documentation on the latest version (2.0.27 as of writing).

GD allows PHP programmers to developer web applications that facilitate generating dynamic images, in the JPEG and PNG formats. These images may be based on user input, database queries or other variable information, which allows for a very powerful and flexible tool for serving up relevant information to end users in a graphical format, e.g. in bar or pie charts.

The GD library is written in C, and is available for Windows and Unix-derivative systems. Although commonly used with PHP, implementations are also available for other programming languages, for example GD.pm for Perl.

An overview of GDs functionality

The functions provided by GD vary greatly depending upon which major version of GD that you have installed on your system. Versions before 1.6 only supported the GIF format. Version 1.6 and later support JPEG, PNG and WBMP, but not GIF, due to a patent on that graphic format .Version 2.x added several new drawing shapes, and it is that version that I will be using in future tutorials on GD.

To give some understanding of GDs power, here are some of its major features:

  • The drawing of primitive shapes such as lines, arcs, ellipses, polygons et cetera with variable parameters provided by your PHP code.
  • Support for true color images with an alpha channel, that allows for transparency in images.
  • Support for merging of two images into one composite.
  • Full text support, with built-in fonts and support for antialised TrueType fonts via the FreeType library.
  • Support for antialised primitives.
  • Optional resampling of resized images.
Читайте также:  If checked true in php

Apart from the features mentioned above, there are likely to be many more additions to come from this very active project. While there are other tools available for generating images dynamically with PHP, GD is the most widely used and provides the best performance.

Making use of GD

In order to use GD 2, you need to have a web server with PHP installed, along with GD support enabled in your PHP setup. You may also need to have the GD library installed separately, although this is usually bundled with the PHP download for most operating systems (although not the Windows installer!).

As for possible uses for GD, here are a few suggestions:

  • Charts, such as pie charts of survey results, as stored in a database.
  • GIS (Geographical Information System), that is drawing maps based on coordinates stored in a spatial database such as MySQL or Oracle.
  • Organizational Structures, for example building a corporate organization chart based on an employee database.
  • Node Trees, such as Binary Trees or any other collection of data that contains parent/child relationships that need to be represented graphically.

As you can see, GD can have many uses. While static images are fine for most purposes and are widely used throughout the Internet, dynamic images provide an extra layer of functionality to a PHP system that allow it to make that jump from being a web site towards being a web application.

In my next piece on GD, I will show you how to draw basic shapes in GD, before moving onto working with text, and then finally some real-life examples of the libraries functions. Until then, I would suggest some further research on installing GD at http://www.boutell.com/gd/ and PHP.net, which is beyond the scope of this introductory article.

Updated 2020 : note that the above post is out-of-date, given this post was originally published in 2004, but is left here for archival purposes. Unfortunately some of the URLs above are now dead, so I have de-linked them.

Источник

Основы работы с библиотекой GD

От автора: очень часто при разработке скриптов необходимо работать с изображениями, используя язык PHP. К примеру, генерация изображений с нуля или редактирование уже существующих и т.д. Поэтому в данном уроке мы с Вами изучим основы работы с библиотекой GD, которая предназначена для обработки изображений средствами языка PHP.

скачать исходникискачать урок

Введение

Язык PHP достаточно разнообразен и его использование не ограничивается только созданием скриптов, выполняющим различные манипуляции с данными. Он также позволяет работать с различными графическими элементами, в частности с изображениями, разных форматов. Для этих целей написана, специальная библиотека, под названием GD, которая расширяет его стандартный функционал. Данная библиотека, чем-то похожа на небольшой графический редактор, используя который, Вы сможете легко обрабатывать изображения, используя только язык PHP. Библиотека GD, позволяет создавать новые изображения, редактировать уже существующие, копировать одни изображения на другие, изменять размеры, а также наносить текст на изображения.

Поэтому, так как, библиотека является расширением, значит необходимо убедиться, что она подключена в Вашем интерпретаторе языка PHP. Для этого необходимо открыть главный конфигурационный файл PHP – php.ini. Если Вы используете Denver, значит Вам необходимо, перейти в виртуальный диск, созданный им (в моем случае это диск Z). И затем по адресу: Z:\usr\local\ php5. В корне папки php5 Вы найдете необходимый файл. Далее открываем данный файл в текстовом редакторе, находим строчку: extension=php_gd2.dll

Онлайн курс «PHP-разработчик»

Изучите курс и создайте полноценный проект — облачное хранилище файлов

С нуля освоите язык программирования PHP, структурируете имеющиеся знания, а эксперты помогут разобраться с трудными для понимания темами, попрактикуетесь на реальных задачах. Напишете первый проект для портфолио.

Если напротив данной строки, нет символа “;” (точка с запятой), значит расширение подключено, если же символ есть – его необходимо удалить и перезапустить Denver. В этом случае Вы подключите библиотеку. Теперь можно приступать к работе с данной библиотекой.

Основы создания и редактирования изображений

Для того чтобы вывести на экране изображение, необходимо использовать тег img и в атрибуте src, данного тега, нужно указать путь к изображению. Но в нашем случае изображение создается при помощи языка PHP. Поэтому в атрибуте src мы укажем путь к файлу php, который создаст нужное нам изображение. Значит, создаем файл index.php, который будет выводить на экран изображение, со следующим содержимым:

Источник

Оцените статью