Click here to Skip to main content
15,861,168 members
Articles / Programming Languages / PHP

Draw Guitar Chords using PHP

Rate me:
Please Sign up or sign in to vote.
4.60/5 (5 votes)
26 Jul 2010CC (ASA 3U)3 min read 45.3K   748   10   15
PHP class to draw guitar chords

Introduction

This is a PHP class which can draw guitar chords, or any other string instruments for that matter.

It makes heavy use of the GD2 image library to build good looking chord diagrams in very few lines of code.

Background

Being an ukulele player myself (and bad guitar player also); I've visited tons of websites that were displaying guitar chords like "x23240" or without any description of the chord at all.

With the help of a few lines of PHP; I thought I could develop a highly customizable class to display those chords.

Using the Code

The class is named "chord" an can be used very easily with few lines of codes. The code:

PHP
<?php
include('chord.inc.php');
$c = new chord(array('x',3,2,0,1,0));
$c->draw();
?> 

It will output a PNG file like this one:

Points of Interest

The main point of interest is that the class is highly customizable. With a few more function calls you can set a title, margins, font sizes, custom colors and a custom background picture among other things.

Support for barre chords was also added. For instance, the following chord...

...was obtained by using:

PHP
<?php
include('chord.inc.php');
$c = new chord(array('x','x',0,0,0,8));
$c->setShowZeros(false);
$c->setMarginRight(20);
$c->setBarreChord(7,3,6);
$c->setStartingFret(5);
$c->draw();
?>

I wanted this class to work out of the box on any PHP5 setup, but in the meantime let users go more in depth with the class if they wished.

For instance, one interesting mechanism is the font. As you may be aware, GD2 with PHP has 5 built in fonts represented by numbers ranging from 1 to 5. They are rather ugly pixel fonts but they do work out of the box. In order to support both built in fonts and custom TTF fonts, people would upload on their webserver; there is some small logic in the setFontxxx methods:

PHP
<?php
function setFontTitle($v)
{
	if(is_int($v))
	{
		//1 to 5 is the correct range for built in fonts
		if($v >= 1 && $v <= 5)
			$this->fontTitle = $v;
		else
			throw new Exception('Built in font must be in 1 to 5 range');
	}
	else if(is_string($v))
	{
		$this->fontTitle = $v;
	}
	else
	{
		throw new Exception
		('Use a TTF file or a number representing a built in font');
	}
} ?> 

With this logic, you can either do $c->setFontTitle('arial.ttf'); or $c->setFontTitle(5);. Then, when it comes to drawing; the class calls "imagestring" or "imagettftext" which are PHP functions to draw text using built in fonts or TTF fonts respectively.

The rest of the interesting logic is located in the draw() method of the class. A lot of logic has been added to support any size of chord. By default, the PNG picture will be 90x120 but as the user can set any size; the final result had to be consistent.

As such, the size of the circle representing a string to be fretted is proportional to the fret spacing size. As such; if fancy values are used, the chord will react accordingly:

It is the responsibility of the user to tune the settings as he wishes.

Code-wise, this creates a lot of computations prior to drawing anything.

Namely, we need to:

  1. Count the number of strings
  2. Compute real width space available for drawing (without margin)
  3. Deduce space in pixels between each string
  4. Compute the size of upper symbols "o" or "x"
  5. Deduce total top margin
  6. If there is a title, compute the size of the text in pixel and add it to the total top margin
  7. Deduce real height space available for drawing (without margin)
  8. Compute the size in pixels between each fret
PHP
<?php
$nbStrings = count($this->data);
$realWidth = $this->width - $this->margin['left'] - $this->margin['right'];
$stringSpacing = ($realWidth / ($nbStrings-1));
$upperSymbolSize =  intval(round($stringSpacing *
	$this->upperSymbolSize));	//space needed to draw the "o" or "x"
$totalTopMargin = $this->margin['top'] + $upperSymbolSize;
$titleMargin = 0;
//if there's a title, compute additional top margin induced
if(!empty($this->title))
{
	if(is_int($this->fontTitle))
	{
		$titleMargin = imagefontheight($this->fontTitle);
	}
	else
	{
		$box = imagettfbboxextended($this->fontTitleSize,
				0, $this->fontTitle, $this->title);
		$titleMargin = $box['height'];
	}
}
$totalTopMargin += $titleMargin;
$realHeight = $this->height - $totalTopMargin - $this->margin['bottom'];
$fretsSpacing = $realHeight / ($this->maxFrets);
?>

When we have all those values, the rest of the code is a piece of cake: draw a grid; draw the stuff where they need to be and this is it!

History

  • 2010-07-25: First release

License

This article, along with any associated source code and files, is licensed under The Creative Commons Attribution-Share Alike 3.0 Unported License


Written By
Systems Engineer
France France
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
BugHow to adapt to php 8+ Pin
Thomas Dilts31-Oct-23 11:09
Thomas Dilts31-Oct-23 11:09 
GeneralMy vote of 5 Pin
Mateus Cabral16-Jul-13 2:14
Mateus Cabral16-Jul-13 2:14 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey23-Feb-12 18:58
professionalManoj Kumar Choubey23-Feb-12 18:58 
GeneralMy vote of 5 Pin
Herman_6-Aug-11 4:52
Herman_6-Aug-11 4:52 
GeneralPHP Chord error message Pin
Member 77256204-Mar-11 2:00
Member 77256204-Mar-11 2:00 
wanted to give it a try but after installation I'm getting this error message:

Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /homepages/7/d290885545/htdocs/widget/PHP/Chords/chord/chord.inc.php on line 30

any idea why ?
QuestionDo you know where to find chord definitions? Pin
Middle Manager3-Aug-10 2:01
Middle Manager3-Aug-10 2:01 
AnswerRe: Do you know where to find chord definitions? Pin
Tony Pottier3-Aug-10 4:36
Tony Pottier3-Aug-10 4:36 
GeneralRe: Do you know where to find chord definitions? Pin
Middle Manager3-Aug-10 9:20
Middle Manager3-Aug-10 9:20 
GeneralMusic notes Pin
JoseMenendez26-Jul-10 4:24
JoseMenendez26-Jul-10 4:24 
GeneralRe: Music notes Pin
Tony Pottier26-Jul-10 5:20
Tony Pottier26-Jul-10 5:20 
GeneralRe: Music notes Pin
Lee Hiles31-Jul-10 19:51
Lee Hiles31-Jul-10 19:51 
GeneralNot enough for an article Pin
Md. Marufuzzaman25-Jul-10 7:34
professionalMd. Marufuzzaman25-Jul-10 7:34 
GeneralRe: Not enough for an article Pin
Tony Pottier25-Jul-10 7:45
Tony Pottier25-Jul-10 7:45 
GeneralRe: Not enough for an article Pin
Dave Kreskowiak25-Jul-10 8:10
mveDave Kreskowiak25-Jul-10 8:10 
GeneralRe: Not enough for an article Pin
Tony Pottier25-Jul-10 8:50
Tony Pottier25-Jul-10 8:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.