NSImage from byte array

眉间皱痕 提交于 2019-12-10 17:48:14

问题


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


回答1:


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.




回答2:


You can use an NSMutableData, like this:

new NSImage (new NSMutableData (imageAsBytes));


来源:https://stackoverflow.com/questions/5645157/nsimage-from-byte-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!