Author Topic: Code snippet - reverse of imagecolorat  (Read 2614 times)

0 Members and 1 Guest are viewing this topic.

Offline carterlake

  • Senior Contributor
  • ****
  • Posts: 243
    • CarterLake.org
Code snippet - reverse of imagecolorat
« on: October 28, 2007, 06:57:36 PM »
Not sure what anyone would use this for, but this reverses the PHP imagecolorat tag so that you can use the image you want to add text to, to set the contrasting color for the text (so if image dark, text is light, and vice versa).

I'm using this in my webcam pause image.... (I.E. I don't set the text color... the software does)

http://www.carterlake.org/cam_pause.php

Code: [Select]
$backgroundcolor = imagecolorat($origimg, 280, 420);

            # Get the rgb values from color $c
            $r = ($backgroundcolor >> 16) & 0xFF;
            $g = ($backgroundcolor >> 8) & 0xFF;
            $b = $backgroundcolor & 0xFF;

            $r = abs( $r - 255 );
            $g = abs( $g - 255 );
            $b = abs( $b - 255 );
           
            # Set the color
            $reverse = imagecolorallocate( $newimg, $r, $g, $b );


Davis VP2 6153; Weather Display (LIVE w/ Ajax); Quickcam for Notebooks Pro; Boltek w/ Nexstorm; GRLevel3; live NOAA Radio

Offline SLOweather

  • Administrator
  • Forecaster
  • *****
  • Posts: 3430
    • http://www.sloweather.com
Re: Code snippet - reverse of imagecolorat
« Reply #1 on: October 28, 2007, 07:05:40 PM »
Actually, that might be quite useful. I spent a lot of time selecting text colors for my weather graphics (nee weather sticker) images, since they were photographs. For that reason, I've been loathe to change the backgrounds. This could make that easier. Also, as you have done, labeling my web cam images, as well.

Thanks!

Offline SLOweather

  • Administrator
  • Forecaster
  • *****
  • Posts: 3430
    • http://www.sloweather.com
Re: Code snippet - reverse of imagecolorat
« Reply #2 on: December 11, 2007, 03:05:44 PM »
I finally played with this today. It took me a bit to figure out one little gotcha with it. It works great with pure colors. However, the closer the background color gets to gray, the more subtle the color difference. In fact, at pure gray, (50% of R, G and B) the reverse is the same color as the background.

EDIT: I tried shifting each color by successive thirds. Makes kinda weird colors, but it avoids the gray complement problem.

            $r = abs( $r - 255 );
            $g = abs( $g - 170 );
            $b = abs( $b - 85 );
« Last Edit: December 11, 2007, 03:33:53 PM by SLOweather »

 

anything