zoukankan      html  css  js  c++  java
  • 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,英文太差不行啊~~~!!!!!!

  • 相关阅读:
    LeetCode 1032. Stream of Characters
    LeetCode 872. Leaf-Similar Trees
    LeetCode 715. Range Module
    LeetCode 353. Design Snake Game
    LeetCode 509. Fibonacci Number
    LeetCode 632. Smallest Range Covering Elements from K Lists
    LeetCode 963. Minimum Area Rectangle II
    LeetCode 939. Minimum Area Rectangle
    LeetCode 727. Minimum Window Subsequence
    LeetCode 844. Backspace String Compare
  • 原文地址:https://www.cnblogs.com/tangmiao/p/7641101.html
Copyright © 2011-2022 走看看