Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting rgba values into one integer in Javascript

I can already convert 32bit integers into their rgba values like this:

pixelData[i] = {
        red: pixelValue >> 24 & 0xFF,
        green: pixelValue >> 16 & 0xFF,
        blue: pixelValue >> 8 & 0xFF,
        alpha: pixelValue & 0xFF
    };

But I don't really know how to reverse it.

like image 287
skerit Avatar asked Jul 30 '13 11:07

skerit


1 Answers

To reverse it, you just have to combine the bytes into an integer. Simply use left-shift and add them, and it will work.

var rgb = (red << 24) + (green << 16) + (blue << 8) + (alpha);

Alternatively, to make it safer, you could first AND each of them with 0xFF:

var r = red & 0xFF;
var g = green & 0xFF;
var b = blue & 0xFF;
var a = alpha & 0xFF;

var rgb = (r << 24) + (g << 16) + (b << 8) + (a);

(You may use bitwise OR | instead of + here, the outcome will be the same).

like image 111
MightyPork Avatar answered Oct 04 '22 07:10

MightyPork