Modern PHP Graphics with Cairo. Michael Maclean FrOSCon 2011

Similar documents
Fireworks CS4 Tutorial Part 1: Intro

To be productive in today s graphic s industry, a designer, artist, or. photographer needs to have some basic knowledge of various file

Microsoft PowerPoint 2010 Templates and Slide Masters (Level 3)

OJS Design Brief. Part 1: Formatting the Web site s look and feel (CSS layout) 1) Preference of colors

Graphic Design Basics Tutorial

Lession: 2 Animation Tool: Synfig Card or Page based Icon and Event based Time based Pencil: Synfig Studio: Getting Started: Toolbox Canvas Panels

Adobe Training Services Exam Guide. ACE: Illustrator CS6

Logo Design Studio Pro Guide

KOMPOZER Web Design Software

ClarisWorks 5.0. Graphics

Links. Blog. Great Images for Papers and Presentations 5/24/2011. Overview. Find help for entire process Quick link Theses and Dissertations

NDSU Technology Learning & Media Center

Graphic Design Studio Guide

Fundamentals of Web Design (One Semester)

Adobe Illustrator CS5

Getting Started with WebSite Tonight

Lab 2: Visualization with d3.js

User Guide. idraw for Mac OS X v2.5.1

GelAnalyzer 2010 User s manual. Contents

04 Links & Images. 1 The Anchor Tag. 1.1 Hyperlinks

Generate Android App

Visual Communication Program Assessment Revised Graphic Design Portfolio Checklist/Assessment

Algolab Photo Vector

Adobe Illustrator CS5 Part 1: Introduction to Illustrator

ArcGIS ArcMap: Printing, Exporting, and ArcPress

Adobe InDesign Creative Cloud

GRAPHIC DESIGN BITES FOR MARKETERS

ACE: Illustrator CC Exam Guide

SMART Notebook 10 User s Guide. Linux Operating Systems

Table of Contents. I. Banner Design Studio Overview II. Banner Creation Methods III. User Interface... 8

WAYNESBORO AREA SCHOOL DISTRICT CURRICULUM INTRODUCTION TO GRAPHICS

PASTPERFECT-ONLINE DESIGN GUIDE

Overview of the Adobe Flash Professional CS6 workspace

KB COPY CENTRE. RM 2300 JCMB The King s Buildings West Mains Road Edinburgh EH9 3JZ. Telephone:

Web Design for Programmers. Brian Hogan NAPCS Slides and content 2008 Brian P. Hogan Do not reproduce in any form without permission

Smartphones and tablets: If you have a data plan, use the SMTP server setting for the company that provides this service.

Creating Web Pages with Microsoft FrontPage

JISIS and Web Technologies

Lynda.com > InDesign CS5 Tutorials Interactive Documents & Presentations

Advertising Specifications, Standards and Guidelines

WIN32TRACE USER S GUIDE

Welcome to the Notability! User Guide! Find what you re looking for! quickly using the search icon.!

Sweet Home 3D user's guide

ACADEMIC TECHNOLOGY SUPPORT

The Nile Programming Language: Declarative Stream Processing for Media Applications. Dan Amelang Viewpoints Research Institute UCSD PhD Student

Section 1 Spreadsheet Design

ADOBE MUSE. Building your first website

IT Fundamentals of Multimedia (Optional)

MyGraphicsLab ADOBE ILLUSTRATOR CC COURSE FOR GRAPHIC DESIGN & ILLUSTRATION Curriculum Mapping to ACA Objectives

Welcome to the Notability User Guide Find what you re looking for quickly using the search icon.

Client Admin Site Adding/Editing Content Under Site Builder/Site Navigation Tutorial by Commerce Promote

FILE PREPARATION GUIDE

File types There are certain image file types that can be used in a web page. They are:

Omnitapps Cloud Request Version 1.0 Manual

Divide your material into sections, for example: Abstract, Introduction, Methods, Results, Conclusions

ExpertCAD Release Summary March 2010

Inspiring Creative Fun Ysbrydoledig Creadigol Hwyl. Web Design in Nvu Workshop Session Plan

Create Accessible PowerPoint Presentations Presented by: Cryssel Vera

Graphic Communication Desktop Publishing

EUROPEAN COMPUTER DRIVING LICENCE / INTERNATIONAL COMPUTER DRIVING LICENCE WEB EDITING

Creating Hyperlinks & Buttons InDesign CS6

Florence School District #1

South Plainfield Public Schools Web Design Scope and Sequence of Curriculum Grade Date August 2011

Creating a Poster Presentation using PowerPoint

REVISED JUNE PLEASE DISCARD ANY PREVIOUS VERSIONS OF THIS GUIDE. Graphic Style Guide

Florence School District #1

Terminal Four (T4) Site Manager

QUICK REFERENCE: ADOBE ILLUSTRATOR CS2 AND CS3 SECTION 1: CS3 TOOL BOX: PAGE 2 SECTION 2: CS2 TOOL BOX: PAGE 11

Printing Guide. MapInfo Pro Version Contents:

Instructions for Creating a Poster for Arts and Humanities Research Day Using PowerPoint

WP Popup Magic User Guide

MMGD0203 Multimedia Design MMGD0203 MULTIMEDIA DESIGN. Chapter 3 Graphics and Animations

Fast track to HTML & CSS 101 (Web Design)

Digital Pen & USB Flash Drive. User Guide. December

MapInfo Professional Version Printing Guide

Graphic Design. Background: The part of an artwork that appears to be farthest from the viewer, or in the distance of the scene.


PowerPoint Interface Menu Bars Work Area Slide and Outline View TASK PANE Drawing Tools

Pivot Animator. User guide

Working With Animation: Introduction to Flash

CHAPTER 6: GRAPHICS, DIGITAL MEDIA, AND MULTIMEDIA

Notepad++ The COMPSCI 101 Text Editor for Windows. What is a text editor? Install Python 3

Graphic Design Basics. Shannon B. Neely. Pacific Northwest National Laboratory Graphics and Multimedia Design Group

Making TIFF and EPS files from Drawing, Word Processing, PowerPoint and Graphing Programs

THE SAS OUTPUT DELIVERY SYSTEM: BOLDLY TAKE YOUR WEB PAGES WHERE THEY HAVE NEVER GONE BEFORE! CHEVELL PARKER, SAS INSTITUTE INC.

PaperlessPrinter. Version 3.0. User s Manual

(La)TeX Support for manuscript preparation. Conference Paper Management System

Intro to Web Design. ACM UIUC

Logo Standards Guideline

Word Processing programs and their uses

CIS 467/602-01: Data Visualization

Epson Brightlink Interactive Board and Pen Training. Step One: Install the Brightlink Easy Interactive Driver

Transcription:

Modern PHP Graphics with Cairo Michael Maclean FrOSCon 2011

Who am I? PHP developer for a number of years Working on some PECL extensions Mainly graphics extensions

What is Cairo? It's a vector graphics library Good for creating graphics, not so good for manipulating photos Written by the FreeDesktop.org project, duallicenced as LGPL v2.1 or MPL v1.1

Vector vs. Raster Raster graphics are bitmaps a big matrix of pixels this is what photos are generally stored as JPEG, PNG, GIF etc are all raster graphic formats Vector graphics are descriptions of the lines, and colours that make up an image SVG, WMF, PostScript and PDF are vector formats

Who uses it?

Why do you want to use it? There are a number of reasons why you should consider it...

It's fast. Graphic created by Kore Nordmann

It gives nice output GD, while it's useful, can't do antialiasing It can't do gradients It only does raster graphics Cairo can and does do all of the above

Output example GD Cairo Graphics generated by ezcgraph

