I’m trying to read a series of PNGs from a file, convert to byte arrays, then convert those to Texture2D. It seems like the byte array is being made correctly, but the function always returns false. I know the documentation says it returns false if the format is unsupported, but as far as I know I am using valid PNG files – I even dropped them into Unity to check and they correctly rendered, and by checking the file explorer I can see that they are all the correct type.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
public class BatchImporter : EditorWindow
{
string path = "";
string[] files = null;
string[] supportedImageExt = new string[] { "png", "jpg", "jpeg" };
List<Texture2D> images = new List<Texture2D>();
[MenuItem("Tools/Batch Card Import")]
public static void BatchCardImport()
{
EditorWindow wnd = GetWindow<BatchImporter>();
wnd.titleContent = new GUIContent("Batch Importer");
}
public void OnGUI()
{
if (GUILayout.Button("Select Card Folder"))
{
path = EditorUtility.OpenFolderPanel("Select Card Folder", "", "");
files = Directory.GetFiles(path);
for (int i = 0; i < files.Length; i++)
{
string file = files[i];
string[] x = file.Split('.');
string fileExt = x[x.Length - 1];
if (supportedImageExt.Any(s => s.Equals(fileExt)))
{
byte[] fileData = File.ReadAllBytes(file);
Debug.Log(fileData.Length); // returns correct number of bytes
Texture2D image = new Texture2D(2, 2);
bool success = ImageConversion.LoadImage(image, fileData);
Debug.Log(success); // always returns false
images.Add(image);
}
}
}
}
}