unity 截图、压缩图片

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

public class TextureZip : MonoBehaviour
{
    public Texture2D texture;
    public Texture2D texture2;

    public RawImage uitexture;
    public RawImage uitexture2;
    public RawImage uitexture3;

    void Start()
    {
        uitexture.texture = texture;
        //uitexture2.texture = CompressionTexture(texture, new Vector2(2500, 2500));
        uitexture3.texture = CompressionTexture(texture, new Vector2(100, 1500), 0);
        TakePhoto(Camera.main, new Vector2(800, 1000), (texture, textureName) =>
        {
            uitexture2.texture = texture;
        });
    }

    /// 
    /// 自适应图片尺寸
    /// 
    /// 
    /// 
    /// 
    public static Vector2 AdaptSize(Vector2 limitRange, Vector2 textureSize)
    {
        Vector2 size = textureSize;
        float standard_ratio = limitRange.x / limitRange.y;
        float ratio = size.x / size.y;
        if (ratio > standard_ratio)
        {
            //宽于标准宽度,宽固定
            float scale = size.x / limitRange.x;
            size.x = limitRange.x;
            size.y /= scale;
        }
        else
        {
            //高于标准宽度,高固定
            float scale = size.y / limitRange.y;
            size.y = limitRange.y;
            size.x /= scale;
        }
        return size;
    }


    /// 
    /// 压缩图片
    /// 
    /// 
    /// 
    ///  0 :无限制  1: 缩小  2:放大
    /// 
    public static Texture2D CompressionTexture(Texture2D orginalTexture, Vector2 limitRange, int type = 0)
    {
        if (!orginalTexture.isReadable)//读写权限
            return orginalTexture;

        //等比例
        Vector2 size = AdaptSize(limitRange, new Vector2(orginalTexture.width, orginalTexture.height));
        Color color;
        float pixo = limitRange.x / size.x;
        float pix = orginalTexture.width / size.x;  

        if (pix > 1 && type == 2) //缩小 
            return orginalTexture;
        else if (pix < 1 && type == 1) //放大 
            return orginalTexture;

        Texture2D newTexture = new Texture2D((int)size.x, (int)size.y, TextureFormat.RGBA32, false);
        for (int i = 0; i < newTexture.width; i++)
        {
            for (int j = 0; j < newTexture.height; j++)
            {
                color = orginalTexture.GetPixel((int)(i * pix), (int)(j * pix));
                newTexture.SetPixel(i, j, color);
            }
        }

        newTexture.Apply();
        return newTexture;
    }

    /// 
    /// 相机截图
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    public static void TakePhoto(Camera camera, Vector2 size, System.Action<Texture2D, string> callback = null, string path = null)
    {
        Vector2 osize = size;
        size = AdaptSize(new Vector2(camera.pixelWidth, camera.pixelHeight), size);
        size = AdaptSize(osize, size);

        Texture2D texture = CaptureCamera(camera, new Rect(Screen.width / 2 - size.x / 2, Screen.height / 2 - size.y / 2, size.x, size.y));
        string imageName = string.Format("Image{0}.png", GetTimeStamp);

        if (!string.IsNullOrEmpty(path))
        {
            var img = texture.EncodeToPNG();
            string file = string.Format("{0}/{1}", path, imageName);
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            CreateFile(file, img);
        }

        callback?.Invoke(texture, imageName);
    }

    /// 
    /// 相机截图
    /// 
    /// 
    /// 
    /// 
    public static Texture2D CaptureCamera(Camera camera, Rect rect)
    {
        // 创建一个RenderTexture对象  
        RenderTexture rt = new RenderTexture(camera.pixelWidth, camera.pixelHeight, 32);
        // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机  
        camera.targetTexture = rt;
        camera.Render();
        //ps: --- 如果这样加上第二个相机,可以实现只截图某几个指定的相机一起看到的图像。  
        //ps: camera2.targetTexture = rt;  
        //ps: camera2.Render();  
        //ps: -------------------------------------------------------------------  
        // 激活这个rt, 并从中中读取像素。  
        RenderTexture.active = rt;
        Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.ARGB32, false);//RGB24
        screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素  
        screenShot.Apply();
        // 重置相关参数,以使用camera继续在屏幕上显示  
        camera.targetTexture = null;
        //ps: camera2.targetTexture = null;  
        RenderTexture.active = null; // JC: added to avoid errors  
        GameObject.Destroy(rt);
        return screenShot;
    }



    public static void CreateFile(string targetPath, byte[] bytes)
    {
        string path = targetPath.Replace("file://", "");

        if (File.Exists(path))
            File.Delete(path);
        FileInfo file = new FileInfo(path);
        Stream stream = file.Create();
        stream.Write(bytes, 0, bytes.Length);
        stream.Close();
        stream.Dispose();
    }

    public static long GetTimeStamp
    {
        get
        {
            TimeSpan ts = new TimeSpan(DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks);
            return (long)ts.TotalMilliseconds;
        }
    }

}

你可能感兴趣的:(unity,游戏引擎)