⭐Unity reads local images and then crops the area

The current requirement is to read the local image and then screenshot it into a new image in the area.

Without further ado, let’s get straight to the code.

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);
    }
}

After the code is mounted, the cropping position and cropping size can be adjusted according to needs.

Guess you like

Origin blog.csdn.net/weixin_53501436/article/details/135150413