unity 图片和base64互转

/// <summary>
/// 图片转换成base64编码文本
/// </summary>
        public void ImgToBase64String(string path)
        {
            try
            {
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, (int)fs.Length);
                string base64String = Convert.ToBase64String(buffer);
                Debug.Log("获取当前图片base64为---" + base64String);
                recordBase64String = base64String;
            }
            catch(Exception e)
            {
                Debug.Log("ImgToBase64String 转换失败:" + e.Message);
            }
        }


/// <summary>
/// base64编码文本转换成图片
/// </summary>

        public void Base64ToImg(Image imgComponent)
        {
            string base64 = recordBase64String;
            byte[] bytes = Convert.FromBase64String(base64);
            Texture2D tex2D = new Texture2D(100, 100);
            tex2D.LoadImage(bytes);
            Sprite s = Sprite.Create(tex2D, new Rect(0, 0, tex2D.width, tex2D.height), new Vector2(0.5f, 0.5f));
            imgComponent.sprite = s;
            Resources.UnloadUnusedAssets();
        }

猜你喜欢

转载自blog.csdn.net/jiangyangll/article/details/80566330