0

So, i'm creating a graphical Bash PS1 Generator using Javascript. The user can select any color from a palette (jscolor library) for any element they want. The value i'm getting is the RGB represantion of that color. I would like to convert that value to a number between 0-255 so it can be represented in Bash.

Example:

Input: #000000

Output: 0

Input: #FFFFFF

Output: 255

Any other input converted to the closest 8 bit representation

**I checked this post but the answers aren't quite working(I'm getting output 215 for input #FFFFFF).

Alator
  • 497
  • 6
  • 23
  • The problem you're going to run into is that you're going to "lose" some colors, and there's not a great way to "lose" them evenly. If you compressed each 8-bit color component value into 3 bits, you'd still have to discard one of them (either red, green, or blue) to fit into 8 bits. If you compressed them down into 2 bits, you could "keep" color balances, but you'd have pretty "grainy" color resolution. – mojo Dec 24 '18 at 20:01
  • @mojo In your opinion, should i give the users limited color options(red,green,blue,gray etc) ? – Alator Dec 24 '18 at 20:12
  • It kind of depends on what you want to do with these colors. There are several ways of dealing with colors. GIF, for example uses the 8-bit value as a reference to a 24-bit color value. You can only have 256 unique colors in any GIF, but they can be any of the 16 million 24-bit colors. – mojo Dec 24 '18 at 20:17
  • 1
    I once wrote a [function](https://github.com/bewuethr/bash-raytracer/blob/master/raytracer#L155) that does that for a terminal-based ray tracer, but in Bash. I used [this Q&A](https://stackoverflow.com/q/27159322/3266847) for the algorithm. – Benjamin W. Dec 24 '18 at 20:24
  • see [Dithering](https://stackoverflow.com/a/36820654/2521214) – Spektre Dec 27 '18 at 18:09

2 Answers2

2

You're getting output 215 for 0xFFFFFF due to used palette.

So-named "web-safe" palette contains 216 (6^3) colors formed with component grades (ir * 255/5, ig * 255/5, ib * 255/5) for impacts ir,ig,ib = 0..5, and 40 additional colors like "money green" or "tender salmon".

So index 215 of such palette really contains 0xFFFFFF RGB.

MBo
  • 77,366
  • 5
  • 53
  • 86
0

Here's a (bad) idea:

let rgb24=0x99FFBB
let r2="($rgb24 >> 16) >> 6"
echo "$r2"
let g2="(($rgb24 >> 8) % 256) >> 6"
echo "$g2"
let b2="($rgb24 % 256) >> 6"
echo "$b2"

let rgb8="($r2 << 4) + ($g2 << 2) + $b2"

printf "%x\n" $rgb24
printf "%x\n" $rgb8

So now, you've got two bits color intensity for each: red, green, and blue.

How you display such a thing is kind of up to you. The simplest thing to do would be to bit shift each component color by 6 and then reconstruct the original 24-bit color value. You'd have a total of four different intensities for each color, or 64 unique colors.

mojo
  • 4,050
  • 17
  • 24