从网址加载并显示图像

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从网址加载并显示图像相关的知识,希望对你有一定的参考价值。

我正在尝试将图像从url加载到GameObject。

我找到了下一个教程:

https://www.youtube.com/watch?v=8UK2EsKBzv8

下载成功,但我看不到图像。

我究竟做错了什么?

// Use this for initialization
void Start () {
    StartCoroutine(loadSpriteImageFromUrl("https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/408px-Google_2015_logo.svg.png"));
}

IEnumerator loadSpriteImageFromUrl(string URL)
{
    // Check internet connection
    if (Application.internetReachability == NetworkReachability.NotReachable)
    {
        yield return null;
    }

    var www = new WWW(URL);
    Debug.Log("Download image on progress");
    yield return www;

    if (string.IsNullOrEmpty(www.text))
    {
        Debug.Log("Download failed");
    }
    else
    {
        Debug.Log("Download succes");
        Texture2D texture = new Texture2D(1, 1);
        www.LoadImageIntoTexture(texture);                      
        Sprite sprite = Sprite.Create(texture,
            new Rect(0, 0, texture.width, texture.height),      
            Vector2.one / 2);                                     

        GetComponent<SpriteRenderer>().sprite = sprite;    // Change current sprite
    }
}

Before Running After Running

编辑

按照ScriptRenderer的建议移动到UI Image后,代码如下所示:

IEnumerator loadSpriteImageFromUrl(string URL, GameObject cell)
{
    // Check internet connection
    if(Application.internetReachability == NetworkReachability.NotReachable)
    {
        yield return null;
    }

    var www = new WWW(URL);
    Debug.Log("Download image on progress");
    yield return www;

    if(string.IsNullOrEmpty(www.text))
    {
        Debug.Log("Download failed");
    }
    else
    {
        Debug.Log("Download succes");
        Texture2D texture = new Texture2D(1, 1);
        www.LoadImageIntoTexture(texture);                      
        Sprite sprite = Sprite.Create(texture, 
            new Rect(0,0, texture.width, texture.height),      
            Vector2.one/2);                                    

        cell.AddComponent<Image>();
        cell.GetComponent<Image>().sprite = sprite;    
    }
}

但我得到下一个结果到屏幕(而不是网址中的图像):

enter image description here

答案

你的代码很好。下载的图像未显示,因为您处于场景视图中且相机远离它。

enter image description here

选择脚本附加到的GameObject然后按F.它应放大它,您将看到下载的图像。有关如何重置Unity布局以获取游戏视图的信息,请参阅here

enter image description here



如果你仍然看不到图像,那么SpriteRenderer不在相机前面。从截图,它的位置是000所以确保相机的位置是00-10

正确的显示图像方式:

要在Unity中简单地显示图像,请使用ImageRawImage组件。建议使用RawImage,因为它在更改纹理时不会产生垃圾。你应该已经知道如何解决这个问题了

如果您需要将刚体或2D碰撞器附加到该图像,则使用SpriteRendererMeshRenderer作为3D对象来显示image

这是在Unity中显示图像的四种方法。如果根本不需要物理或碰撞,建议使用#2:

1.与Image组件:

public Image imageToDisplay;
string url = "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/408px-Google_2015_logo.svg.png";

void Start()
{
    StartCoroutine(loadSpriteImageFromUrl(url));
}

IEnumerator loadSpriteImageFromUrl(string URL)
{

    WWW www = new WWW(URL);
    while (!www.isDone)
    {
        Debug.Log("Download image on progress" + www.progress);
        yield return null;
    }

    if (!string.IsNullOrEmpty(www.error))
    {
        Debug.Log("Download failed");
    }
    else
    {
        Debug.Log("Download succes");
        Texture2D texture = new Texture2D(1, 1);
        www.LoadImageIntoTexture(texture);

        Sprite sprite = Sprite.Create(texture,
            new Rect(0, 0, texture.width, texture.height), Vector2.zero);

        imageToDisplay.sprite = sprite;
    }
}

LoadImageIntoTexture过去曾遇到过问题。出于这个原因,我的其他例子将不会使用LoadImageIntoTexture。如果你看到一个问号作为图像,那么使用www.bytesTexture2D.LoadImage函数。

简单地替换:

Texture2D texture = new Texture2D(1, 1);
www.LoadImageIntoTexture(texture);

Texture2D texture = new Texture2D(1, 1);
texture.LoadImage(www.bytes);
texture.Apply();

2.使用RawImage组件(推荐):

public RawImage imageToDisplay;
string url = "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/408px-Google_2015_logo.svg.png";

void Start()
{
    StartCoroutine(loadSpriteImageFromUrl(url));
}

IEnumerator loadSpriteImageFromUrl(string URL)
{

    WWW www = new WWW(URL);
    while (!www.isDone)
    {
        Debug.Log("Download image on progress" + www.progress);
        yield return null;
    }

    if (!string.IsNullOrEmpty(www.error))
    {
        Debug.Log("Download failed");
    }
    else
    {
        Debug.Log("Download succes");
        Texture2D texture = new Texture2D(1, 1);
        texture.LoadImage(www.bytes);
        texture.Apply();


        imageToDisplay.texture = texture;
    }
}

3.与SpriteRenderer组件:

主要用于使用Rigidbody2D和2D Colliders进行2D对象和2D物理模拟。如果没有,则使用上面的UI(#1或#2)。

public SpriteRenderer imageToDisplay;
string url = "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/408px-Google_2015_logo.svg.png";

void Start()
{
    StartCoroutine(loadSpriteImageFromUrl(url));
}

IEnumerator loadSpriteImageFromUrl(string URL)
{

    WWW www = new WWW(URL);
    while (!www.isDone)
    {
        Debug.Log("Download image on progress" + www.progress);
        yield return null;
    }

    if (!string.IsNullOrEmpty(www.error))
    {
        Debug.Log("Download failed");
    }
    else
    {
        Debug.Log("Download succes");
        Texture2D texture = new Texture2D(1, 1);
        www.LoadImageIntoTexture(texture);

        Sprite sprite = Sprite.Create(texture,
            new Rect(0, 0, texture.width, texture.height), Vector2.zero);


        imageToDisplay.sprite = sprite;
    }
}

4.与MeshRenderer组件:

主要用于使用刚体和2D碰撞器的3D物体和3D物理模拟。如果没有,则使用上面的UI(#1或#2)。只需使用飞机,四方或立方体与MeshRenderer

public MeshRenderer imageToDisplay;
string url = "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/408px-Google_2015_logo.svg.png";

void Start()
{
    StartCoroutine(loadSpriteImageFromUrl(url));
}

IEnumerator loadSpriteImageFromUrl(string URL)
{

    WWW www = new WWW(URL);
    while (!www.isDone)
    {
        Debug.Log("Download image on progress" + www.progress);
        yield return null;
    }

    if (!string.IsNullOrEmpty(www.error))
    {
        Debug.Log("Download failed");
    }
    else
    {
        Debug.Log("Download succes");
        Texture2D texture = new Texture2D(1, 1);
        www.LoadImageIntoTexture(texture);

        imageToDisplay.material.mainTexture = texture;
    }
}

新的Unity版本:

WWW API现在似乎已被弃用。现在应该使用UnityWebRequest

public Image imageToUpdate;

void Start()
{
    StartCoroutine(downloadImage());
}

IEnumerator downloadImage()
{
    string url = "http://wallpaper-gallery.net/images/hq-images-wallpapers/hq-images-wallpapers-12.jpg";

    UnityWebRequest www = UnityWebRequest.Get(url);

    DownloadHandler handle = www.downloadHandler;

    //Send Request and wait
    yield return www.SendWebRequest();

    if (www.isHttpError || www.isNetworkError)
    {
        UnityEngine.Debug.Log("Error while Receiving: " + www.error);
    }
    else
    {
        UnityEngine.Debug.Log("Success");

        //Load Image
        Texture2D texture2d = new Texture2D(8, 8);
        Sprite sprite = null;
        if (texture2d.LoadImage(handle.data))
        {
            sprite = Sprite.Create(texture2d, new Rect(0, 0, texture2d.width, texture2d.height), Vector2.zero);
        }
        if (sprite != null)
        {
            imageToUpdate.sprite = sprite;
        }
    }
}

您还可以使用UnityWebRequestTexture.GetTextureDownloadHandlerTexture.GetContent函数来更快地下载,处理和获取图像。

IEnumerator downloadImage()
{
    string url = "http://wallpaper-gallery.net/images/hq-images-wallpapers/hq-images-wallpapers-12.jpg";

    UnityWebRequest www = UnityWebRequestTexture.GetTexture(url);

    DownloadHandler handle = www.downloadHandler;

    //Send Request and wait
    yield return www.SendWebRequest();

    if (www.isHttpError || www.isNetworkError)
    {
        UnityEngine.Debug.Log("Error while Receiving: " + www.error);
    }
    else
    {
        UnityEngine.Debug.Log("Success");

        //Load Image
        Texture2D texture2d = DownloadHandlerTexture.GetContent(www);

        Sprite sprite = null;
        sprite = Sprite.Create(texture2d, new Rect(0, 0, texture2d.width, texture2d.height), Vector2.zero);

        if (sprite != null)
        {
            imageToUpdate.sprite = sprite;
        }
    }
}

以上是关于从网址加载并显示图像的主要内容,如果未能解决你的问题,请参考以下文章

如何从片段中检索gridview中的图像?

如何将图像视图从改造加载的片段传递给子片段?

SwiftUI 无法从下载地址获取图片

如何在片段中从相机捕获图像,

毕加索未能从用bangla写的url加载图像

分享前端开发常用代码片段