It's Free Software If you're using a recent Linux distro, you might well have the libraries installed already If not, you can download it for Windows (I'm not sure about MacOS X...)

How do you use it with PHP? There have been several Cairo extensions developed at various times for PHP PECL/Cairo aims to be definitive It provides both object oriented and procedural APIs (I'm only going to demo the object oriented one)

Installation UNIX/Linux use PECL Windows you can download it from http://perisama.net/cairo/ Intrepid folk grab it from PECL SVN and compile it yourself If you do this, please run the tests!

Using Cairo First, I need to explain a few basics

Surfaces These are what you draw on They represent an image of a certain size You can also use them as the paint when drawing on other surfaces

Surfaces You create them using the constructor: $s = new CairoImageSurface(CairoFormat::ARGB32, 1000, 1000); This creates a new Image surface, in 32 bit colour, 1000x1000 pixels in size There are different Surface classes for Images, PDFs, etc.

Surfaces The other surface types have different constructors PDF, PostScript, and SVG surface constructors take a filename or a file resource They don't have colour formats, and output data directly to the file or file resource as you draw You can write directly to php://output if you like, and send the right header

Contexts Contexts are what you use to do the drawing operations. They're objects that have methods to draw on surfaces, set colour sources, move around the surface, etc. You create a context by passing the constructor an existing CairoSurface object $c = new CairoContext($s);

Contexts Once you have a context, you can draw on your surface. The context has methods to set various properties: The colour (referred to as a source ) The line style, width, end caps, fill style, etc.

Basic context methods moveto() / relmoveto() move to a point lineto() rellineto() draw a line to a point rectangle() draw a rectangle arc() / arcnegative() draw an arc stroke() / strokepreserve() stroke the current path fill() / fillpreserve() fill the current path

An example $s = new CairoImageSurface( CairoFormat::ARGB32, 400, 400); $c = new CairoContext($s); $c->fill(); $c->setsourcergb(1, 0, 0); $c->setlinewidth(50); $c->arc(200, 200, 100, 0, 2 * M_PI); $c->stroke(); $c->setsourcergb(0, 0, 0.6); $c->rectangle(0, 160, 400, 75); $c->fill(); header("content-type: image/png"); $s->writetopng("php://output");

The result

Where's the text? The Cairo library itself supports two APIs for text; the toy API and the real API The toy API is quite sufficient for simple things It's also the only one implemented in PECL/Cairo so far CairoContext::showText() and CairoContext::textPath() are the main methods

Fonts There are a couple of ways of selecting fonts at the moment CairoContext::selectFontFace() will attempt to select the font you specify, and lets you choose italic or bold if you want The CSS2 names ( sans, serif, monospace etc.) are likely to be available anywhere

Adding text to the example After the final fill(), we add: $c->selectfontface( "sans", CairoFontSlant::NORMAL, CairoFontWeight::NORMAL); $c->moveto(5, 215); $c->setsourcergb(1, 1, 1); $c->setfontsize(48); $c->showtext("underground");

The slightly cheesy result s

Using local fonts There is also a font class that uses FreeType to load any font file that FreeType can read (which is most of them) $s = new CairoImageSurface(CairoFormat::ARGB32, 200, 100); $c = new CairoContext($s); $f = new CairoFtFontFace("vollkorn.otf"); $c->setfontface($f); $c->moveto(10, 10); $c->showtext("hello world");

Complex text handling Cairo doesn't really do text layout, it's designed for graphics You have to do the positioning work yourself Or...

Pango Pango is the text layout library generally used with Cairo

Pango I've written an extension for it too http://github.com/mgdm/php-pango

Pango Pango is able to handle laying out more complex text than Cairo is

Pango It's able to set paragraphs, and do line breaking etc

Pango It has its own HTML like markup language to handle text attributes like bold, italic, etc

Pango Markup

Pango example // $c is a CairoContext $l = new PangoLayout($c); $l->setmarkup("<i>pango</i> is rather <b>clever</b> actually"); $desc = new PangoFontDescription( DejaVu Sans Mono 24 ); $l->setfontdescription($desc); $l->showlayout();

Pango Example

</pango>

Patterns Patterns are the ink used when drawing setsourcergb() and setsourcergba() are shortcuts to set solid colour patterns You don't have to use solid colours as sources You can create gradients, either linear or radial You can use other surfaces, too

Linear gradients They are a progression from one colour to another along a line You create a CairoLinearGradient object, with a pair of coordinates representing the line Then, add stops, specifying the distance along the line and the colour in RGBA Note the line length is normalized to 1.0 when you do that

Linear gradient example $p = new CairoLinearGradient(0, -10, 0, 10); $p->addcolorstoprgba(0,1,0,0,1); $p->addcolorstoprgba(1,0,0,1,0.5); $c->setsource($pat); $c->paint();

Radial gradients These are described as having one circle of one colour inside another You pass the XY coordinates of the two circles, and their radii, as arguments to the constructors Then you add colour stops, as before

Radial gradient example $p = new CairoRadialGradient(200, 100, 50, 200, 100, 200); $p->addcolorstoprgba(0, 1, 0, 0, 1); $p->addcolorstoprgba(1, 0, 0, 1, 1); $c->setsource($p); $c->paint();

Using other surfaces As I mentioned before, you can use other surfaces as sources You can also create new Image surfaces by loading PNG files (Support for loading other filetypes is on the way...)

Example $source = CairoImageSurface::createFromPNG( dirname( FILE ). "/php-logo.png"); $c->setsourcesurface($source); $c->arc(60, 33, 40, 0, 2 * M_PI); $c->fill();

Other surface types The other two surfaces that are probably useful are PDF and SVG There are a couple of limitations, unfortunately The Cairo library has no way to create anchors in PDFs or SVGs, so you can't create hyperlinks (yet!) Both of these are written straight to a file as you create them, which you can overcome with the PHP streams API

Creating PDFs header("content-type: application/pdf"); header("content-disposition: attachment; filename=cairopdf.pdf"); $s = new CairoPdfSurface("php://output", 210 * 2.83, 297 * 2.83); $c = new CairoContext($s); $c->setfontsize(48); $c->moveto(10, 100); $c->showtext("hello world"); $c->showpage(); $s->setsize(297 * 2.83, 210 * 2.83); $c->moveto(10, 100); $c->showtext("and this should be page 2."); $c->showpage();

More on contexts Contexts have an internal stack, which means you can save a state and restore it later This is handy in certain situations, but mainly when using...

Transformations Contexts let you draw using one set of coordinates, but have them appear on the surface in another This is cool where you have a method to draw a certain item that you might want over and over in different places or orientations

Transformations CairoContext::translate() moves the origin (normally top left) to somewhere else CairoContext::scale() scales the coordinates so what you draw ends up at a different size on the surface CairoContext::rotate() rotates the coordinates to draw at a different angle

save() and restore() You can use the stack to save the current transformation, so you can go and do something else and restore later

Transformation example function drawlogo($c) { $c->save(); $c->scale(1.0, 1.0); $c->setsourcergb(1, 0, 0); $c->setlinewidth(10); $c->arc(0, 0, 25, 0, 2 * M_PI); $c->stroke(); $c->setsourcergb(0, 0, 0.6); $c->rectangle(-42.5, -7.5, 85, 15); $c->fill(); $c->setsourcergb(1, 1, 1); $c->moveto(-41, 4); $c->showtext("underground"); $c->restore(); } $c->translate(75, 75); for($i = 0; $i < 4; $i++) { drawlogo($c); $c->translate(250, 0); $c->rotate(m_pi / 2); }

Example output

Operators Normally, Cairo will draw on top of whatever is on the surface You can change this, using the operators, which are specified using CairoContext::setOperator() There are a few operators you can choose from

Basic operators CairoOperator::OVER the default replace destination CairoOperator::CLEAR clear (erase) the destination CairoOperator::IN draw where there is already something on the destination CairoOperator::OUT draw where there isn't already something on the destination...etc (check the manual, it's rather dull)

Operator examples OVER CLEAR IN OUT

New version We're releasing a new version of the extension shortly

New version Please check it out and give it a go, running the tests if you can

New version Feedback is always welcome!

Any questions?

Thank you for listening http://kore nordmann.de/blog/comparision_of_php_image_libraries.html Slides and demo code will appear online at http://mgdm.net/talks/ Drop me a line on mgdm@php.net or Twitter @mgdm or mgdm on Freenode IRC