82 lines
2.9 KiB
C#
82 lines
2.9 KiB
C#
using BestHTTP;
|
||
using System.IO;
|
||
using UnityEngine;
|
||
|
||
namespace Thousandto.Plugins.Common
|
||
{
|
||
//图片同步工具类,提供给lua使用,防止lua直接访问bytes数据导致数据交换频繁
|
||
public static class TexSyncUtils
|
||
{
|
||
//保存图片到文件
|
||
public static void SaveTex(Texture2D tex, string filePath)
|
||
{
|
||
File.WriteAllBytes(filePath, tex.EncodeToJPG());
|
||
}
|
||
//从文件中读取图片,并且规范size
|
||
public static Texture2D LoadTex(string filePath, int texWidth, int texHeight)
|
||
{
|
||
Texture2D result = null;
|
||
var bytes = File.ReadAllBytes(filePath);
|
||
var tex2d = new Texture2D(0, 0);
|
||
tex2d.LoadImage(bytes);
|
||
if (texWidth != tex2d.width || texHeight != tex2d.height)
|
||
{
|
||
result = new Texture2D(texWidth, texHeight);
|
||
for (int x = 0; x < texWidth; ++x)
|
||
{
|
||
for (int y = 0; y < texHeight; ++y)
|
||
{
|
||
result.SetPixel(x, y, tex2d.GetPixelBilinear((float)x / texWidth, (float)y / texHeight));
|
||
}
|
||
}
|
||
}
|
||
else
|
||
{
|
||
result = tex2d;
|
||
}
|
||
result.Apply();
|
||
return result;
|
||
}
|
||
//将图片文件增加到HTTPRequest的二进制数据中
|
||
public static void AddTexToBinData(HTTPRequest request, Texture2D tex, string fieldName)
|
||
{
|
||
request.AddBinaryData(fieldName, tex.EncodeToJPG());
|
||
}
|
||
//将图片文件增加到HTTPRequest的上传流中
|
||
public static void AddTexToUpStream(HTTPRequest request, Texture2D tex)
|
||
{
|
||
request.UploadStream = new MemoryStream(tex.EncodeToJPG());
|
||
}
|
||
//将HTTPResponse中的数据转换为图片并且存储到文件
|
||
public static Texture2D CovertToTex(HTTPResponse res, string filePath)
|
||
{
|
||
//创建图片
|
||
var tex2d = new Texture2D(0, 0);
|
||
tex2d.LoadImage(res.Data);
|
||
tex2d.Apply();
|
||
//保存到文件
|
||
File.WriteAllBytes(filePath, res.Data);
|
||
return tex2d;
|
||
}
|
||
//创建目录
|
||
public static void CreateDirectory(string path)
|
||
{
|
||
if (!Directory.Exists(path))
|
||
{
|
||
Directory.CreateDirectory(path);
|
||
}
|
||
}
|
||
//设置连接超时时间
|
||
public static void SetConnectTimeout(HTTPRequest request, float sec)
|
||
{
|
||
var span = new System.TimeSpan((long)(sec * 10000000));
|
||
request.ConnectTimeout = span;
|
||
}
|
||
//设置访问超时时间
|
||
public static void SetTimeout(HTTPRequest request, float sec)
|
||
{
|
||
var span = new System.TimeSpan((long)(sec * 10000000));
|
||
request.Timeout = span;
|
||
}
|
||
}
|
||
} |