Unity中的截图方法(包括全屏截图、区域截图、Camera截图和摄像头截图)

article/2025/9/15 11:46:27

Unity中的截图方法(包括全屏截图、区域截图、Camera截图和摄像头截图)

    • Application.CaptureScreenshot
      • ScreenCapture
    • Texture2D.ReadPixels
      • 视口截图
      • RenderTexture(Camera截图)
      • WebCamTexture(摄像头截图、照相)
    • 参考链接

之前项目中需要用到截图功能,经过查找找到3种方式,这里做一个记录。

Application.CaptureScreenshot

Application类下的CaptureScreenshot方法,截取的是某一帧时整个游戏的画面,或者说是全屏截图吧。
以下是两个重载的函数。其中filename参数为截图后保存下来的文件名;superSize参数为增加分辨率的因数:

//
// 摘要:
//     Captures a screenshot at path filename as a PNG file.
//
// 参数:
//   filename:
//     Pathname to save the screenshot file to.
//
//   superSize:
//     Factor by which to increase resolution.
[Obsolete("Application.CaptureScreenshot is obsolete. Use ScreenCapture.CaptureScreenshot instead (UnityUpgradable) -> [UnityEngine] UnityEngine.ScreenCapture.CaptureScreenshot(*)", true)]
public static void CaptureScreenshot(string filename);
//
// 摘要:
//     Captures a screenshot at path filename as a PNG file.
//
// 参数:
//   filename:
//     Pathname to save the screenshot file to.
//
//   superSize:
//     Factor by which to increase resolution.
[Obsolete("Application.CaptureScreenshot is obsolete. Use ScreenCapture.CaptureScreenshot instead (UnityUpgradable) -> [UnityEngine] UnityEngine.ScreenCapture.CaptureScreenshot(*)", true)]
public static void CaptureScreenshot(string filename, int superSize);

通过上面的代码也可以看出,在新版的Unity中该函数被废弃了。新的系统函数类是ScreenCapture

ScreenCapture

以下为系统类ScreenCapture

//
// 摘要:
//     Functionality to take Screenshots.
[NativeHeader("Modules/ScreenCapture/Public/CaptureScreenshot.h")]
public static class ScreenCapture
{public static void CaptureScreenshot(string filename);//// 摘要://     Captures a screenshot at path filename as a PNG file.//// 参数://   filename://     Pathname to save the screenshot file to.////   superSize://     Factor by which to increase resolution.////   stereoCaptureMode://     Specifies the eye texture to capture when stereo rendering is enabled.public static void CaptureScreenshot(string filename, int superSize);public static void CaptureScreenshot(string filename, StereoScreenCaptureMode stereoCaptureMode);public static Texture2D CaptureScreenshotAsTexture();//// 摘要://     Captures a screenshot of the game view into a Texture2D object.//// 参数://   superSize://     Factor by which to increase resolution.////   stereoCaptureMode://     Specifies the eye texture to capture when stereo rendering is enabled.public static Texture2D CaptureScreenshotAsTexture(int superSize);public static Texture2D CaptureScreenshotAsTexture(StereoScreenCaptureMode stereoCaptureMode);//// 摘要://     Captures a screenshot of the game view into a RenderTexture object.//// 参数://   renderTexture://     RenderTexture that will get filled with the screen content.public static void CaptureScreenshotIntoRenderTexture(RenderTexture renderTexture);//// 摘要://     Enumeration specifying the eye texture to capture when using ScreenCapture.CaptureScreenshot//     and when stereo rendering is enabled.public enum StereoScreenCaptureMode{//// 摘要://     The Left Eye is captured. This is the default setting for the CaptureScreenshot//     method.LeftEye = 1,//// 摘要://     The Right Eye is captured.RightEye = 2,//// 摘要://     Both the left and right eyes are captured and composited into one image.BothEyes = 3}
}

在之前的用法上有新加了另外两种用法,一是将截图直接通过Texture2D获取;二是截图直接捕捉到RenderTexture中。
使用时,直接调用即可:UnityEngine.ScreenCapture.CaptureScreenshotAsTexture();

Texture2D.ReadPixels

使用Texture2D类的相关方法,来实现截图功能。可分给三种情况:视口截屏、RenderTextureWebCamTexture
而无论那种情况都可以总结成三行代码,即三个步骤:

  • 先创建一个的空纹理,大小可根据实现需要设置。Texture2D texture2D = new Texture2D(int width, int height);
  • 将相应的像素信息存储入这个新建的空纹理中。texture2D.ReadPixelstexture2D.SetPixels
  • 最后,将所有像素信息,“申请”成正式的Texture2D类对象。texture2D.Apply();

