// THIRD_PARTY // SOURCE: // https://forum.unity.com/threads/generating-sprites-dynamically-from-png-or-jpeg-files-in-c.343735/ using UnityEngine; using System.Collections; using System.IO; public static class ImageToSprite { //Static class instead of _instance // Usage from any other script: // MySprite = IMG2Sprite.LoadNewSprite(FilePath, [PixelsPerUnit (optional)], [spriteType(optional)]) public static Sprite LoadNewSprite(string FilePath, float PixelsPerUnit = 100.0f, SpriteMeshType spriteType = SpriteMeshType.FullRect) { // Load a PNG or JPG image from disk to a Texture2D, assign this texture to a new sprite and return its reference Texture2D SpriteTexture = LoadTexture(FilePath); if (SpriteTexture == null) { Debug.LogError("Failed to load texture from " + FilePath); return null; } Sprite NewSprite = Sprite.Create(SpriteTexture, new Rect(0, 0, SpriteTexture.width, SpriteTexture.height), new Vector2(0, 0), PixelsPerUnit, 0, spriteType); return NewSprite; } public static Sprite ConvertTextureToSprite(Texture2D texture, float PixelsPerUnit = 32.0f, SpriteMeshType spriteType = SpriteMeshType.FullRect) { // Converts a Texture2D to a sprite, assign this texture to a new sprite and return its reference Sprite NewSprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0), PixelsPerUnit, 0, spriteType); return NewSprite; } public static Texture2D LoadTexture(string FilePath) { // Load a PNG or JPG file from disk to a Texture2D // Returns null if load fails Texture2D Tex2D; byte[] FileData; if (File.Exists(FilePath)) { FileData = File.ReadAllBytes(FilePath); Tex2D = new Texture2D(2, 2); // Create new "empty" texture if (Tex2D.LoadImage(FileData)) // Load the imagedata into the texture (size is set automatically) return Tex2D; // If data = readable -> return texture } return null; // Return null if load failed } }