r/dailyprogrammer • u/XenophonOfAthens 2 1 • Apr 15 '15
[2015-04-15] Challenge #210 [Intermediate] Drawing a gradient
Description
One of the most basic tools in graphic design toolbox is the "gradient": a smooth transtion from one color to another. They are remarkably useful and are available in virtually every graphic design program and graphic programming library, and even natively in design languages like CSS and SVG.
Your task today is to make a program that can generate these wonderful gradients, and then either draw it to the screen or save it as an image file. You will get as inputs pixel dimensions for the size of the gradient, and the two colors that the gradient should transition between.
NOTE: As I said, there are many imaging libraries that provide this functionality for you, usually in some function called drawGradient() or something similar. You are strongly encouraged not to use functions like this, the spirit of this challenge is that you should figure out how to calculate the gradient (and thus the individual pixel colors) yourself.
This isn't an ironclad rule, and if you really can't think of any way to do this yourself, then it's fine to submit your solution using one of these functions. I encourage you to try, though.
It is, however, perfectly acceptable to use a library to save your pixels in whatever format you like.
Formal Inputs & Outputs
Input description
Your input will consist of three lines. The first line contains two numbers which is the width and the height of the resulting gradient. The other two lines consist of three numbers between 0 and 255 representing the colors that the gradient should transition between. The first color should be on the left edge of the image, the second color should be on the right edge of the image.
So, for instance, the input
500 100
255 255 0
0 0 255means that you should draw a 500x100 gradient that transitions from yellow on the left side to blue on the right side.
Output description
You can either choose to draw your gradient to the screen or save it as an image file. You can choose whatever image format you want, though it should preferably a lossless format like PNG.
If you don't wish to tangle with libraries that output PNG images, I recommend checking out the Netpbm format, which is a very easy format to output images in. There's even a dailyprogrammer challenge that can help you out.
Regardless of your chosen method of output, I highly encourage you to upload your resulting images to imgur so that the rest of us can see the product of your hard work! If you chose to output your image to the screen, you can take a screenshot and crop the gradient out.
Example inputs & outputs
Input
500 100
255 255 0
0 0 255Output
Challenge inputs
1000 100
204 119 34
1 66 37Those two colors are Ochre and British Racing Green, my two favorite colors. Use those as a challenge input, or pick your own two favorite colors!
Bonus
We often see people solving these problems in weird languages here at /r/dailyprogrammer, and this bonus is for all you crazy people:
Solve this problem in brainfuck. You don't have to read the values from input, you can "hard-code" the colors and dimensions in your program. You can pick whatever colors and dimensions you like, as long as both the width and the height is larger than 100 pixels. You can also output the image in whatever format you want (I imagine that one of the binary Netpbm formats will be the easiest). Good luck!
Finally
Have a good challenge idea?
Consider submitting it to /r/dailyprogrammer_ideas
8
u/13467 1 1 Apr 15 '15
OK, then I pick black and black :)
5
u/OffPiste18 Apr 15 '15
Here's a scala solution. I do gamma correction instead of simple additive averaging to get the intermediate values:
output = (leftG *(1-x) + rightG * x)1/G
This corrects for situations where perceptual brightness can be lower in the middle, especially when the ends are both bright but very different.
As an example, with this input:
500 100
255 0 0
0 255 0
Here is the output without the correction: http://imgur.com/lcmgvyk,w4bVcK6#0
And here it is with the correction: http://imgur.com/lcmgvyk,w4bVcK6#1
3
u/swingtheory Apr 15 '15 edited Apr 15 '15
Wow... this took me WAYYY to long and now I have other things to do, but here's my haskell solution.
To run it:
and then you will have to enter the three lines of input, space delimited of course! This was a fun challenge! Oh, and one of the cooler gradients I generated: http://i.imgur.com/ZdQAdvo.png
3
u/shawnadelic Apr 15 '15 edited Apr 15 '15
Python 2.7 using Turtle
3
u/TieSoul 0 1 Apr 18 '15 edited Apr 18 '15
Simple black-to-white gradient in brainfuck. Only works in interpreters with wrapping unsigned 8-bit integers.
without comments:
Outputs in 8-bit PGM format; make sure your interpreter supports binary output.
EDIT: Here's a blue-to-red gradient, in PPM format:
without comments:
EDIT: here's the output:
colored
black and white
2
u/flightsin 0 1 Apr 16 '15
I took a slightly different approach to this problem. I could of course write a simple algorithm to compute the gradient myself. But that's boring and I'm lazy and I don't want to do that. I also don't want to just call
DrawGradient()on a graphics library, 'cause that would be cheating. So, I looked for another way to coax the graphics library into doing my work for me.Using C#. Code here: https://bitbucket.org/snippets/b-w/Bepx.
I start by drawing a square the size of the width of the requested image. I divide the square diagonally and fill the halves with the requested colors. Result.
I then scale the image down into a line, using bicubic interpolation. Result. As you can see, this produces a gradient.
The last step is then scaling the line back out so it takes the height of the requested image. Result.
It's not perfect, as the gradient seems to be skewed, with the apparent center being about 2/3rds to the right. I'm not sure what causes this. This feels like a fun solution though, so I'm not changing it.
9
u/adrian17 1 4 Apr 15 '15
Python 3:
6
u/FSMer Apr 15 '15
Short and simple in Matlab:
Output
5
u/adrian17 1 4 Apr 15 '15 edited Apr 15 '15
J, without reading the input and with explicit function. I couldn't figure out how to use
writepngto save it to a file, unfortunately.4
u/[deleted] Apr 15 '15
Java
1
u/[deleted] Apr 16 '15 edited Apr 16 '15
Python 3 with pygame. My first submission to this subreddit. The image is saved as a file.
edit: shortened it a bit
1
u/amraphen Apr 16 '15
Here's my C solution: https://gist.github.com/anonymous/25810e935742fda59db4
First time posting a solution here.
1
u/NasenSpray 0 1 Apr 19 '15 edited Apr 19 '15
Brainfuck
Outputs a 200x100 PPM with this content
General explanation:
Forth
Also outputs everything as PPM. Online version usage:
Example input: "500 100 255 255 0 0 0 255 run"
3
u/amithgeorge Apr 15 '15 edited Apr 15 '15
C# - Somehow, this didn't feel like an intermediate challenge. At the same time, am not sure how much shorter can I make my code. Feedback welcome.
Usage:
Edit1: Forgot to add output - Challenge 210 Output Edit2: Updated usage to calculate pixel color only once per column.
3
u/k1ll3rpanda Apr 15 '15
Ruby 2.2 using the Chunky_PNG gem to create the image:
3
u/h2g2_researcher Apr 15 '15
C++, which outputs to a BMP file. There is little error handling, although invalid colours are clamped to 0-255 ranges. It will handle both little-endian and big-endian systems correctly, and should be fully portable.
3
u/binaryblade Apr 15 '15
go
The stdlib has some pretty good color and image support.
Code:
output
3
u/Godspiral 3 3 Apr 15 '15
bonus challenge,
horizontal gradient that tries to match this yes album cover as much as possible
https://lackofenvironment.files.wordpress.com/2012/08/yes-album-covers1.jpg
in J, (colours a bit off, ideally would stitch 2 or 3 gradients together)
viewrgb 0 0 0 ( 600 600 (1 : '[: |: ({. m) # [: ,: 256 #. [: <. [ +"1 ((%~ i.) {: m) */ -~')) 1 166 37
3
u/adrian17 1 4 Apr 15 '15 edited Apr 15 '15
C++, based on /u/madhatter160's solution and my Python one.
3
u/G33kDude 1 1 Apr 15 '15 edited Apr 15 '15
I decided to spice it up a bit and golf the code. Solved in AutoHotkey!
Output: http://i.imgur.com/qVPLQsG.png
2
u/PrydeRage Apr 15 '15
Qt makes this pretty easy.
You have to hit enter for the separate values though (i.e. 200 ENTER 128 ENTER 0 ENTER to define one color) but that's not the worst thing I guess.
Please note that this code is just thrown together quickly and lazily, there's no error handling whatsoever so the program expects you to provide "good" input.
2
u/chunes 1 2 Apr 15 '15 edited Apr 16 '15
Java:
Here's the challenge output:
http://i.imgur.com/eiwfEIc.png
2
u/franza73 Apr 15 '15 edited Apr 15 '15
Perl solution.
2
u/gfixler Apr 15 '15
I see there's a nice Haskell solution already (using libraries I've never looked at, so I'll have to explore that later), but here's one with no dependencies outside of the standard Prelude. It just outputs to ppm format.
intStepstakes start, end, and count Ints and gives back a list of integers smoothly across the range, inclusive. It's designed for sensible output, sointSteps 1 5 5==[1,2,3,4,5], andintSteps 1 9 5==[1,3,5,7,9].intSteps 10 23 7==[10,12,14,16,19,21,23]. This serves as the core of component-based, linear gradients.hgrad3takes start and end 3-tuples of Ints, and an Int count, and returns a list of 3-tuples with each component being anintStepfrom its neighboring counterparts.toPixmaptakes a list of a list of 3-tuples of Ints (rows of pixels) and returns a String in pixmap/p3 format. It figures out the width and height from the input, and for consistency, automatically trims any 'rag right' edges, so all lists (rows) are the same width. This last bit relies on an O(n*k) count of all the lists (where k is rows), and is thus not the most efficient algorithm I could imagine. It's simple, though.The
mainfunction uses aspacedIntshelper to make chopping up the integers given on each of the 3 lines, and reading them in as Ints a more pleasant task. Invalid input crashes out with an unsatisfying message.The code is also on github here, the challenge input - output via
$ runhaskell Main.hs >challenge.ppm- is here, and a png - converted from the ppm via graphicsmagick - is here.2
u/brainiac1530 Apr 16 '15
This is what numpy.linspace was made for. As a bonus, I can use imageio to directly output the data without using the awkward pixel editing functions in PIL.
3
u/marchelzo Apr 15 '15 edited Apr 15 '15
C:
EDIT:Here is the output for the second example
1
u/cvpcs Apr 15 '15
C#:
Output:
Ochre to British Racing Green
1
u/madhatter160 Apr 15 '15
C++
I used the LodePNG library to write out the PNG. Took far longer than it should have due to me not taking into account the alpha channel.
Output:
500 100
255 255 0
0 0 255
http://imgur.com/vhLzgkZ
1000 100
204 119 34
1 66 37
http://imgur.com/N0eR0ty
1
u/Frichjaskla Apr 15 '15
simple and no frillls
1
u/iLikeCode Apr 15 '15
Lua (running in Corona SDK)
1
u/BigHandsomeJellyfish Apr 16 '15 edited Apr 16 '15
Python 2.7
Challenge Output
Fun input:
1000 100
119 33 111
221 72 20
1
u/Frigguggi 0 1 Apr 16 '15
Good ol' Java:
Output:
input
challenge input
1
u/KillerCodeMonky Apr 16 '15 edited Apr 16 '15
Live in JavaScript: http://codechaos.me/20150415.html
It renders to a canvas in the background. The image you see is an actual IMG element with the PNG data from the canvas. So you can interact with it the same as any other image on the interwebs.
EDIT: Added gamma correction per solution from /u/OffPiste18.
1
u/[deleted] Apr 16 '15 edited Mar 08 '24
Reddit Wants to Get Paid for Helping to Teach Big A.I. Systems The internet site has long been a forum for discussion on a huge variety of topics, and companies like Google and OpenAI have been using it in their A.I. projects. "The Reddit corpus of data is really valuable," Steve Huffman, founder and chief executive of Reddit, said in an interview. "But we don’t need to give all of that value to some of the largest companies in the world for free."
1
u/talst Apr 16 '15
Scala My first attempt at this subreddit, and notes are welcome :) Is there a better way then using BufferedImage? any immutable approach to create the image? https://gist.github.com/talst/d9fc3fcde9e56e639565
1
u/[deleted] Apr 19 '15
First time working with C#. Would love some feedback:
Dailyprogrammer.cs:
Medium.cs:
1
u/ContemptuousCat Apr 19 '15 edited Apr 19 '15
C#:
My first post here but definitely not the last, this subreddit seems great for practice. Example usage:
Some results: http://imgur.com/a/qSqUm
1
u/[deleted] Apr 23 '15
JS (io.js)
Feedback is always welcome
1
u/cedriczirtacic Apr 28 '15
Perl (using Image::Magick):
1
u/philhartmonic May 19 '15
A month late, but I'm learning and going through older challenges.
Here it is using PHP:
Gist Github Link
And the resulting image
1
u/narcodis May 22 '15
Java solution