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

Nevin Brackett-Rozinsky nevin.brackettrozinsky at gmail.com
Wed Mar 15 13:07:42 CDT 2017


Right, I understand conceptually what needs to happen. It is the actual
implementation where I’m getting stuck.

Ideally I’d like to create the bitmap image without having to allocate a
second buffer. The sole purpose of the Float array is for creating this
image, so I’d like to directly use its bytes as the pixels data. I expect
this will involve some Unsafe[…] APIs in Swift, though I don’t know exactly
how.

And yes, I am on an Apple platform. Despite reading boatloads of Core
Graphics documentation, I still can’t make heads or tails out of how to
turn a pre-existing array into the backing data for a bitmap image. This
part is only Swift-related in the sense that I am trying to do it in Swift,
so if there’s a better place to ask/learn about it I’d appreciate being
pointed there.

Thanks again,
Nevin


On Wed, Mar 15, 2017 at 1:44 PM, Jens Alfke <jens at mooseyard.com> wrote:

>
> On Mar 15, 2017, at 9:56 AM, Nevin Brackett-Rozinsky via swift-users <
> swift-users at swift.org> wrote:
>
> For one of my programs, I need to take an array of Floats and use the
> underlying bytes as the RGBA data for a bitmap image. In particular, the 32
> bits of each Float must be treated as the color of the corresponding pixel.
> So the result is an image of height 1 and width the length of the array.
>
>
> Make a pixmap, an array of UInt8 that’s 4x longer than your original
> array, where the elements are interpreted as R, G, B, A, R, G, B, A… Then
> fill it in based on the original float values.
>
> In particular, I need to be able to save the image as a PNG file, then
> later load it from disk and reconstruct each Float from its pixel, with no
> loss or change to the value of the Floats. So, how do I go from [Float] to
> a bitmap image suitable for saving to disk, without altering the underlying
> bytes?
>
>
> You’ll need to call some external image-encoding library, passing it your
> pixmap. If you’re on an Apple platform try ImageIO. If not, or if you want
> to be cross-platform, try libpng.
>
> —Jens
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170315/58c1d4a3/attachment.html>


More information about the swift-users mailing list