- Home /
iOS NSData to Unity, and LoadImage from the data
I have already get a NSData instance of an UIImage like this:
UIImage *myImage = [UIImage imageNamed:@"pic.png"];
NSData *imageData = UIImagePNGRepresentation(myImage);
Now I want to send the data to Unity and get the image.
Is there a possible solution to send "imageData" to Unity and use the function: Texture2D.LoadImage to get this image? I wonder whether the method "UnitySendMessage" in XCode can send this imageData to Unity?
Or is there any way to send an image from XCode's UIImage to Unity?
Thanks for any idea.
Answer by Peter G · Jun 14, 2011 at 04:18 PM
I did something similar in an app I made where I let the user choose there own image for the players texture. So let me direct you to some helpful sources.
take the
NSData
object that you have and save it. Your app has permission to write data to your game's "Documents" folder. (According to the developer docs) The proper way of getting the documents path from XCode is to do the following:NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; then append on your specific file name such "/MyImage.png". So you have the file directory and the data so save it (theres a method in `NSData` for writing to files), and you're ready for the next step.
In Unity, then you can read that file and load the image. For reading files, see @SpinalJack's explanation here. Load the byte array using
System.IO
into Unity.Then the final step is the easiest. Use Texture2D.LoadImage() to load the image data into a texture.
EDIT: Just remembered, you can use the WWW
to load the bytes as well. Probably isn't any faster than System.IO, but its easier. Just add file:
to the beginning of the asset path in Unity.
Thanks a lot for the answer. A good way to solve my issue. Saving the image to "Document" direction and then loading it from disk is a way. But I think it may be a little expensive to perform IO operations to/from disk, especially when I want load a lot of images.
If there is a way to just passing the bytes of image from XCode to Unity, it will be perfect.
Thank you again, and if there is no better solution, I will just follow you to perform IO.
In one of my projects, I used the WWW object to load textures, but, the problem is,every time you use the WWW.LoadTexture(), a new texture is created, and you run into memory issues. So, I guess, System.IO.ReadAllBytes(pathname) is more efficient.
Your answer
Follow this Question
Related Questions
Is it possible to split Texture2D.LoadImage into multiple parts? 1 Answer
Texture2D.LoadImage black pixel border 0 Answers
Fatal Exception when loading multiple image files on Android from persistent data path 0 Answers
Detecting Texture2D.LoadImage failure 2 Answers
loadImage texture crash on android 0 Answers