Search code examples
cocoamonomac

NSImage from byte array


I'm trying to display an image in a NSImageView, with an image contained in a Byte array. How can I do this? From what I understand I need to convert my byte[] to an NSData variable and feed that to an NSImage. Is this correct? How do I do it? I've tried casting and that doesn't work, and there doesn't seem to be any conversion built in...

I have tried the following:

Casting:

NSData bytesAsMacVariable = (NSData) imageAsBytes;

Also tried

NSData bytesAsMacVariable = imageAsBytes as NSData;

Finally, tried to pass a byte[] as if it was a NSData.

NSImage imageToShow = new NSImage(imageAsBytes);

None of these will work, and as far as I can see, neither NSImage or NSData has a member function that accepts byte[] for conversion...


Solution

  • You're casting to the object type, but you should cast to pointer-to-object type.
    Try something more like

    NSData *imageData = [NSData dataWithBytes:byteArray length:arrayLength];
    NSImage *image = [[NSImage alloc] initWithData:imageData];
    [imageView setImage:image];
    [image release];
    

    The pointers are very important.