【问题标题】:CIImage creation with initWithTexture使用 initWithTexture 创建 CIImage
【发布时间】:2015-11-14 04:38:54
【问题描述】:

我正在尝试在 iOS 9.0 下使用 CIImage initWithTexture 读取纹理数据,但我得到的只是一张黑色图像。我什至尝试过先加载纹理,然后再读取它,但仍然是黑色图像。

这是我的代码:

    CGImageRef brushImage;
    CGContextRef brushContext;
    GLubyte *brushData;
    size_t width, height;
    GLUint texId;
    CIImage *cimage;

    //
    // Here I'm just loading an image and preparing it as a bitmap.
    //
    brushImage = [UIImage imageNamed:"brush"].CGImage;
    width = CGImageGetWidth(brushImage);
    height = CGImageGetHeight(brushImage);
    brushData = (GLubyte *) calloc(width * height * 4, sizeof(GLubyte));
    brushContext = CGBitmapContextCreate(brushData, width, height, 8, width * 4, CGImageGetColorSpace(brushImage), kCGImageAlphaPremultipliedLast);
    CGContextDrawImage(brushContext, CGRectMake(0.0, 0.0, (CGFloat)width, (CGFloat)height), brushImage);


    //
    // Here I create the texture I want to use.
    // 
    glGenTextures(1, &texId);
    glBindTexture(GL_TEXTURE_2D, texId);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    //
    // Load in my bitmap to the texture.
    //
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (int)width, (int)height, 0, GL_RGBA, GL_UNSIGNED_BYTE, brushData);

    //
    // Now, try to read the texture back out.
    //
    cimage = [[CIImage alloc] initWithTexture:texId size:CGSizeMake(width, height) flipped:YES colorSpace:CGImageGetColorSpace(brushImage)];

    return [[UIImage alloc] initWithCIImage: cimage];

返回的 UIImage 似乎具有正确的大小——但图像似乎是空白的(全黑),尽管源图像(PNG)肯定有一些内容。不知道我做错了什么。请问有什么帮助吗?谢谢!!

【问题讨论】:

    标签: ios objective-c opengl-es-2.0 gpu core-image


    【解决方案1】:

    我可以通过使用 GLKit 中的 GLKTextureLoader 来完成这项工作,我创建了以下方法来从图像创建纹理支持的 CIImage:

    - (CIImage *)createImageFromPath:(NSString *)filePath{
         NSError *error;
         GLKTextureInfo *texture = [GLKTextureLoader textureWithContentsOfFile:filePath options:@{GLKTextureLoaderApplyPremultiplication : @YES} error:&error];
         glBindTexture(texture.target, texture.name);
    
         return [CIImage imageWithTexture:texture.name size:CGSizeMake(texture.width, texture.height) flipped:YES colorSpace:nil];
    }
    

    为了使它工作,您需要确保在调用此函数之前需要设置 EAGLContext。您还需要基于相同的 EAGLContext 创建一个 CIContext 来渲染 CIImage

    EAGLContext *eaglContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    CIContext *ciContext = [CIContext contextWithEAGLContext:eaglContext options:@{kCIContextWorkingColorSpace : [NSNull null]}];
    [EAGLContext setCurrentContext:eaglContext];
    
    CIImage *image = [self createImageFromPath:[[NSBundle mainBundle] pathForResource:@"brush" ofType:@"png"]];
    

    然后您可以将过滤器应用到此 CIImage 并使用 ciContext 渲染图像。

    【讨论】:

      猜你喜欢
      • 2012-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-14
      • 1970-01-01
      • 2021-05-30
      • 2018-05-29
      • 2012-04-16
      相关资源
      最近更新 更多