(resent to the list) On Nov 14, 2017, at 18:36 , Rick Mann <rm...@latencyzero.com <mailto:rm...@latencyzero.com>> wrote: > > Is there a way to get at the underlying raw image data for a given UIImage > (in an immutable buffer) in Swift? > > Does this end up making copies? (For bonus points, what's the array magic?) > > let img: UIImage = UIImage(named: "MyImage") > let data: CFData? = img.CGImage.dataProvider.data > let dataArray: [UInt8] = <some Swift magic to see this as [UInt8]>
There are some simple answers, but the correct answer is “it depends”. For example, you can do this: > var data = Data ([1,2,3,4]) > print (data [3]) In other words, seeing a Data instance as an array of bytes is simple. Or, if you want to do something more like the old days in Obj-C, you can do this: > data.withUnsafeBytes { > (bytes: UnsafePointer<UInt8>) in > print (bytes [3]) > } which (in some sense) gives you a raw-ish pointer to the underlying data, inside the closure. (The latter, which a different generic specialization type, is also what you’d use if you wanted to access pairs of bytes as UInt16 values, etc.) Back to original problem, the following code in a playground works: > let img = UIImage(named: "Image”)! // I used a PNG image so the data is simple > let data = img.cgImage!.dataProvider!.data! as Data > print (data [0], data [1], data [2], data [3]) The last part of this is (a) whether you can always get the raw data as bytes, (b) what those bytes represent, and (c) does this kind of approach make a copy? The answer is “I don’t know”, because it’s going to depend on the format of the image and the particular data provider. AFAIK, both the array treatment and the UnsafePointer treatment require a continuous underlying buffer, so if the data provide build the data using multiple partial buffers, I suppose there has to be a copy to meet the API semantics. You could also iterate through a Data object using a for loop (and general collection/sequence methods as required). Since that would access only 1 byte at a time, I’d expect there’s no copy involved, but who knows what the performance might be in general. Does any of that help? _______________________________________________ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com