Advertisement
Guest User

Untitled

a guest
Oct 1st, 2016
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. //
  2. // ColorCubeHelper.swift
  3. //
  4. // Created by Joshua Sullivan on 10/01/16.
  5. // Copyright © 2016 Joshua Sullivan. All rights reserved.
  6. //
  7.  
  8. import UIKit
  9. import Accelerate
  10.  
  11. public final class ColorCubeHelper {
  12.  
  13. public enum ColorCubeError: ErrorType {
  14. case IncorrectImageSize
  15. case MissingImageData
  16. case UnableToCreateDataProvider
  17. }
  18.  
  19. public class func createColorCubeData(inputImage image: UIImage, cubeDimension: Int) throws -> NSData {
  20.  
  21. // Set up some variables for calculating memory size.
  22. let imageSize = image.size
  23. let dim = Int(imageSize.width)
  24. let pixels = dim * dim
  25. let channels = 4
  26.  
  27. // If the number of pixels doesn't match what's needed for the supplied cube dimension, abort.
  28. guard pixels == cubeDimension * cubeDimension * cubeDimension else {
  29. throw ColorCubeError.IncorrectImageSize
  30. }
  31.  
  32. // We don't need a sizeof() because uint_8t is explicitly 1 byte.
  33. let memSize = pixels * channels
  34.  
  35. // Get the UIImage's backing CGImageRef
  36. guard let img = image.CGImage else {
  37. throw ColorCubeError.MissingImageData
  38. }
  39.  
  40. // Get a reference to the CGImage's data provider.
  41. guard let inProvider = CGImageGetDataProvider(img) else {
  42. throw ColorCubeError.UnableToCreateDataProvider
  43. }
  44.  
  45. let inBitmapData = CGDataProviderCopyData(inProvider)
  46. let inBuffer = CFDataGetBytePtr(inBitmapData)
  47.  
  48. // Calculate the size of the float buffer and allocate it.
  49. let floatSize = memSize * sizeof(Float.self)
  50. let finalBuffer = unsafeBitCast(malloc(floatSize), UnsafeMutablePointer<Float>.self)
  51.  
  52. // Convert the uint_8t to float. Note: a uint of 255 will convert to 255.0f.
  53. vDSP_vfltu8(inBuffer, 1, finalBuffer, 1, UInt(memSize))
  54.  
  55. // Divide each float by 255.0 to get the 0-1 range we are looking for.
  56. var divisor = Float(255.0)
  57. vDSP_vsdiv(finalBuffer, 1, &divisor, finalBuffer, 1, UInt(memSize))
  58.  
  59. // Don't copy the bytes, just have the NSData take ownership of the buffer.
  60. let cubeData = NSData(bytesNoCopy: finalBuffer, length: floatSize, freeWhenDone: true)
  61.  
  62. return cubeData
  63.  
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement