Converting rgba values into one integer in Javascript

僤鯓⒐⒋嵵緔 提交于 2019-12-10 01:04:28

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/17945972/converting-rgba-values-into-one-integer-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!