0

我正在尝试将 base64 字符串转换为 Unity 3D 中的 Sprite,但我在场景中的精灵仍然空白。

public var cardPicture : Image;

function ReceiveData(jsonReply : JSONObject) {
    var pictureBytes : byte[] = System.Convert.FromBase64String(jsonReply.GetString("picture"));
    var cardPictureTexture = new Texture2D( 720, 720);
    Debug.Log(cardPictureTexture.LoadImage(pictureBytes));
    var sprite : Sprite = new Sprite ();
    sprite = Sprite.Create (cardPictureTexture, new Rect (0,0,720,720), new Vector2 (0.5f, 0.5f));
    cardPicture.overrideSprite = sprite;
}

这打印出来是真的,但我不确定它是否从字节中正确加载图像或者是否有其他问题。我也不确定要检查什么以确定出了什么问题。将一些图片分配给场景中的 cardPicture 正确显示。

我记录了 jsonReply.picture 并使用了在线 base64 到图像转换器,它正确显示了图像。

4

3 回答 3

0
 byte[] pictureBytes = System.Convert.FromBase64String(jsonReply.GetString("picture"));

 Texture2D tex = new Texture2D(2, 2);
 tex.LoadImage( imageBytes );

 Sprite sprite = Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), new Vector2(0.5f, 0.5f), 100.0f);

 cardPicture.overrideSprite = sprite;
于 2019-11-16T11:01:56.440 回答
0

我假设您正在尝试从远程 url 获取图像并尝试将字节解析为纹理。In unityWWW促进了这一点,并且不需要用户参与转换。

我相信您的回复可能包含标题详细信息,这可能会导致转换为纹理时出现问题。您可以使用如下代码,

public string Url = @"http://dummyimage.com/300/09f/fff.png";

    void Start () {
        // Starting a coroutine to avoid blocking
        StartCoroutine ("LoadImage");
    }

    IEnumerator LoadImage()
    {
        WWW www = new WWW(Url);
        yield return www;

        Debug.Log ("Loaded");
        Texture texture = www.texture;
        this.gameObject.GetComponent<Renderer>().material.SetTexture( 0,texture );
    }
于 2015-08-15T13:35:11.207 回答
0

我不知道这是否解决了,但我想分享我的解决方案。

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

IEnumerator GetQR()
{
    using (UnityWebRequest www = UnityWebRequest.Get(GetQR_URL))
    {
        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            // Show results as text
            Debug.Log(www.downloadHandler.text);
            
            QRData qr = JsonUtility.FromJson<QRData>(www.downloadHandler.text);

            string result = Regex.Replace(qr.img, @"^data:image\/[a-zA-Z]+;base64,", string.Empty);

            CovertBase64ToImage(result);
        }
    }
}

void CovertBase64ToImage(string img)
{
    byte[] bytes = Convert.FromBase64String(img);
    Texture2D myTexture = new Texture2D(512,212);
    myTexture.LoadImage(bytes);
   
    Sprite sprite = Sprite.Create(myTexture, new Rect(0, 0, myTexture.width, myTexture.height), new Vector2(0.5f, 0.5f));
    QRimage.transform.parent.gameObject.SetActive(true);
    QRimage.sprite = sprite;
}

它在统一版本 2019.4 上运行良好

于 2021-01-28T10:36:44.910 回答