Guest User

Untitled

a guest
Jul 18th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. func savePixels(x: Int, y: Int, w: Int, h: Int) -> UIImage {
  2. let bitsPerComponent:Int = 8
  3. let bitsPerPixel:Int = 32
  4. let byteLength = Int(w * h) * 4;
  5.  
  6. let bytes = UnsafeMutablePointer<GLubyte>.allocate(capacity: byteLength)
  7. bytes.initialize(to: GLubyte())
  8.  
  9. glReadPixels(0, 0, GLsizei(w), GLsizei(h), GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), bytes)
  10.  
  11. for i in 0 ..< Int(w * h) {
  12. let r = bytes[4 * i + 0]
  13. let g = bytes[4 * i + 1]
  14. let b = bytes[4 * i + 2]
  15. let a = bytes[4 * i + 3]
  16.  
  17. bytes[4 * i ] = b
  18. bytes[4 * i + 1] = g
  19. bytes[4 * i + 2] = r
  20. bytes[4 * i + 3] = a
  21. }
  22.  
  23. let dataProvider = CGDataProvider(dataInfo: nil, data: bytes, size: byteLength, releaseData: { (info, data, size) -> Void in
  24. //data.deallocate(bytes: size, alignedTo: MemoryLayout<GLubyte>.alignment)
  25. })
  26.  
  27. let colorspace = CGColorSpaceCreateDeviceRGB()
  28. let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.first.rawValue)
  29. let aCGImage = CGImage(
  30. width: Int(w),
  31. height: Int(h),
  32. bitsPerComponent: bitsPerComponent,
  33. bitsPerPixel: bitsPerPixel,
  34. bytesPerRow: Int(w) * 4,
  35. space: colorspace,
  36. bitmapInfo: bitmapInfo,
  37. provider: dataProvider!,
  38. decode: nil,
  39. shouldInterpolate: false,
  40. intent: .defaultIntent
  41. )!
  42.  
  43. return UIImage.init(cgImage: aCGImage, scale: 1, orientation: .up)
  44. }
Add Comment
Please, Sign In to add comment