Home > other >  Sprite no show in localfolder?
Sprite no show in localfolder?

Time:03-05

I use the code below to convert the png to sprite on a button, it works fine in the runtime. but when I close the project and restart the png still no convert to sprite.

public void creatimage(){
string pngpath = Application.dataPath   $"/Screenshot{index}.png";
byte[] filedata;
filedata = System.IO.File.ReadAllBytes(pngpath);
Texture2D text = new Texture2D(2, 2);
text.LoadImage(filedata);
Rect rec = new Rect(0, 0, text.width, text.height);
Sprite sp = Sprite.Create(text, rec, new Vector2(0, 0), 0.1f);
child.GetComponent<Image>().sprite = sp;
text.Apply();
}

I need to convert the png to sprite forever, how can I do that?

enter image description here

CodePudding user response:

Well, I'm pretty sure that you can only load/save textures to disk. A texture can be saved as follows:

                    byte[] itemBGBytes = text.EncodeToPNG();
                    File.WriteAllBytes(pngpath, itemBGBytes);

CodePudding user response:

You can covert the png to sprite by using UnityEditor then use

TextureImporter to covert the png to sprite

TextureImporter importer = AssetImporter.GetAtPath(filename) as TextureImporter;
importer.textureType = TextureImporterType.Sprite;
EditorUtility.SetDirty(importer);
importer.SaveAndReimport();
  • Related