Base64 to texture decoding, js -> webgl
I'm building webgl application in unity and I want to allow user to import image (png).
Javascript:
function process(input) {
let file = input.files[0];
let reader = new FileReader();
reader.onload = function (e) {
unityInstance.SendMessage('Phone', 'SetImageFromBase64', e.target.result);
};
reader.readAsDataURL(file);
}
C#:
private void Awake()
{
SetImageFromBase64();
}
public void SetImageFromBase64(string str = "data:image/png;base64,iVBORw0KGg(...)")
{
var bytes = Convert.FromBase64String(str.Substring("data:image/png;base64,".Length));
var tex = new Texture2D(2, 2);
tex.LoadImage(bytes);
tex.wrapMode = TextureWrapMode.Clamp;
tex.Apply();
meshRenderer.material.SetTexture(MainTex, tex);
}
And when application is started, image is properly loaded, but when I try to load same image using javascript all I'm getting is black texture. Do anyone have an idea why this is happening?
Comment
Best Answer
Answer by Waxy · Jul 17, 2019 at 07:45 AM
OK, so I've solved problem... Before setting texture I had code:
var oldTexture = meshRenderer.material.GetTexture(MainTex2);
#if UNITY_EDITOR
// Original texture is loaded from Asset folder and unity will throw error if we try to destroy it
if (!AssetDatabase.Contains(oldTexture))
{
Destroy(oldTexture);
}
#else
Destroy(oldTexture);
#endif
That was supposed to avoid memory leak by removing old texture, problem obviously was in removing wrong texture from shader.