最近再做一个从电脑上选择图片设置成头像图标之类的功能。
void OnIconSelectBtnClick()
{
#region 调用Window文件选择窗体 选中图片文件
OpenFileName openFileName = new OpenFileName();
openFileName.structSize = Marshal.SizeOf(openFileName);
openFileName.filter = "图片文件(*.png)\0*.png";
openFileName.file = new string(new char[256]);
openFileName.maxFile = openFileName.file.Length;
openFileName.fileTitle = new string(new char[64]);
openFileName.maxFileTitle = openFileName.fileTitle.Length;
openFileName.initialDir = Application.streamingAssetsPath.Replace('/', '\\');
openFileName.title = "图标选择";
openFileName.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008;
if (LocalDialog.GetOpenFileName(openFileName))
{
projectIconPath = openFileName.file;
}
#endregion
//设置图标
if (!string.IsNullOrEmpty(projectIconPath))
{
//图片保存到本地
PictureLoad.instance.LoadTextuer("file://"+projectIconPath, Application.dataPath + "/Resources/"+ openFileName.fileTitle);
}
}
使用WWW请求来下载图片到本地
public void LoadTextuer(string LoadPath,string SavePath)
{
Debug.Log("开始下载");
StartCoroutine(LoadImg(LoadPath,SavePath));
}
IEnumerator LoadImg(string LoadPath,string SavePath)
{
//开始下载图片
WWW www = new WWW(LoadPath);
yield return www;
//下载完成,保存图片到路径filePath
if (www.isDone==true)
{
Debug.Log("下载完成");
Texture2D texture2D = www.texture;
byte[] bytes = texture2D.EncodeToPNG();
File.WriteAllBytes(SavePath, bytes);
}
}
下载完成,可以看到图片已经保存到unity目录下面了。