PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 10, 2022

[FIXED] How to draw a gradient rectangle in PHP?

 October 10, 2022     drawing, gd, php     No comments   

Issue

I want to draw a double gradient like this gradient in PHP (in different colors).

Edit: Ended up modifying one of the provided gradient functions in the answers to simply draw the double gradient.


Solution

create gradients in PHP using the normal GD Image functions. The function uses HTML Hex Codes for the color values and then converts them over to an array that has the RGB values.

function image_gradientrect($img,$x,$y,$x1,$y1,$start,$end) {
   if($x > $x1 || $y > $y1) {
      return false;
   }
   $s = array(
      hexdec(substr($start,0,2)),
      hexdec(substr($start,2,2)),
      hexdec(substr($start,4,2))
   );
   $e = array(
      hexdec(substr($end,0,2)),
      hexdec(substr($end,2,2)),
      hexdec(substr($end,4,2))
   );
   $steps = $y1 - $y;
   for($i = 0; $i < $steps; $i++) {
      $r = $s[0] - ((($s[0]-$e[0])/$steps)*$i);
      $g = $s[1] - ((($s[1]-$e[1])/$steps)*$i);
      $b = $s[2] - ((($s[2]-$e[2])/$steps)*$i);
      $color = imagecolorallocate($img,$r,$g,$b);
      imagefilledrectangle($img,$x,$y+$i,$x1,$y+$i+1,$color);
   }
   return true;
}


$imgWidth = 300;
$imgHeight = 150;
$img = imagecreatetruecolor($imgWidth,$imgHeight);

image_gradientrect($img,0,0,$imgWidth,$imgHeight,'ff0000','0000ff');
/* Show In Browser as Image */
header('Content-Type: image/png');
imagepng($img);

/* Save as a File */
imagepng($img,'save.png');

/* Some Cleanup */
imagedestroy($img);

Just change the height & widht and color in above code and it will generate the rectangle image.



Answered By - Harshal
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing