Problems setting up a Texture2D

I am trying to set up a Texture2D using either the material/texture of a GameObject or by loading a material/texture from my Resources folder, but keep getting the following error:

NullReferenceException: Object reference not set to an instance of an object

Here is the code I’ve been TRYING to use with no success:

**First attempt:**
Texture2D tex = new Texture2D(200,200);
tex = Resources.Load("imageCamera") as Texture2D;
byte[] bytes = tex.EncodeToPNG();
Destroy(tex);
File.WriteAllBytes(Application.persistentDataPath + "/SavedS2creen.png", bytes);

**Second attempt:**
Texture2D tex2 = GameObject.Find("CapturedPicture").renderer.material.GetTexture("_MainTex") as Texture2D;
byte[] bytes = tex2.EncodeToPNG();

If anyone has any idea how to help me out, I would really appreciate it.

EDIT: I know that for sure the material/texture that I’m trying to load is not null. If you look at my “second attempt”, you’ll see that I have a GameObject called CapturedPicture. That has the material in question that I want to assign to a Texture2D.

For EncodeToPNG to work, the texture must first have it’s IsReadable flag set to true.

string path AssetDatabase.GetAssetPath( (Texture2D)tex );
TextureImporter ti = TextureImporter.GetAtPath( path ) as TextureImporter;
ti.isReadable = true;
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);

I added the code, so that it now looks like this:

Texture2D tex = new Texture2D(200, 200);
tex = Resources.Load("imageCamera") as Texture2D;
		
string path = AssetDatabase.GetAssetPath( (Texture2D)tex );
TextureImporter ti = TextureImporter.GetAtPath( path ) as TextureImporter;
ti.isReadable = true; //nullRef
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
		
byte[] bytes = tex.EncodeToPNG();
Destroy(tex);
File.WriteAllBytes(Application.persistentDataPath + "/SavedS2creen.png", bytes);

But now I’m getting a NullReferenceException at ti.isReadable = true;

Any thoughts?