Click here to Skip to main content
Click here to Skip to main content

Draw Guitar Chords using PHP

By , 26 Jul 2010
 

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
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
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
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
$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

About the Author

Tony Pottier
Systems Engineer
France France
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5membermanoj kumar choubey23 Feb '12 - 18:58 
Nice
GeneralMy vote of 5memberYusufHermanto6 Aug '11 - 4:52 
nice Smile | :)
GeneralPHP Chord error messagememberMember 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?memberEd Bouras3 Aug '10 - 2:01 
Hi Tony. I don;t work with PHP but I appreciate the content of the article nonetheless. I started writing a .NET version that could assist in looking up finger placements for chords but I let the project go to fallow. Your article may breathe some life into it again but I was wondering if you or anyone else here knows where I can find a "dictionary" of chord definitions? I suppose I'm just being lazy but I really don't want to hand enter 180 chords from a book. Any ideas?
AnswerRe: Do you know where to find chord definitions?memberTony Pottier3 Aug '10 - 4:36 
Hi Ed,
 
Unfortunately it seems the music world is still largely dominated by books/word of mouth. When I created this class I've been looking for some kind of open database myself with all the chords. I couldn't find anything but maybe you'll have more luck than me.
 
Cheers,
Tony
GeneralRe: Do you know where to find chord definitions?memberEd Bouras3 Aug '10 - 9:20 
Shucks! Sniff | :^) I'll be sure to pass it along should I find it then.
GeneralMusic notesmvpJose Menendez Póo26 Jul '10 - 4:24 
I think the article is good, I just would like to see the explain of why are notes drawn like that, for those of us who have no clue about music and notes.
Jm
www.menendezpoo.com
www.amazingpedia.com

GeneralRe: Music notesmemberTony Pottier26 Jul '10 - 5:20 
I couldn't find the origin of this representation of chords; Wikipedia[] doesn't say a word about it. Most likely; it's because it looks exactly like guitar frets.
GeneralRe: Music notesmemberLee Hiles31 Jul '10 - 19:51 
The images generated by the authors script are more commonly known as guitar 'tabs'. They are not musical notes but rather the circles represent finger placements on the fretboard. The textual notation (ie x13300) would map to the number of the fret being pressed for each string. For the example X13300, the top string would not be played as represented by the X, then the first fret would be pressed for the second string, the 3rd fret for the 3rd string and so on down the fret board.
 
Just a little more info for those who are not familiar with this notation.
GeneralNot enough for an articlemvpMd. Marufuzzaman25 Jul '10 - 7:34 
Frown | :(
Thanks
Md. Marufuzzaman


I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.

GeneralRe: Not enough for an articlememberTony Pottier25 Jul '10 - 7:45 
Do you want me to go more in depth? I didn't want to bore readers!
GeneralRe: Not enough for an articlemvpDave Kreskowiak25 Jul '10 - 8:10 
You also have to interest readers. Right now, you've got a Cliff-Notes version of an article. There simply isn't enough information here.

A guide to posting questions on CodeProject[^]



Dave Kreskowiak
Microsoft MVP
Visual Developer - Visual Basic
     2006, 2007, 2008
But no longer in 2009...




GeneralRe: Not enough for an articlememberTony Pottier25 Jul '10 - 8:50 
Alright Dave I appreciate your input. I have amended the article and I hope this time it complies with the website's policy.

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 26 Jul 2010
Article Copyright 2010 by Tony Pottier
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid