Skip to content

Instantly share code, notes, and snippets.

@anzfactory
Created December 21, 2016 13:43
Show Gist options
  • Save anzfactory/4f8db6dd1df843bbbe95c71737cc81a6 to your computer and use it in GitHub Desktop.
Save anzfactory/4f8db6dd1df843bbbe95c71737cc81a6 to your computer and use it in GitHub Desktop.
[Unity]base64エンコードされた画像を表示するサンプル
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using System.Text;
using System;
public class ButtonConvert : MonoBehaviour
{
[SerializeField] private Image image;
public void OnClick()
{
string base64String = ReadFile("gahaha.base64.txt");
if (string.IsNullOrEmpty(base64String)) {
return;
}
this.image.sprite = SpriteFromBase64(base64String);
}
string ReadFile(string fileName)
{
// read base64 file
FileInfo fileInfo = new FileInfo(Application.dataPath + "/Base64/" + fileName);
string base64String = "";
try {
using (StreamReader reader = new StreamReader(fileInfo.OpenRead(), Encoding.UTF8)){
base64String = reader.ReadToEnd();
}
} catch (Exception e){
Debug.LogError(e);
}
return base64String;
}
Sprite SpriteFromBase64(string base64String)
{
// base64 -> bytes
byte[] bytes = Convert.FromBase64String(base64String.Split(',')[1]);
// bytes -> texture
Texture2D texture2D = new Texture2D(1, 1);
texture2D.LoadImage(bytes);
// texture -> sprite
return Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height), Vector2.zero);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment