Skip to content

Instantly share code, notes, and snippets.

@smkplus
Forked from nnm-t/ConvertToSprite.cs
Last active August 3, 2019 08:24
Show Gist options
  • Save smkplus/6d4b5e13105a8fedb626451917a352d6 to your computer and use it in GitHub Desktop.
Save smkplus/6d4b5e13105a8fedb626451917a352d6 to your computer and use it in GitHub Desktop.
Convert Texture2D To Sprite
using UnityEngine;
public static class SpriteExtensiton
{
/// <summary>
/// Convert Texture2D To Sprite
/// </summary>
/// <param name="texture"></param>
/// <returns></returns>
public static Sprite Texture2DToSprite(this Texture2D texture)
{
return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
}
/// <summary>
/// Convert Sprite To Texture2D
/// </summary>
/// <param name="sprite"></param>
/// <returns></returns>
public static Texture2D SpriteToTexture2D(Sprite sprite)
{
if (sprite.rect.width != sprite.texture.width)
{
Texture2D newText = new Texture2D((int)sprite.rect.width, (int)sprite.rect.height);
Color[] newColors = sprite.texture.GetPixels(
(int)sprite.textureRect.x,
(int)sprite.textureRect.y,
(int)sprite.textureRect.width,
(int)sprite.textureRect.height);
newText.SetPixels(newColors);
newText.Apply();
return newText;
}
else
return sprite.texture;
}
/// <summary>
/// Load Sprite From Path
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static Sprite LoadSprite(string path)
{
if (string.IsNullOrEmpty(path)) return null;
if (System.IO.File.Exists(path))
{
byte[] bytes = System.IO.File.ReadAllBytes(path);
Texture2D texture = new Texture2D(1, 1);
texture.LoadImage(bytes);
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
return sprite;
}
return null;
}
/// <summary>
/// Load Texture From Path
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static Texture2D LoadTexture(string path)
{
if (string.IsNullOrEmpty(path)) return null;
if (System.IO.File.Exists(path))
{
byte[] bytes = System.IO.File.ReadAllBytes(path);
Texture2D texture = new Texture2D(1, 1);
texture.LoadImage(bytes);
return texture;
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment