- Home /
Loading some images doesn't work
I'm working on a Tool, for which users can load in images locally from their computer. However, some images appear to be converted in such a way, that Unity can't load them into the game. I'm using WWW for loading Images locally, though I've also tried using UnityWebRequest and File.ReadAllBytes and all of them resulted in loading the white picture with a red questionmark (error-texture). The picture in question was exported/created with AffinityPhoto as jpg. Also: Most images seem to work (at least for me)
if (!string.IsNullOrEmpty(path))
{
WWW www = new WWW(path);
currentlyLoadedSprite = Sprite.Create(www.texture, new Rect(0, 0, www.texture.width, www.texture.height), Vector2.one * 0.5f);
SetImagesToCurrentSprite();
}
Answer by Link17x · Mar 15, 2020 at 12:26 PM
I think WWW is depreciated, and you should use UnityWebRequest. But I'm not sure if you need UnityWebRequest if you're only getting images locally? You could use the UnityWebRequest to fetch images from online using a URL. If you decide to use this,
// Use IEnumerator so you can yield
// which waits till you have the image before proceeding
private void IEnumerator()
{
use var getImage = UnityWebRequest.Get(your URL);
yield return getImage.SendWebRequest();
// Do something with your image (this is in bytes)
}
private void SetImages(List<byte[]> images)
{
for (var i = 0; i < images.Count; i++)
{
// Texture size doesn't matter, it will be changed by the loaded image anyway
var texture = new Texture2D(1, 1);
texture.LoadImage(images[i]);
var img = Instantiate(imagePrefab, pos, Quaternion.identity, transform);
img.GetComponent<Renderer>().material.mainTexture = texture;
}
}
I don't really know what you want to do with your image, this is an example if you were to use the image on a game object and I think you need to use RawImage component on a quad or something if you decide to do that. Just bear in mind the image should be loaded in bytes, and you might need to create some texture using those bytes, rather than simply loading an image in and setting it.