1. 程式人生 > >osg::readPixels,glreadPixels截圖,保存圖片的alpha不對,總是255(1)

osg::readPixels,glreadPixels截圖,保存圖片的alpha不對,總是255(1)

rds its asp fbo sign graphic 源碼 cor sig

這個函數最近折磨了我很久很久,因為需要用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,英文太差不行啊~~~!!!!!!

osg::readPixels,glreadPixels截圖,保存圖片的alpha不對,總是255(1)