视口截图

使用Texture2D类的相关方法,来实现截图功能。代码如下:

/// <summary>
/// Captures the screenshot2.
/// </summary>
/// <returns>The screenshot2.</returns>
/// <param name="rect">Rect.截图的区域,左下角为o点</param>
Texture2D CaptureScreenshot2(Rect rect)
{Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);//先创建一个的空纹理,大小可根据实现需要来设置
#pragma warning disable UNT0017 // SetPixels invocation is slowscreenShot.ReadPixels(rect, 0, 0);//读取屏幕像素信息并存储为纹理数据,
#pragma warning restore UNT0017 // SetPixels invocation is slowscreenShot.Apply();byte[] bytes = screenShot.EncodeToPNG();//然后将这些纹理数据,成一个png图片文件string filename = Application.dataPath + "/Screenshot.png";System.IO.File.WriteAllBytes(filename, bytes);Debug.Log(string.Format("截屏了一张图片: {0}", filename));//最后,我返回这个Texture2d对象,这样我们直接,所这个截图图示在游戏中,当然这个根据自己的需求的。return screenShot;
}

与上面的ScreenCapture.CaptureScreenshot一样,这个方法也是对全屏截图。核心方法就是Texture2D.ReadPixels读取屏幕像素信息;Texture2D.Apply则是正式将其申请成为Texture2D;如有需要通过EncodeToPNG等函数,获取为位数组,用于保存为图片。
除截取全屏外,也可以通过对传入的参数Rect rect的大小操控,完成对整个游戏画面中,某个区域的截图。总体的说,就是整个视口的截图方法。

RenderTexture(Camera截图)

上面的方法都是全屏截图或全屏中的某块区域,那如何只截取场景中某个或某几个这相机的图像呢?
同样,使用Texture2D类的相关方法,就可以实现,代码如下:

/// <summary>
/// 对相机截图
/// </summary>
/// <param name="camera">Camera.要被截屏的相机</param>
/// <param name="rect">Rect.截屏的区域</param>
/// <returns>The screenshot2.</returns>
Texture2D CaptureCamera(Camera camera, Rect rect)
{RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);//创建一个RenderTexture对象camera.targetTexture = rt;//临时设置相关相机的targetTexture为rt, 并手动渲染相关相机camera.Render();//ps: --- 如果这样加上第二个相机,可以实现只截图某几个指定的相机一起看到的图像。//ps: camera2.targetTexture = rt;//ps: camera2.Render();//ps: -------------------------------------------------------------------RenderTexture.active = rt;//激活这个rt, 并从中中读取像素。Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);screenShot.ReadPixels(rect, 0, 0);//注:这个时候,它是从RenderTexture.active中读取像素screenShot.Apply();//重置相关参数,以使用camera继续在屏幕上显示camera.targetTexture = null;//ps: camera2.targetTexture = null;RenderTexture.active = null; //JC: added to avoid errorsGameObject.Destroy(rt);byte[] bytes = screenShot.EncodeToPNG();//最后将这些纹理数据,成一个png图片文件string filename = Application.dataPath + "/Screenshot.png";System.IO.File.WriteAllBytes(filename, bytes);Debug.Log(string.Format("截屏了一张照片: {0}", filename));return screenShot;
}

这个方法中用到了RenderTexture类,该类的用法,一般就是在项目中新建一个RenderTexture对象,然后拖拽到场景中对应的Camera组件的targetTexture位置,如下图所示:
Camera
代码中的前几行,实现的就是这个过程。然后通过系统的静态属性RenderTexture.active,使系统从对应的Camera上获取像素,然后再通过Texture2D.ReadPixelsTexture2D.Apply将截图保存成Texture2D对象,之后的操作就不用再多说了。
另外,新建RenderTexture类对象的过程可以用我刚刚提到的手动过程代替,我项目中就是这样使用的,代码如下:

/// <summary>
/// 头像截图
/// </summary>
public IEnumerator<string> CameraScreenshot()
{Debug.LogError("截取头像图片!");//文件名int hour = DateTime.Now.Hour;int minute = DateTime.Now.Minute;int second = DateTime.Now.Second;int year = DateTime.Now.Year;int month = DateTime.Now.Month;int day = DateTime.Now.Day;string name = string.Format("{0:D4}-{1:D2}-{2:D2}-{3:D2}-{4:D2}-{5:D2}", year, month, day, hour, minute, second);name += ".png";//截图RenderTexture.active = m_iconCamera.activeTexture;Texture2D texture2D = new Texture2D(m_iconCamera.activeTexture.width, m_iconCamera.activeTexture.height, TextureFormat.RGB24, false);Rect rect = new Rect(0, 0, m_iconCamera.activeTexture.width, m_iconCamera.activeTexture.height);texture2D.ReadPixels(rect, 0, 0);//注:这个时候,它是从RenderTexture.active中读取像素texture2D.Apply();yield return name;
#if UNITY_EDITORstring path = Application.streamingAssetsPath + "/Icon/" + name;
#elsestring path = Application.persistentDataPath + "/Icon/" + name;
#endifbyte[] pngData = texture2D.EncodeToPNG();//获取位数组File.WriteAllBytes(path, pngData);Debug.LogError("保存图片:" + path);
}

