osg::readPixels,glreadPixels截图,保存图片的alpha不对,总是255(1)

       这个函数最近折磨了我很久很久,因为需要用osg截图保存到本地,但是这个图片要具有alpha值,也就是背景的alpha值全为0,但是在公司上用_image->readPixels(448, 28, 1024, 1024, GL_RGBA, GL_UNSIGNED_BYTE);截图出来的是成功有alpha值的,但是就是alpha值全为255(1),因为1个alpha值是8位,全1的话就是255,也就是背景全不透明,但是我的要求是背景透明,截图中的物体不透明,然后千方百计试,试了FBO(帧缓存对象),也就是OSG里面的渲染到纹理的做法,确实成功,但是不好调节渲染相机的几个矩阵,这里有类似的源码http://bbs.osgchina.org/forum.php?mod=viewthread&tid=1703&highlight=%E4%D6%C8%BE%B5%BD%CE%C6%C0%ED&_dsign=f8f30f82,太麻烦对我来说就放弃了,最后一想,怎么可能readPixels这个函数不能截出alpha值,于是在网上搜,百度硬是不出来,google也出不来,最后用英文搜google,出来了,找到原因了,如下:

https://www.opengl.org/discussion_boards/showthread.php/152623-Why-glReadPixels-always-read-alpha-value-as-255

https://www.gamedev.net/forums/topic/136637-glreadpixels-amp-alpha-values/

也就是说没有设置好cAlphaBits这个值,导致出错,我查看了一下osg::GraphicsContext源码,它默认R,G,B都是8,A是0,于是我在自己的代码里重新设置了一个gc,如下:

osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
traits->x = 0;
traits->y = 0;

//屏幕分辨率

traits->width = 1920;
traits->height = 1080;
//支持窗口扩展,默认是不支持的
traits->windowDecoration = true;
//支持双缓存,默认不支持
traits->doubleBuffer = true;
traits->sharedContext = 0;
traits->red = 8;
traits->blue = 8;
traits->green = 8;
//支持alpha,默认不支持为0,这里改为支持,使截出来的图片具有alpha值
traits->alpha = 8;

osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
if (gc.valid())
{
std::cout << "create" << std::endl;
}
double fovy, aspectRatio, zNear, zFar;
viewer->getCamera()->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar);
double newAspectRatio = double(traits->width) / double(traits->height);
double aspectRatioChange = newAspectRatio / aspectRatio;
if (aspectRatioChange!=1.0)
{
viewer->getCamera()->getProjectionMatrix() *= osg::Matrix::scale(1.0 / aspectRatioChange, 1.0, 1.0);
}
viewer->getCamera()->setViewport(0, 0, 1920, 1080);
viewer->getCamera()->setGraphicsContext(gc.get());

然后readPixels出来的图片就有正确的alpha值的,感谢google,英文太差不行啊~~~!!!!!!

转载于:https://www.cnblogs.com/tangmiao/p/7641101.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值