Texture转换成Texture2D
/// <summary>
/// Texture转换成Texture2D...
/// </summary>
/// <param name="texture"></param>
/// <returns></returns>
Texture2D TextureToTexture2D(Texture texture)
{
Texture2D texture2D = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false);
RenderTexture currentRT = RenderTexture.active;
RenderTexture renderTexture = RenderTexture.GetTemporary(texture.width, texture.height, 32);
Graphics.Blit(texture, renderTexture);
RenderTexture.active = renderTexture;
texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
texture2D.Apply();
RenderTexture.active = currentRT;
RenderTexture.ReleaseTemporary(renderTexture);
return texture2D;
}
使用Texture2D 的形式截图,,,
/// <summary>
/// 截图...
/// </summary>
/// <param name="rect">截图的区域</param>
/// <returns></returns>
Texture2D CaptureScreenshot(Rect rect)
{
// 先创建一个的空纹理,大小可根据实现需要来设置
Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24,false);
// 读取屏幕像素信息并存储为纹理数据,
screenShot.ReadPixels(rect, 0, 0);
screenShot.Apply();
// 然后将这些纹理数据,成一个png图片文件
byte[] bytes = screenShot.EncodeToPNG();
string filename = Application.dataPath + "/Screenshot.png";
System.IO.File.WriteAllBytes(filename, bytes);
Debug.Log(string.Format("截屏了一张图片: {0}", filename));
// 最后,我返回这个Texture2d对象,这样我们直接,所这个截图图示在游戏中,当然这个根据自己的需求的。
return screenShot;
}
将Texture保存到本地,,,
/// <summary>
/// 将Texture转为本地PNG...
/// </summary>
/// <param name="filePath"></param>
/// <param name="teture"></param>
/// <returns></returns>
public static bool saveMainTextureToPng(string filePath, Texture teture)
{
if (teture.GetType() != typeof(Texture2D))
{
return false;
}
Texture2D savedTexture = (Texture2D)teture;
try
{
Texture2D newTexture = new Texture2D(savedTexture.width, savedTexture.height, TextureFormat.RGBA32, false);
newTexture.SetPixels(0, 0, savedTexture.width, savedTexture.height, savedTexture.GetPixels());
newTexture.Apply();
byte[] bytes = newTexture.EncodeToPNG();
if (bytes != null && bytes.Length > 0)
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
System.IO.File.WriteAllBytes(filePath, bytes);
}
}
catch (IOException ex)
{
return false;
}
return true;
}
将本地图片转换为Byte[]数组,,,
/// <summary>
/// 将图片转换为byte数组...
/// </summary>
/// <param name="filePath">图片路径</param>
/// <returns></returns>
public static byte[] ReadTexture(string filePath)
{
FileStream fileStream = new FileStream(filePath, FileMode.Open, System.IO.FileAccess.Read);
fileStream.Seek(0, SeekOrigin.Begin);
//创建byte数组 ...
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, (int)fileStream.Length);
fileStream.Close();
fileStream.Dispose();
fileStream = null;
return buffer;
}