字段m_iconCamera就是场景中的有targetTexture的Camera。其原理与上面的是一样的。

WebCamTexture(摄像头截图、照相)

WebCamTexture类是Unity用于获取摄像头画面所做的系统类。其创建和使用的方法,通过搜索引擎可以找到很多,这我就不多说了。我是用其配合Texture2D类,做出照相的功能。
为了实现这个,配合上面提到的三个步骤,就是差了,如何获取像素信息。这个就是要用到WebCamTexture类的GetPixels方法,用于获取像素数据,即Color数组(也因此第二步这里使用的是texture2D.SetPixels)。
代码如下:

Texture2D texture2D = new Texture2D(m_texture.width, m_texture.height);
#pragma warning disable UNT0017 // SetPixels invocation is slow
texture2D.SetPixels(m_texture.GetPixels());
#pragma warning restore UNT0017 // SetPixels invocation is slow
texture2D.Apply();
byte[] pngData = texture2D.EncodeToPNG();//获取位数组

其中的m_texture字段就是WebCamTexture类对象。

参考链接

  1. https://blog.csdn.net/anyuanlzh/article/details/17008909
  2. https://blog.csdn.net/lawliet_lin/article/details/82382287

http://chatgpt.dhexx.cn/article/XSSgMZcY.shtml

相关文章

实现区域截图功能

利用QQ或微信自带的截图功能实现区域截图。 在腾讯安装目录下找到PrScrn.dll&#xff0c;并将它放在需要的位置&#xff0c; 将D:/PrScrn.dll修改为你的目录。 如果在maya里面直接使用该代码 import os,subprocess from PySide2.QtWidgets import QApplication clipboard …

小米手机怎么截屏?小米手机区域截屏

小米手机怎么截屏&#xff1f;手机的截屏其实都是差不多的&#xff0c;基本上都是三指向下滑动而达到截屏效果的&#xff0c;但基本都是全屏截图。小米手机区域截屏怎么做&#xff1f;如果想要做到任意位置的那种区域块截屏的话&#xff0c;该怎么做&#xff1f;下面就来看看吧…

浏览器截图方法(长截图、node截图、指定区域截图)

1.打开需要截屏的页面&#xff0c;按键盘上的F2&#xff08;或者CtrlShiftI&#xff09;打开浏览器控制台 2.CtrlshiftP进入搜索框&#xff0c;输入“screen”: 这里有四种截图模式&#xff0c;点击需要的截图方式即可截取图片。

Windows关闭指定端口命令

假设要关闭端口号为3003&#xff0c;使用下面的命令&#xff0c;查出此端口号对应的PID netstat -ano|findstr 3003 上图红框内的 22876 就是3003端口对应的PID&#xff0c;再使用下面的命令就可以关闭这个端口了 taskkill /PID 22876 /F

Linux关闭端口

netstat -anp | grep xxx //查看端口是否被占用kill -9 10762 //即可关闭端口

linux开放端口和关闭端口

centos6&#xff1a; 关闭防火墙:service iptables stop 开启防火墙:service iptables start 防火墙状态:service iptables status 永久关闭:chkconfig iptables off 永久开启:chkconfig iptables on 方法一(命令): 1. 开放端口命令&#xff1a; /sbin/iptables -I INPUT…

[NLP自然语言处理]谷歌BERT模型深度解析

BERT模型代码已经发布&#xff0c;可以在我的github: NLP-BERT--Python3.6-pytorch 中下载&#xff0c;请记得start哦 目录 一、前言 二、如何理解BERT模型 三、BERT模型解析 论文的核心&#xff1a;详解BERT模型架构 关键创新&#xff1a;预训练任务 实验结果 四、BERT模型…

深度学习:BERT模型

BERT模型 BERT出自https://arxiv.org/pdf/1810.04805.pdf的全称是Bidirectional Encoder Representation from Transformers&#xff0c;即双向Transformer的Encoder。作为一个Word2Vec的替代者&#xff0c;其在NLP领域的11个方向大幅刷新了精度&#xff0c;可以说是近年来自残…

