【问题标题】:Load and display image from a url从 url 加载和显示图像
【发布时间】:2023-03-31 10:07:01
【问题描述】:

我正在尝试将图像从 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
    }
}

编辑

按照 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;    
    }
}

但我将下一个结果显示在屏幕上(而不是 url 中的图像):

【问题讨论】:

  • 您的hierarchy 中附加的上述脚本在哪里?
  • 资产 --> 脚本 --> LoadImage 。它附加到一个空的游戏对象。为什么?
  • 你的空GameObject 需要有一个SpriteRenderer 组件,否则你的脚本将永远无法工作
  • @Hristo 我已经有了 SpriteRenderer。
  • @Programmer 我已经有了 SpriteRenderer。我想显示来自网络的图像网格。

标签: c# image url unity3d


【解决方案1】:

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

选择脚本附加到的游戏对象,然后按F。它应该放大它,您将看到下载的图像。请参阅here,了解如何重置 Unity 布局以恢复游戏视图。



如果您仍然看不到图像,则SpriteRenderer 不在摄像头前面。从截图来看,它的位置是0,0,0,所以请确保相机的位置是0,0,-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 组件:

主要用于 2D 对象和带有 Rigidbody2D2D Colliders 的 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 组件:

主要用于 3D 对象和带有 Rigidbody2D Colliders 的 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;
        }
    }
}

【讨论】:

  • 再次感谢您的详细解答。我尝试了#1 和#2,不幸的是我仍然得到一个带有红色? 标记的白色方块
  • 你的 Unity 版本是多少?您可以压缩并发送给我一个不起作用的简单项目吗?我会看看它。顺便问一下,你原来的 SpriteRenderer 问题解决了吗?我只是想知道....
  • 5.6.0f3.我可以把它寄到这里吗?在 #2 解决方案中,我不需要 SpriteRenderer,我只使用没有它的 RawImage 对象。
  • 现在来看看。从我的电脑里出来了
  • 老兄,代码工作正常。我不知道你是不是在拖钓我。如果您正确复制代码,您将不会遇到此问题。您使用i.stack.imgur.com/Cu4SA.png 作为网址,i.stack.imgur.com/Cu4SA.png 有一张带问号的图片.....它得到了准确的图片。这就是问题
猜你喜欢
  • 1970-01-01
  • 2013-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-26
  • 1970-01-01
  • 2021-09-07
相关资源
最近更新 更多