Created
November 7, 2013 12:11
-
-
Save dkesberg/7353635 to your computer and use it in GitHub Desktop.
Imagine watermark example
Imagine: http://imagine.readthedocs.org/ https://github.com/avalanche123/Imagine
Color Contrast based on: http://www.had2know.com/technology/color-contrast-calculator-web-design.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$imagine = new Imagine\Gd\Imagine(); | |
$pathPhoto = 'photo.jpg'; | |
$pathThumbnail = 'thumb.jpg'; | |
$watermarkText = 'My watermark text'; | |
// thumb config | |
$thumbQuality = 75; | |
$thumbSize = new \Imagine\Image\Box(800, 600); | |
$thumbMode = \Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND; | |
// build font | |
$watermarkFontFile = 'font.ttf'; | |
$watermarkFontSize = 14; | |
$watermarkFontColor = new Imagine\Image\Color('#fff'); // use white as default color | |
$watermarkFont = new Imagine\Gd\Font($watermarkFontFile, $watermarkFontSize, $watermarkFontColor); | |
// get watermark dimensions | |
$watermarkBox = $watermarkFont->box($watermarkText); | |
try { | |
// try to open photo & build thumbnail | |
$photo = $imagine->open($path) | |
->thumbnail($size, $mode); | |
// calc watermark position | |
// display on bottom right with a 10 px padding | |
$watermarkPadding = 10; | |
$photoSize = $photo->getSize(); | |
$watermarkPosition = new Imagine\Image\Point($photoSize->getWidth() - $watermarkBox->getWidth() - $watermarkPadding, | |
$photoSize->getHeight() - $watermarkBox->getHeight() - $watermarkPadding); | |
// test color | |
$photoColor = $photo->getColorAt($watermarkPosition); | |
// color brightness formula | |
// ( 299*R + 587*G + 114*B ) / 1000 | |
// is sufficient if brightness diff > 125 | |
$brightnessBreakpoint = 125; | |
$brightnessWatermark = (299 * $watermarkFontColor->getRed() + 587 * $watermarkFontColor->getGreen() + 114 * $watermarkFontColor->getBlue()) / 1000; | |
$brightnessPhoto = (299 * $photoColor->getRed() + 587 * $photoColor->getGreen() + 114 * $photoColor->getBlue()) / 1000; | |
$brightnessDiff = $brightnessWatermark - $brightnessPhoto; | |
// use black text if brightness difference is not sufficient | |
if ($brightnessDiff < $brightnessBreakpoint) { | |
$watermarkFontColor = new Imagine\Image\Color('#000'); | |
$watermarkFont = new Imagine\Gd\Font($watermarkFontFile, $watermarkFontSize, $watermarkFontColor); | |
} | |
// draw watermark | |
$photo->draw()->text( | |
$watermarkText, | |
$watermarkFont, | |
$watermarkPosition | |
); | |
// save thumb | |
$photo->save($pathThumbnail, array( | |
'quality' => $quality, | |
'format' => 'jpg' | |
)); | |
} catch(Exception $e) { | |
// oh noes | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment