Loading a sprite from URL C#
I'm trying to load an image from an URL, but none of the answers i found online apply to my problem. There is a good example in the unity docs, but it's javascript:
http://docs.unity3d.com/ScriptReference/WWW.LoadImageIntoTexture.html
I than need to load this sprite onto UI image element.
Please help,
Thanks
Answer by blazeaster · Apr 25, 2016 at 05:26 PM
Solved thanks to the The Little Guy from unity forums!
public class ExampleClass : MonoBehaviour {
// The output of the image
public Image img;
// The source image
public string url = "http://images.earthcam.com/ec_metros/ourcams/fridays.jpg";
IEnumerator Start() {
WWW www = new WWW(url);
yield return www;
img.sprite = Sprite.Create(www.texture, new Rect(0, 0, www.texture.width, www.texture.height), new Vector2(0, 0));
}
}
Great answer. I did not know until now that Start (and other event handlers) can be made return IEnumerator and will be run as coroutines. Thats awesome!!
can be Resources.Load with URL? because I have a lot of pictures
Answer by idbrii · Oct 31, 2018 at 11:29 PM
Instead of Sprite.Create, you may want to use WWW.LoadImageIntoTexture to ensure your image isn't downsampled by QualitySettings (the difference is very noticeable at "Eighth Res").
www.LoadImageIntoTexture(img.mainTexture as Texture2D);
Answer by creativeConny · Oct 26, 2017 at 12:45 PM
I wonder if there is any option to auto scale the aspect ratio of the downloaded image? In my case there is a placeholder with 800x600 pixels. So I want to keep the downloaded image's aspect ratio but cap its size to 800x600? Right now unity tries to fill my placeholder to its max...
EDIT: Ok found the solution by my self: At first I had not any source file in my image object. This caused the "preserve aspect ratio" button to not appear. After I inserted a placeholder image (before uploading one) the button appeared. Then just simply turn it on, now every time you upload a new image from url it keeps its aspect ratio! :)