// --------------------------------------------------------------------------------------------------------------------
//
// Copyright (c) VRMADA, All rights reserved.
//
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using UltimateXR.Extensions.System;
using UltimateXR.Extensions.System.IO;
using UnityEngine;
namespace UltimateXR.Extensions.Unity.Render
{
///
/// extensions.
///
public static class Texture2DExt
{
#region Public Methods
///
/// Creates a texture with a flat color.
///
/// Width in pixels
/// Height in pixels
/// Color to fill the texture with
/// The created object
public static Texture2D Create(int width, int height, Color32 color)
{
Texture2D tex = new Texture2D(width, height);
Color32[] pixels = new Color32[width * height];
for (int i = 0; i < pixels.Length; ++i)
{
pixels[i] = color;
}
tex.SetPixels32(pixels);
tex.Apply();
return tex;
}
///
/// Loads asynchronously a texture from a given file . See for
/// information on the file location.
///
/// Location of the texture file. See
/// Optional cancellation token, to cancel the operation.
/// An awaitable that returns the loaded texture
/// is null or empty
/// Task canceled using
/// The file specified in was not found.
/// is in an invalid format.
/// An I/O error occurred while opening the file.
/// The stream is currently in use by a previous read operation.
public static async Task FromFile(string uri, CancellationToken ct = default)
{
byte[] bytes = await FileExt.Read(uri, ct);
return FromBytes(bytes);
}
///
/// Loads asynchronously a texture from a file encoded in a base64 .
///
/// The base 64 image string
/// Optional cancellation token, to cancel the operation
/// is null or empty
/// Task canceled using
///
/// The length of , ignoring white-space characters, is not
/// zero or a multiple of 4.
///
/// An awaitable that returns the loaded texture, or null if it could not be loaded
public static async Task FromBase64(string base64, CancellationToken ct = default)
{
base64.ThrowIfNullOrWhitespace(nameof(base64));
// Screenshot is from a file embedded in a string in base64 format
byte[] bytes = await Task.Run(() => Convert.FromBase64String(base64), ct);
return FromBytes(bytes);
}
///
/// Loads a texture from a file loaded in a byte array.
///
/// Image file byte array
/// The loaded
public static Texture2D FromBytes(byte[] bytes)
{
bytes.ThrowIfNull(nameof(bytes));
var tex = new Texture2D(2, 2);
tex.LoadImage(bytes);
return tex;
}
#endregion
}
}