- Home /
Create image-file from resources image
Hello,
I am working on an leveleditor for standalone, where each level can have a picture. An example level is created, if the editor does not contain any levels, consisting of a txt file for the coordinates of the elements and the image from the resources-folder:
void CreateExample(){
if(!Directory.Exists(Application.dataPath+"/Resources/Levels/") ||
!File.Exists(Application.dataPath+"/Resources/Levels/Example.txt")){
Directory.CreateDirectory(Application.dataPath+"/Resources/Levels/");
string exampleLevel = "0:Corridore:(-1.0, 0.0, -1.0):(0.0, 0.0, 0.0)";
File.WriteAllText(Application.dataPath+"/Resources/Levels/Example.txt",exampleLevel);
Texture2D exampleImage = Resources.Load("Levels/Example.jpg") as Texture2D;
byte[] bytes = exampleImage.EncodeToJPG(100);
BinaryWriter binary = new BinaryWriter(bytes);
File fileImage = File.Open(Application.dataPath+"/Resources/Levels/Example.jpg", FileMode.Create);
binary.Write(fileImage);
fileImage.Close();
PlayerPrefs.SetString("Levelname", "Example");
}
}
But there are some big errors when it's trying to write the image-file.
error CS0723: `fileImage': cannot declare variables of static types
Answer by saschandroid · Mar 24, 2016 at 06:46 AM
Like File.WriteAllText you could use File.WriteAllBytes:
byte[] bytes = exampleImage.EncodeToJPG(100);
File.WriteAllBytes(Application.dataPath+"/Resources/Levels/Example.jpg", bytes);
Thanks, but now it there is a NullReference Exception in the line where the bytes array is declared. It seems the texture2D could not be loaded although it is existing.
If you load from Resources, "extensions must be omitted." Have you done that?
hmm if I omit the extension I get an error because there is a txt file with the same name. If I store them in a different folder to avoid the inconsistency I get an Exeption: Texture "Name" is not readable, the texture memory can not be accessed from scripts. You can make the texture readable in the texture import settings.