2

How to send UIImage data to Unity3d via a C# script and iOS plug-in? I need to set this image as a background to a button.

1 Answer 1

4

I flowed the steps that are specified in this link:

http://answers.unity3d.com/questions/129937/ios-nsdata-to-unity-and-loadimage-from-the-data.html

& did it in this way: I have created a plug-in to save the image in directories folder

extern "C"
{
    const char*  _GetImage() 
    {
        NSLog(@"I am in Begin");
        UIImage *myUIImage = [UIImage imageNamed:@"Test.jpg"];
        NSData *imageData = UIImagePNGRepresentation(myUIImage);
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Test.jpg"]; //Add the file name
        NSLog(@"filePath %@",filePath);
        [imageData writeToFile:filePath atomically:YES];
        return MakeStringCopy([filePath UTF8String]);
    }
}

& read the file path through C# script converted it into bytes and gave it to Texture2D.

[DllImport ("__Internal")]    
private static extern String _GetImage();
    public Texture2D texture2D;

    void Start () {
        texture2D = new Texture2D (200, 200);
        imagePath = GetImage();
        byte[] imageBytes = File.ReadAllBytes(imagePath);
        texture2D.LoadImage(imageBytes);
    }

    void OnGUI () {
        GUI.Button (new Rect(20,20,100,100),texture2D);
    }

    public static String GetImage() 
    {
        if (Application.platform != RuntimePlatform.OSXEditor)
        {
            return _GetImage();
        }   
        else
        {
             return @"Hello";
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

I guess, the same can be done backward - send image from unity to iOs app? Is it true?
You are calling UIImagePNGRepresentation but you are naming the file Test.jpg?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.