BERT模型系列大全解读

前言 本文讲解的BERT系列模型主要是自编码语言模型-AE LM&#xff08;AutoEncoder Language Model&#xff09;&#xff1a;通过在输入X中随机掩码&#xff08;mask&#xff09;一部分单词&#xff0c;然后预训练的主要任务之一就是根据上下文单词来预测这些单词&#xff0c;从…

BERT模型的深度解读

一、BERT整体概要 Bert由两部分组成&#xff1a; 预训练&#xff08;Pre-training&#xff09;:通过两个联合训练任务得到Bert模型微调&#xff08;Fine-tune&#xff09;&#xff1a;在预训练得到bert模型的基础上进行各种各样的NLP 二、预训练 输入经过bert encoder层编…

BERT从零详细解读:BERT整体模型架构

基础结构-TRM的Encoder BERT使用多个Encoder堆叠在一起&#xff0c;其中bert base使用的是12层的encoder&#xff0c;bert large使用的是24层的encoder。 对于transformer来说&#xff0c;输入包括两个部分&#xff1a; 一部分是input enbedding&#xff0c;就是做词的词向量…

如何计算Bert模型的参数量

BERT是基于transformer结构的预训练模型。具体bert原理介绍&#xff0c;请参考博客&#xff1a;Bert系列解读及改进_&永恒的星河&的博客-CSDN博客_bert系列 求解Bert模型的参数量是面试常考的问题&#xff0c;也是作为算法工程师必须会的一个点。所谓会用并不代表熟悉…

关于Bert模型参数的分布

参数分布 Bert模型的版本如下&#xff1a; BERT-Base, Uncased: 12-layer, 768-hidden, 12-heads, 110M parameters BERT-Large, Uncased: 24-layer, 1024-hidden, 16-heads, 340M parameters BERT-Base, Cased: 12-layer, 768-hidden, 12-heads , 110M parameters BERT-L…

BERT模型原理的详细介绍

文章目录 参考文章1. BERT模型1.1 模型结构1.2 输入表示1.3 预训练任务1.3.1 Task 1:Masked Language Model1.3.2 Task 2&#xff1a;Next Sentence Prediction 1.4 微调(fine-tuning)基于句子对的分类任务基于单个句子的分类任务问答任务命名实体识别 2. 总结 参考文章 【NLP…

BERT和GPT模型简介

1. 引言 从现在的大趋势来看&#xff0c;使用某种模型预训练一个语言模型看起来是一种比较靠谱的方法。从之前 AI2 的 ELMo&#xff0c;到 OpenAI 的 fine-tune transformer&#xff0c;再到 Google 的 BERT、GPT&#xff0c;全都是对预训练的语言模型的应用。 本文将主要介绍…

BERT模型简介

基础架构-Transformer的Encoder&#xff1a; 由下到上&#xff0c;依次三个部分为输入、注意力机制和前馈神经网络 基础的Bert&#xff0c;六个encoder&#xff0c;六个decoder。 输入部分 input token embedding segment embedding position embedding bert预训练的NSP&am…

BERT 模型详解

BERT 结构 上图是 BERT 的结构图&#xff0c;左侧的图表示了预训练的过程&#xff0c;右边的图是对于具体任务的微调过程 BERT 的输入 BERT 的输入可以包含一个句子对 (句子 A 和句子 B)&#xff0c;也可以是单个句子。同时 BERT 增加了一些有特殊作用的标志位&#xff1a; …

如何从零开始训练BERT模型

我的许多文章都专注于 BERT——这个模型出现并主导了自然语言处理 (NLP) 的世界&#xff0c;标志着语言模型的新时代。 对于那些之前可能没有使用过 Transformer 模型&#xff08;例如 BERT 是什么&#xff09;的人&#xff0c;这个过程看起来有点像这样&#xff1a; pip 安装…

BERT模型详解

Auto-Regressive & Auto-Encoding 在介绍当下最火热的BERT模型之前&#xff0c;我们先来看两个概念&#xff0c;Auto-Regressive和Auto-Encoding。 Auto-Regressive Auto-Regressive如上图所示&#xff0c;其实很像是一个语言模型&#xff0c;遵循的是链式法则&#xff0…

BERT(预训练Transformer模型)

目录 一、前言 二、随机遮挡&#xff0c;进行预测 三、两句话是否原文相邻 四、两者结合起来 五、总结 六、参考链接 一、前言 Bert在18年提出&#xff0c;19年发表&#xff0c;Bert的目的是为了预训练Transformer模型encoder网络&#xff0c;从而大幅提高准确率 Bert …