[swift-users] How do I turn an array into a bitmap image?

Brent Royal-Gordon brent at architechies.com
Wed Mar 15 15:04:36 CDT 2017


Without touching the broader question of bitmap formats:

> On Mar 15, 2017, at 12:01 PM, Nevin Brackett-Rozinsky via swift-users <swift-users at swift.org> wrote:
> 
> Also, for my specific application, I need to take an array of floating point numbers and say, “Hey, the underlying bits that make up the IEEE-754 representation of these numbers are exactly the bits that I want to use for the colors of the pixels.” I do not know how to do that in Swift.
> 
> In C I would malloc a buffer, write to it as (float*), then pass it to a function which takes (char*) and saves a PNG. Thus there is only one allocation, the buffer is filled with float values, and the exact bit-pattern is interpreted as RGBA pixels.
> 
> How can I do the equivalent in Swift?

Create and fill an Array<Float> (actually, a ContiguousArray<Float> would be a little better for this use) with your data. Then use `withUnsafeBytes` to access the raw bytes as an `UnsafeRawBufferPointer`, a type which behaves sort of like a fixed-size array of `UInt8`.

You could access the bytes one at at time by looping (or indexing, or doing many other things):

	myFloats.withUnsafeBytes { buffer in
		for byte in buffer {
			putchar(byte)
		}
	}

Or you can pull out the start pointer and count and use them:

	myFloats.withUnsafeBytes { buffer in
		guard write(fd, buffer.baseAddress, buffer.count) != -1 else { throw MyError.IOError(errno) }
	}
		
Or you can copy it into a `Data` or `Array` and return it to the outer context:

	let bytes = myFloats.withUnsafeBytes { buffer in
		return Data(buffer: buffer) 	// or Array(buffer)
	}

One thing you should *not* do is hold on to `buffer` or its `baseAddress` beyond the closing bracket. Once `withUnsafeBytes` returns, the `Array` or `ContiguousArray` is free to move or delete its data, so you can no longer depend on the pointer to be correct. Copy the data to an `Array` or `Data`, or allocate and copy it to your own `UnsafeRawBufferPointer`, if you want to hold on to it longer.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-users mailing list