问题描述
将颜色值从浮点数转换为字节的正确方法是什么?起初我认为 b=f*255.0
应该这样做,但现在我在想,在这种情况下,只有确切的 1.0
会被转换为 255
,但 0.9999
已经是 254
这可能不是我想要的...
What would be the correct way of converting color value from float to byte? At first I thought b=f*255.0
should do it, but now I'm thinking, that in this case only the exact 1.0
will be converted to 255
, but 0.9999
will already be 254
which is probably not what I want...
看起来 b=f*256.0
会更好,除了在精确的 1.0
的情况下它会产生 256
代码>.
It seems that b=f*256.0
would be better except that it would have an unwanted case of making 256
in the case of exact 1.0
.
最后我使用了这个:
#define F2B(f) ((f) >= 1.0 ? 255 : (int)((f)*256.0))
推荐答案
1.0 是唯一可能出错的情况,所以单独处理:
1.0 is the only case that can go wrong, so handle that case separately:
b = floor(f >= 1.0 ? 255 : f * 256.0)
此外,为了避免由于舍入误差(例如 f=1.0000001)导致的错误行为,强制 f 确实是 0
Also, it might be worth forcing that f really is 0<=f<=1 to avoid incorrect behaviour due to rounding errors (eg. f=1.0000001).
f2 = max(0.0, min(1.0, f))
b = floor(f2 == 1.0 ? 255 : f2 * 256.0)
替代安全解决方案:
b = (f >= 1.0 ? 255 : (f <= 0.0 ? 0 : (int)floor(f * 256.0)))
或
b = max(0, min(255, (int)floor(f * 256.0)))
这篇关于将颜色值从浮点 0..1 转换为字节 0..255的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!