2
\$\begingroup\$

I am working on a Unity project where I need to be able to grab an image from disk and then have it be replaced as the source image for an image gameobject. Currently I already have a filebrowser implemented that gives me the filepath.

if (File.Exists(output)){
    GameOjbect imageselect = GameObject.Find("ImageSelection");
    imageselect.GetComponent<Image>();
    //I need to make the file location at path output be the sprite?/sourceimage? for imageselect
}

Sorry if this has already been asked, I have been looking at other examples this morning with no luck.

\$\endgroup\$
0
\$\begingroup\$

You can use Texture2D.LoadImage to load your image into a Texture2D, assuming it's a PNG or JPG image.

The method takes in a byte[], so you'll have to use File.ReadAllBytes(output).

Something like this:

if (File.Exists(output))
{
    var fileBytes = File.ReadAllBytes(output);
    var texture2D = new Texture2D(2, 2);

    if (texture2D.LoadImage(fileBytes))
    {
        _image.sprite = Sprite.Create(texture2D,
                                      new Rect(0, 0, texture2D.width, texture2D.height),
                                      new Vector2(0.5f, 0.5f));
    }
    else
    {
        Debug.LogError("Error when loading file as Texture2D!");
    }
}

should work just fine.

The Texture2D.LoadImage() method will automatically resize the 2x2 texture2D object depending on the file loaded.

There's also an optional fourth parameter for Sprite.Create() that takes in a float pixelsPerUnit.

\$\endgroup\$
  • \$\begingroup\$ You can also use the WWW class to asynchronously load an image from a local or network location. You can then access the image as a Texture2D by reading the .texture property of your www object. \$\endgroup\$ – DMGregory Dec 14 '16 at 16:26
  • \$\begingroup\$ Is it also possible to replace a source image that is used by a unity gameobject this way? I want to replace the slice that is used in a sprite renderer and in an animation clip by setting a different source image. \$\endgroup\$ – Kokodoko Feb 18 '18 at 11:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.