当前位置:网站首页>Unity图片加载和保存

Unity图片加载和保存

2022-06-23 06:47:00 牛神自

加载:

1.异步:(其实还是在主线程加载)
使用UnityWebRequest(或者WWW)进行图片加载,可以加载本地(速度慢,2048*1024大小的图片加载时间780ms,不卡界面)和网络图片。

UnityWebRequest request = UnityWebRequestTexture.GetTexture(Application.streamingAssetsPath + "/Test3.jpg");
yield return request.SendWebRequest();
if (request.downloadHandler.isDone)
{
    
    var tex = DownloadHandlerTexture.GetContent(request);
}

2.同步:
使用File进行读取(速度快,2048*1024大小的图片加载时间22ms,会卡主线程界面,小图片时间短,察觉不到)

var bytess = File.ReadAllBytes(Application.streamingAssetsPath + "/Test3.jpg");
var temp = new Texture2D(1, 1);
temp.LoadImage(bytess);

保存:

1.同步:

//这一步比较耗时,图片很大,会卡主线程
var bytes3 = tex.EncodeToJPG();
//下面的保存也可以用异步,但保存时间很短,也可以不用,2048*1024保存时间大约1ms,
//超大图片可以改用异步保存
File.WriteAllBytes(Application.streamingAssetsPath + "/Test3.jpg", bytes3);

2.异步:

var pixels = tex.GetPixels32(0);
GraphicsFormat format = tex.graphicsFormat;
uint width = (uint)tex.width;
uint height = (uint)tex.height;
Task.Run(() =>
{
    
    var bytes3 = ImageConversion.EncodeArrayToJPG(pixels, format, width, height);
    File.WriteAllBytes(Application.streamingAssetsPath + "/Test3.jpg", bytes3);
});
原网站

版权声明
本文为[牛神自]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_41155760/article/details/125336545