-1

I trying take screenshot of camera vuforia. I using this code. Its perfect working on iPhone 7 (ios 11.3) and iPad Pro (ios 11.2). But this code not working on iPad 2 (ios 9.3.5), function returning valid UIImage, but it black.

    static public func takeScreenshot() -> UIImage? {
    let xCoord: Int = 0
    let yCoord: Int = 0
    let screen = UIScreen.main.bounds

    let scale = UIScreen.main.scale
    let width = screen.width * scale
    let height = screen.height * scale
    let dataLength: Int = Int(width) * Int(height) * 4
    let pixels: UnsafeMutableRawPointer? = malloc(dataLength * MemoryLayout<GLubyte>.size)
    glPixelStorei(GLenum(GL_PACK_ALIGNMENT), 4)
    glReadPixels(GLint(xCoord), GLint(yCoord), GLsizei(width), GLsizei(height), GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), pixels)
    guard let pixelData: UnsafePointer = (UnsafeRawPointer(pixels)?.assumingMemoryBound(to: UInt8.self)) else { return nil }
    let cfdata: CFData = CFDataCreate(kCFAllocatorDefault, pixelData, dataLength * MemoryLayout<GLubyte>.size)

    let provider: CGDataProvider! = CGDataProvider(data: cfdata)
    let colorspace = CGColorSpaceCreateDeviceRGB()
    guard let iref = CGImage(width: Int(width),
                                 height: Int(height),
                                 bitsPerComponent: 8,
                                 bitsPerPixel: 32,
                                 bytesPerRow: Int(width)*4,
                                 space: colorspace,
                                 bitmapInfo: CGBitmapInfo.byteOrder32Big,
                                 provider: provider,
                                 decode: nil,
                                 shouldInterpolate: false,
                                 intent: CGColorRenderingIntent.defaultIntent) else { return nil }
    UIGraphicsBeginImageContext(CGSize(width: CGFloat(width), height: CGFloat(height)))
    if let cgcontext = UIGraphicsGetCurrentContext() {
        cgcontext.setBlendMode(CGBlendMode.copy)
        cgcontext.draw(iref, in: CGRect(x: CGFloat(0.0), y: CGFloat(0.0), width: CGFloat(width), height: CGFloat(height)))
        let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
    return nil
}

UPDATE: i resolved this problem, need run function in opengl thread

1 Answers1

0

OpenGL ES has very limited formats that are accepted. There is an excellent website with OpenGL documentations http://docs.gl

You are interested in http://docs.gl/es2/glReadPixels or http://docs.gl/es3/glReadPixels. Buffer format should be GL_RGBA or GL_BGRA.

Maybe better approach would be https://stackoverflow.com/a/9704392/1351828.

DHEERAJ
  • 1,478
  • 12
  • 32