unity图片转换(Texture2d与Sprite,Base64与Texture2d)

本文介绍了如何在Unity中进行Texture2D对象与Base64编码之间的转换,以及Sprite与Texture2D之间的转换,包括Texture2DToBase64,Base64ToTexture2D,Texture2DToSprite和SpriteToTexture2D的具体实现方法。
摘要由CSDN通过智能技术生成

1、Texture2d转Base64

    public static string Texture2DToBase64(Texture2D texture)
    {
        byte[] data = texture.EncodeToPNG();
        return Convert.ToBase64String(data);
    }

2、Base64转Texture2d

public static Texture2D Base64ToTexture2D(string encoded)
    {
        byte[] data = Convert.FromBase64String(encoded);
        int width, height;
        GetImageSize(data, out width, out height);
        Texture2D texture = new Texture2D(width, height, TextureFormat.ARGB32, false, true);
        texture.hideFlags = HideFlags.HideAndDontSave;
        texture.filterMode = FilterMode.Point;
        texture.LoadImage(data);
        return texture;
    }
 static void GetImageSize(byte[] imageData, out int width, out int height)
    {
        width = ReadInt(imageData, 3 + 15);
        height = ReadInt(imageData, 3 + 15 + 2 + 2);
    }
    static int ReadInt(byte[] imageData, int offset)
    {
        return (imageData[offset] << 8) | imageData[offset + 1];
    }

3、Texture2d转Sprite

public static Sprite Texture2DToSprite(Texture2D texture2D)
    {
         return Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height), Vector2.zero);
    }

4、Sprite转Texture2d

 public static Texture2D SpriteToTexture2D(Sprite sprite)
    {
        Texture2D texture = new Texture2D((int)sprite.rect.width, (int)sprite.rect.height);

        Color[] colors = sprite.texture.GetPixels(Mathf.RoundToInt(sprite.rect.x), Mathf.RoundToInt(sprite.rect.y), Mathf.RoundToInt(sprite.rect.width), Mathf.RoundToInt(sprite.rect.height));
        texture.SetPixels(colors);
        texture.Apply();
        return texture;
    }

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值