Skip to content

Instantly share code, notes, and snippets.

@gavinblair
Created September 20, 2010 22:00
Show Gist options
  • Save gavinblair/588729 to your computer and use it in GitHub Desktop.
Save gavinblair/588729 to your computer and use it in GitHub Desktop.
Adding a year ribbon to thumbnails with PHP and GD
<div class="film">
<div class="imgbox">
<div style="background-image: url(ribbon.php?text=2010)" class="year">
</div>
<img height="151" width="200" alt="In tellus" src="robot1.gif" />
</div>
<h4><a href="/in-tellus-libero">In tellus libero</a></h4>
<p>In tellus libero, pretium et rhoncus ut, fringilla et enim. Duis at dolor non dolor ultricies…</p>
</div>
<?php //make sure there is no whitespace echoed or it will cause an error!
//Usage: Use this file as the src for an <img> tag or a CSS background image.
// <img src='ribbon.php?text=1985' />
// .ribbon { background-image: url(ribbon.php?text=1985); }
//we're making a transparent PNG
header("Content-type: image/png");
//Load in the ribbon image
$im=imagecreatefrompng("ribbon.png");
//The background color is pink
$bg_color = imagecolorallocate($im, 255, 162, 144);
//Set pink as transparent in this image
imagecolortransparent($im,$bg_color);
//Text color is white
$text_color = imagecolorallocate($im, 255, 255, 255);
//To use Arial, we have to include arial.ttf. You can find it in your fonts directory.
//The text that we're outputting is from the query string.
imagettftext($im, 14, 45, 30, 60, $text_color, 'arial.ttf', $_GET['text']);
//Output the image
imagepng($im);
//Cleanup
imagedestroy($im);
//Let's leave out the end-php tag so we don't end up with accidental whitespace!
/* This contains an image and the ribbon */
.imgbox {
float: left;
height: 152px;
margin-right: 24px;
overflow: hidden;
position: relative;
text-align: center;
width: 202px;
}
/* This is the ribbon */
.imgbox .year {
bottom: 0;
height: 63px;
position: absolute;
right: 0;
width: 108px;
background: transparent;
background-position: bottom right;
}
@gavinblair
Copy link
Author

I know this is possible with CSS3, but with GD the result is cleaner (doesn't wiggle when you hover over it), and automatically consistent cross-browser.

@SeanJA
Copy link

SeanJA commented Sep 24, 2010

Why not modify the actual image and save a copy of it instead of creating it every time?

@gavinblair
Copy link
Author

good idea.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment