I know this kind of answer is kind of annoying but doing this is a bad idea, if you really need to save texture data you should save it as binary and not as a string, you will user more bytes, over complicate your code and in general it's not a good practice.
HOWEVER, I will still answer the question, but please avoid this.
If you want to save this string as a json, you will have to specify that its serializable as c# sees strings as not suitable for serialization (this is false however: Is String not serializable by default in .Net Core?), add this behind your string and your code should work (in case you are wondering this is called an attribute, it's sort of like a tag):
[Serializable]
NOW, for the correct way of doing this we will take an example code from the unity docs (an extremely helpful tool by the way):
Texture2D.EncodeToPNG
// Encode texture into PNG
byte[] bytes = tex.EncodeToPNG();
Object.Destroy(tex);
// For testing purposes, also write to a file in the project folder
// File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes);
This piece of code takes a texture 2d class, converts it to bytes (just like you are already doing) and then writes it as binary using File.WriteAllBytes()
.
You should also destroy the texture object (Object.Destroy(Your texture)
) to prevent the game from storing unnecessary bytes which might cause lag spikes from the garbage collector (I think).
But all of this is useless for you're case, if you want to screenshot the main camera you can just use unity's built in function, which also insures cross platform compatibility:
ScreenCapture.CaptureScreenshot("your path");
If you need an higher-res OR lower-res screenshot, add an multiplier argument after the path, like this:
ScreenCapture.CaptureScreenshot("your path", SizeMultiplier);
So, to wrap this up, do something like this and you should be good to go:
ScreenCapture.CaptureScreenshot(Application.dataPath + "/File.png");