现在需求是将本地的图片读取之后再区域截图成新的图片
话不多说直接上代码
using UnityEngine;
using System.IO;
public class LocalRegionCapture : MonoBehaviour
{
public string fullScreenImagePath = "Assets/SavedImages/fullScreenScreenshot.png";
public string localRegionImagePath = "Assets/SavedImages/localRegionScreenshot.png";
public UnityEngine.Rect localRegionRect = new UnityEngine.Rect(100, 100, 200, 200); // Adjust the region as needed
private void Start()
{
CaptureLocalRegionAndSave();
}
private void CaptureLocalRegionAndSave()
{
// Load the full screen image
Texture2D fullScreenTexture = LoadFullScreenImage();
// Extract the local region from the full screen image
Texture2D localRegionTexture = ExtractLocalRegion(fullScreenTexture, localRegionRect);
// Save the local region image to file
SaveTextureToFile(localRegionTexture, localRegionImagePath);
// Clean up
Destroy(fullScreenTexture);
Destroy(localRegionTexture);
}
private Texture2D LoadFullScreenImage()
{
// Load the full screen image
byte[] bytes = File.ReadAllBytes(fullScreenImagePath);
Texture2D texture = new Texture2D(2, 2);
texture.LoadImage(bytes);
return texture;
}
private Texture2D ExtractLocalRegion(Texture2D fullScreenTexture, UnityEngine.Rect regionRect)
{
// Create a new texture for the local region
Texture2D localRegionTexture = new Texture2D((int)regionRect.width, (int)regionRect.height, TextureFormat.RGB24, false);
// Read pixels from the full screen image within the specified region
localRegionTexture.SetPixels(fullScreenTexture.GetPixels((int)regionRect.x, (int)regionRect.y, (int)regionRect.width, (int)regionRect.height));
localRegionTexture.Apply();
return localRegionTexture;
}
private void SaveTextureToFile(Texture2D texture, string filePath)
{
byte[] bytes = texture.EncodeToPNG();
File.WriteAllBytes(filePath, bytes);
Debug.Log("Local region screenshot saved at: " + filePath);
}
}
代码挂载后可根据需求调整裁剪位置和裁剪大小