unity.webp
unity.webp copied to clipboard
Unable to load webp from URL
I apologize if this is known, but I am not sure how to move forward from here. I know that this is under the .wip example, but I am hoping that maybe I am just missing a simple thing.
In the example3 script and scene, uncommenting the load by url and putting in an actual URL with a webp image does not seem to work. The raw image just remains a white square.
I've also tried specifically pulling the file as bytes using a web request and running that into the LoadAnimation function from example2, but that did not seem to work either (it was a long shot anyways).
Hi, I was solving the same problem. For one the code to load request is not working in the source but even when I fixed that it also gave me just blank image. So instead I have used the native functions. Please note I also opted for newer async .NET request that supports HTTP 2.0 instead of UnityWebRequest which is meh.
Solution below:
using System.Net.Http; //experimental alternative to UnityWebRequest
using WebP; //this plugin namespace
.....
public async Task<Texture2D> LoadWebP(string source){
byte[] bytes = await GetBytesAsync(source);
if (bytes == null){
Debug.LogWarning("Failed to download WebP image");
return null;
}
Texture2D texture = Texture2DExt.CreateTexture2DFromWebP(bytes, lMipmaps: true, lLinear: false, lError: out Error lError);
return texture;
}
//-------------------------------------------------
//native .NET async web request instead of unity web request
public async Task<byte[]> GetBytesAsync(string url){
try{
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url))
{
HttpClientHandler handler = new HttpClientHandler();
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = await client.SendAsync(request);
Debug.Log($"Response Status: {response.StatusCode}");
response.EnsureSuccessStatusCode(); // Ensure successful response
byte[] byteResponse = await response.Content.ReadAsByteArrayAsync();
return byteResponse;
}
}
catch (Exception ex)
{
Debug.LogWarning($"Request failed: {ex.Message}");
return null;
}
}