使用HttpWebRequest下载后,PNG文件显示为红色问号 [英] PNG file displayed as red question mark after download with HttpWebRequest

查看:157
本文介绍了使用HttpWebRequest下载后,PNG文件显示为红色问号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下问题:我从Google驱动器下载了一个png文件,所有字节都被成功接收(看上去),但是当我尝试构造一个Texture2D并将其设置为Sprite时,它在,只有红色的问号出现.

I face the following issue: I downloading a png file from google drive, all bytes are successfully received (as it seems), but when I try to construct a Texture2D and set it as Sprite in an Image, only red a question mark appears.

我想念什么吗?

以下代码:

HttpWebRequest request = (HttpWebRequest) WebRequest.Create("https://content.googleapis.com/drive/v3/files/" + fileId + "?alt=media");
request.Method = "GET";
request.ContentType = "image/png";
request.Headers.Add("Authorization", "Bearer " + AUTH_TOKEN);

WebResponse response = request.GetResponse();
byte[] bytes = new byte[response.ContentLength];
response.GetResponseStream().Read(bytes, 0, (int) response.ContentLength);
response.Close();

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

推荐答案

我对您的确切代码和此

I did a quick test with your exact code and this image and go this:

问题是您下载所有图像字节.这不是用HttpWebRequest下载所有图像字节的方法.在while循环中使用MemoryStreamStream.Read.如果没有其他要读取的内容,则Stream.Read将返回0.

The problem is that you are not downloading all the image bytes. This is not how to download all the image bytes with HttpWebRequest. Use MemoryStream and Stream.Read in a while loop. If there is nothing else to read, Stream.Read will return 0.

查看downloadFullData函数以了解如何正确执行此操作:

Look at the downloadFullData function for how to do this properly:

public Image imageToUpdate;

void Start()
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://wallpaper-gallery.net/images/hq-images-wallpapers/hq-images-wallpapers-12.jpg");
    request.Method = "GET";
    //request.ContentType = "image/png";
    //request.Headers.Add("Authorization", "Bearer " + AUTH_TOKEN);

    WebResponse response = request.GetResponse();

    if (response == null)
    {
        return;
    }

    //Download All the bytes
    byte[] bytes = downloadFullData(request);

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

byte[] downloadFullData(HttpWebRequest request)
{
    using (WebResponse response = request.GetResponse())
    {

        if (response == null)
        {
            return null;
        }

        using (Stream input = response.GetResponseStream())
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while (input.CanRead && (read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }
    }
}

结果:

这应该可以,但是不要使用HttpWebRequest,因为它会阻塞您的程序,直到下载图像为止.如果要使用它,则必须在另一个Thread中使用它.从这里开始,这变得非常复杂,因为您不能在另一个Thread中使用Unity的API,而必须使用

This should work but don't use HttpWebRequest because it will block your program until image is downloaded. If you want to use it then you must use it in another Thread. This gets really complicated from here because you can't use Unity's API in another Thread and would have to use something like this to call Unity's API( texture2d.LoadImage(bytes) ) in another Thread.

使用Unity的 WWW

Use Unity's WWW or UnityWebRequest API for this. The example below will accomplish the-same exact thing with UnityWebRequest.

public Image imageToUpdate;

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

IEnumerator downloadImage()
{
    string authorization = authenticate("YourUserName", "YourPass");

    string url = "http://wallpaper-gallery.net/images/hq-images-wallpapers/hq-images-wallpapers-12.jpg";

    UnityWebRequest www = UnityWebRequest.Get(url);
    //www.SetRequestHeader("AUTHORIZATION", authorization);

    DownloadHandler handle = www.downloadHandler;

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

    if (www.isError)
    {

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

string authenticate(string username, string password)
{
    string auth = username + ":" + password;
    auth = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(auth));
    auth = "Basic " + auth;
    return auth;
}

这篇关于使用HttpWebRequest下载后,PNG文件显示为红色问号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