4

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...

Robin Heggelund Hansen
  • 4,906
  • 6
  • 37
  • 54
  • 1
    Please edit your question and paste the code you’ve tried. In general, what you’ve described is correct. –  Apr 13 '11 at 06:46

2 Answers2

3

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.

Richard
  • 3,316
  • 30
  • 41
  • 1
    @Robin also note that, if the byte array is guaranteed not to go away, you can optimize the NSData by using one of the `NSData` `...WithBytesNoCopy:` methods. -- and here it's probably ok even if the `byteArray` will not persist, since the `NSImage` presumably copies the data out of the `NSData` anyway. – Richard Apr 14 '11 at 15:47
3

You can use an NSMutableData, like this:

new NSImage (new NSMutableData (imageAsBytes));
mkestner
  • 246
  • 1
  • 4
  • Conceptually, that's the same thing I posted, but what language are you using where that is valid and meaningful syntax? – Richard Apr 17 '11 at 13:00
  • The question was tagged monomac and cocoa, which is the mono binding for cocoa/mac development. The source syntax is C#. – mkestner May 03 '11 at 14:17
  • 1
    will the `new NSMutableData(imageAsBytes)` copy the bytes or use them in-place? – Richard May 03 '11 at 15:46