Unity 截图功能

可以设置各种分辨率,图片样式(png,jpg)

/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

using System;
using System.IO;
using Borodar.ScreenShooter.Configs;
using UnityEngine;


namespace Borodar.ScreenShooter.Configs
{
    /// <summary>
    /// 保存的图片属性
    /// </summary>
    [Serializable]
    public class ScreenshotConfig
    {
        public string Name; 
        /// <summary>
        /// 宽
        /// </summary>
        public int Width;

        //高
        public int Height;

        //后缀格式 png,jpg
        public Format Type;

        public ScreenshotConfig() { }

        public ScreenshotConfig(string name, int width, int height, Format type)
        {
            Name = name;
            Width = width;
            Height = height;
            Type = type;
        }

        //---------------------------------------------------------------------
        // Nested
        //---------------------------------------------------------------------

        public enum Format
        {
            PNG,
            JPG
        }
    }
}
namespace Borodar.ScreenShooter.Utils
{
    public static class ScreenshotUtil
    {
        public static void TakeScreenshot(ScreenShooterSettings settings, ScreenshotConfig config)
        {
            var suffix = settings.AppendTimestamp ? "." + DateTime.Now.ToString("yyyyMMddHHmmssfff") : "";
            TakeScreenshot(settings.Camera, settings.SaveFolder, settings.Tag, suffix, config);
        }


        /// <summary>
        /// 通过一个摄像机截图
        /// </summary>
        /// <param name="camera"></param>
        /// <param name="saveFolder">保存的路径</param>
        /// <param name="prefix">图片名称前缀</param>
        /// <param name="config"></param>
        /// <param name="isAddTime">图片名称是否加入世界</param>
        public static void TakeScreenshot(Camera camera,string saveFolder,string prefix, ScreenshotConfig config, bool isAddTime = false)
        {
            var suffix = isAddTime ? "." + DateTime.Now.ToString("yyyyMMddHHmmssfff") : "";
            TakeScreenshot(camera, saveFolder, prefix, suffix, config);
        }

        public static void TakeScreenshot(Camera camera, string folderName, string prefix, string suffix, ScreenshotConfig screenshotConfig)
        {
            var scrTexture = new Texture2D(screenshotConfig.Width, screenshotConfig.Height, TextureFormat.RGB24, false);
            var scrRenderTexture = new RenderTexture(scrTexture.width, scrTexture.height, 24);
            var camRenderTexture = camera.targetTexture;

            camera.targetTexture = scrRenderTexture;
            camera.Render();
            camera.targetTexture = camRenderTexture;

            RenderTexture.active = scrRenderTexture;
            scrTexture.ReadPixels(new Rect(0, 0, scrTexture.width, scrTexture.height), 0, 0);
            scrTexture.Apply();

            SaveTextureAsFile(scrTexture, folderName, prefix, suffix, screenshotConfig);
        }

        /// <summary>
        /// 保存图片文件
        /// </summary>
        /// <param name="texture"></param>
        /// <param name="folder"></param>
        /// <param name="prefix"></param>
        /// <param name="suffix"></param>
        /// <param name="screenshotConfig"></param>
        public static void SaveTextureAsFile(Texture2D texture, string folder, string prefix, string suffix, ScreenshotConfig screenshotConfig)
        {
            byte[] bytes;
            string extension;

            switch (screenshotConfig.Type)
            {
                case ScreenshotConfig.Format.PNG:
                    bytes = texture.EncodeToPNG();
                    extension = ".png";
                    break;
                case ScreenshotConfig.Format.JPG:
                    bytes = texture.EncodeToJPG();
                    extension = ".jpg";
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            var fileName = prefix + screenshotConfig.Name + "." + screenshotConfig.Width + "x" + screenshotConfig.Height + suffix;
            var imageFilePath = folder + "/" + MakeValidFileName(fileName + extension);

            // ReSharper disable once PossibleNullReferenceException
            (new FileInfo(imageFilePath)).Directory.Create();
            File.WriteAllBytes(imageFilePath, bytes);

            Debug.Log("Image saved to: " + imageFilePath);
        }

        private static string MakeValidFileName(string name)
        {
            var invalidChars = System.Text.RegularExpressions.Regex.Escape(new string(Path.GetInvalidFileNameChars()));
            var invalidRegStr = string.Format(@"([{0}]*\.+$)|([{0}]+)", invalidChars);

            return System.Text.RegularExpressions.Regex.Replace(name, invalidRegStr, "_");
        }
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值