Load External JPG as TextAsset

I have code that takes an image file and converts it to bytes. If I rename an image manually by adding “.bytes” then drag it into the Inspector slot of variable imageAsset, the code below works great:

public TextAsset imageAsset;

    int width = Screen.width;
    int height = Screen.height;
    var tex = new Texture2D(width, height, TextureFormat.RGB24, false);

    byte[] bytes = tex.EncodeToPNG();

The problem I have is that I want to perform the same operation for Android images.

The pathname is already captured (e.g. /storage/emulated/0/Pictures/IMG_20180318.jpg) in:
private string toPathname;

I’m not sure how I would use the pathname of the image to process the actual image the same way I do when dragging the image to the Inspector variable slot for imageAsset.

Thanks in advance, I’ve been struggling with this one,


Well, first of all an TextAsset is an asset registrated in the assetdatabase of your project. TextAssets can only be created inside the UnityEditor so an external file will never become a TextAsset.

To read external files you can either use the WWW class of Unity inside a coroutine or simply use the .NET File class and use the static ReadAllBytes method.

Also note that creating such a large texture is just a waste of memory as when you call LoadImage the image will be replaced anyways. So just do something like this:

public static byte[] ConvertToPng(string aPath)
    bytes[] data = System.IO.File.ReadAllBytes(aPath);
    var tex = new Texture2D(1, 1, TextureFormat.RGB24, false);
    byte[] bytes = tex.EncodeToPNG();
    return bytes;