Generate Guitar Chords with PHP
Many sites provides guitar chords/tabs in a text format and these can be little hard to read sometimes. Here's a quick article on how to generate an image of a guitar chords in PHP.
First, you will have to get these two files:
Then, create a PHP script (call it chords.php) with the following code:
define('IMAGE_EXT', '.jpg');
define('PATH', './');
function generateChords($chord, $filename) {
$imgfile = PATH . 'guitar.jpg';
$text = '.';
$font = PATH . 'arial.ttf';
$im = imagecreatefromjpeg($imgfile);
$x = imagesx($im);
$y = imagesy($im);
$fontsize = 100;
$white = imagecolorallocate($im, 0, 0, 0);
$chords = explode('-', $chord);
// chords[0] = e1 and chords[5] = e6
$minimum = min($chords);
imagettftext($im, 15, 0, 1, 32, $white, $font, $minimum);
$add = 0;
if($minimum > 0) {
$add = 30;
}
// chords positions
$interval1 = ($chords[0] != 0 ? (25 + $add + (intval($chords[0]) - $minimum) * 30) : 0);
$interval2 = ($chords[1] != 0 ? (25 + $add + (intval($chords[1]) - $minimum) * 30) : 0);
$interval3 = ($chords[2] != 0 ? (25 + $add + (intval($chords[2]) - $minimum) * 30) : 0);
$interval4 = ($chords[3] != 0 ? (25 + $add + (intval($chords[3]) - $minimum) * 30) : 0);
$interval5 = ($chords[4] != 0 ? (25 + $add + (intval($chords[4]) - $minimum) * 30) : 0);
$interval6 = ($chords[5] != 0 ? (25 + $add + (intval($chords[5]) - $minimum) * 30) : 0);
// write to the image
imagettftext($im, $fontsize, 0, 01, $interval1, $white, $font, $text);
imagettftext($im, $fontsize, 0, 18, $interval2, $white, $font, $text);
imagettftext($im, $fontsize, 0, 36, $interval3, $white, $font, $text);
imagettftext($im, $fontsize, 0, 53, $interval4, $white, $font, $text);
imagettftext($im, $fontsize, 0, 70, $interval5, $white, $font, $text);
imagettftext($im, $fontsize, 0, 86, $interval6, $white, $font, $text);
imagejpeg($im, $filename);
}
if(!isset($_GET['chord']) || substr_count($_GET['chord'], '-') != 5) {
$_GET['chord'] = '0-0-0-0-0-0';
}
$filename = PATH . $_GET['chord'] . IMAGE_EXT;
if(!file_exists($filename)) {
generateChords($_GET['chord'], $filename);
}
header('Content-type: image/jpeg');
readfile($filename);
ImageDestroy($im);
On your HTML page you simply call like this:
<img src="chords.php?chord=1-3-3-1-1-1" alt="chord 1-3-3-1-1-1" width="125" height="306" />
This will output:




