- Home /
What is the best way to save a modified texture to disk?
I have some textures that I want to do some SetPixel operations on, probably in an Editor script.
What is the best way to make the changes that I do in Unity stick? I want to take some of the load off my game, and put what I can in a pre-process.
I've seen some answers using the serializer to do this, would this work locally as well?
hmm to save locally i usually encode it to png and then change it to string64 and save it in a text file
and and reverse the process to get the texture back, works fine for me!! but im not sure if this is wat you want.
That would probably work fine for me, any pointers to some how-to's?
im not on unity now let me prepare a rough on give me some time.
Is this what you mean? http://unity3d.com/support/documentation/ScriptReference/Texture2D.EncodeToPNG.html
Answer by flamy · May 17, 2012 at 04:44 PM
using UnityEngine;
using System.Collections;
using System;
public class ImageSaver : MonoBehaviour {
public Texture2D test;
WWW www;
void Start () {
StartCoroutine( SaveTexture("bar","bar"));
}
public IEnumerator SaveTexture(string imageName,string saveAs)
{
Texture2D tex;
byte[] byteArray;
WWW www= new WWW("file://"+Application.dataPath+"//Resources//"+imageName+".png");
yield return www;
if(www.texture!=null)
{
print("success");
}
tex=www.texture;
byteArray=tex.EncodeToPNG();
string temp=Convert.ToBase64String(byteArray);
PlayerPrefs.SetString(saveAs,temp); /// save it to file if u want.
PlayerPrefs.SetInt(saveAs+"_w",tex.width);
PlayerPrefs.SetInt(saveAs+"_h",tex.height);
}
public Texture2D RetriveTexture(string savedImageName)
{
string temp=PlayerPrefs.GetString(savedImageName);
int width=PlayerPrefs.GetInt(savedImageName+"_w");
int height=PlayerPrefs.GetInt(savedImageName+"_h");
byte[] byteArray= Convert.FromBase64String(temp);
Texture2D tex = new Texture2D(width,height);
tex.LoadImage(byteArray);
return tex;
}
void Update () {
test=RetriveTexture("bar");
}
}
hey this is the tested code that works at my end. I am using www to load the texture inside the game because you cannot encode the texture imported inside unity, unless it is imported as ARGB32 or RGB24. so im loading it like an external image file and processing it. other than that it is pretty much explainable i guess.
PS: the texture shd be in resource folder.