?Unity 读取本地图片再区域裁剪
2023-12-22 14:12:08
现在需求是将本地的图片读取之后再区域截图成新的图片
话不多说直接上代码
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);
}
}
代码挂载后可根据需求调整裁剪位置和裁剪大小
文章来源:https://blog.csdn.net/weixin_53501436/article/details/135150413
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!