Converting rgba values into one integer in Javascript

前端 未结 1 1297
余生分开走
余生分开走 2021-02-19 03:01

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

pixelData[i] = {
        red: pixelValue >> 24 & 0xFF,
        green: pixelValue         


        
相关标签:
1条回答
  • 2021-02-19 03:11

    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).

    0 讨论(0)
提交回复
热议问题