Unity屏幕截图、区域截图、读取图片、WebGL长截屏并下载到本地jpg

news2025/3/1 3:15:51

Unity屏幕截图、区域截图、读取图片、WebGL长截屏并下载到本地jpg

一、全屏截图并保存到StreamingAssets路径下
   Texture2D screenShot;//保存截取的纹理
    public Image image;  //显示截屏的Image
 public void Jietu()
    {
         StartCoroutine(ScrrenCapture(new Rect(0, 0, Screen.width, Screen.height), 0));    
    }
    IEnumerator ScrrenCapture(Rect rect, int a)
    {

        screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
        yield return new WaitForEndOfFrame();
        screenShot.ReadPixels(rect, 0, 0);
        screenShot.Apply();

        yield return new WaitForSeconds(0.1f);

        Sprite sp = Sprite.Create(screenShot, new Rect(0, 0, screenShot.width, screenShot.height), new Vector2(0.5f, 0.5f), 100.0f);
        image.sprite = sp;
        
             //保存到streamingAssets
        byte[] bytes = screenShot.EncodeToJPG();
        string filename = Application.streamingAssetsPath + "/Images/Screenshot" + DateTime.UtcNow.Ticks + ".png";
        File.WriteAllBytes(filename, bytes);
            }
二、区域截图并保存到StreamingAssets路径下
  Texture2D screenShot;//保存截取的纹理
    public Image image;  //显示截屏的Image
    public Image im;
    Texture2D texture2ds;//存储的截图
     public void Jietu()
    {
        StartCoroutine(getScreenTexture(im.rectTransform));
    }
    public IEnumerator getScreenTexture(RectTransform rectT)
    {
        yield return new WaitForEndOfFrame();

        texture2ds = new Texture2D((int)rectT.rect.width, (int)rectT.rect.height, TextureFormat.RGB24, true);
        float x = rectT.localPosition.x + (Screen.width - rectT.rect.width) / 2;
        float y = rectT.localPosition.y + (Screen.height - rectT.rect.height) / 2;
        Rect position = new Rect(x, y, rectT.rect.width, rectT.rect.height);
        texture2ds.ReadPixels(position, 0, 0, true);//按照设定区域读取像素;注意是以左下角为原点读取
        texture2ds.Apply();
   Sprite sp = Sprite.Create(texture2ds, new Rect(0, 0, texture2ds.width, texture2ds.height), Vector2.zero);
        image.sprite = sp;
         //保存到streamingAssets
        byte[] bytes = texture2ds.EncodeToJPG();
        string filename = Application.streamingAssetsPath + "/Images/Screenshot" + DateTime.UtcNow.Ticks + ".png";
        File.WriteAllBytes(filename, bytes);
    }
三、unity发布WebGL屏幕长截屏并通过浏览器下载到本地jpg文件

在这里插入图片描述

using System.Collections;
using System.IO;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// unity发布WebGL屏幕长截屏并通过浏览器下载到本地jpg文件
/// </summary>
public class ScreenshotArea : MonoBehaviour
{
    [Header("截图区域")]
    public RectTransform screenshot_area;
    [Header("滚动条")]
    public Scrollbar scrollbar;
    [Header("截图数量")]
    public int number_max;
    [Header("每次截图滑动条vaule的位置,从下往上记")]
    public float[] number;
    [Header("是否横向合并")]
    public bool isHorizontal;

    Texture2D[] texture2ds;//存储的截图
    Texture2D merge_image;//合并后的图片
    string image_name="测试";//下载后图片的名字


    public RectTransform screenshot_area1;
    public RectTransform screenshot_area2;
    private void Start()
    {
        texture2ds = new Texture2D[number_max];
    }
    public void OnClick_调用()
    {
        Screen.fullScreen = true;
        StartCoroutine(getScreenTexture(screenshot_area));
    }

    #region 屏幕多次截图
    public IEnumerator getScreenTexture(RectTransform rectT)
    {
        scrollbar.value = number[0];
        yield return new WaitForEndOfFrame();

        for (int i = 0; i < number_max; i++)
        {
            texture2ds[i] = new Texture2D((int)rectT.rect.width, (int)rectT.rect.height, TextureFormat.RGB24, true);
            float x = rectT.localPosition.x + (Screen.width - rectT.rect.width) / 2;
            float y = rectT.localPosition.y + (Screen.height - rectT.rect.height) / 2;
            Rect position = new Rect(x, y, rectT.rect.width, rectT.rect.height);
            texture2ds[i].ReadPixels(position, 0, 0, true);//按照设定区域读取像素;注意是以左下角为原点读取
            texture2ds[i].Apply();

            if (i < number_max - 1)
                scrollbar.value = number[i + 1];
            if (i == 0)
            {
                rectT = screenshot_area;
            }
            if (i == number_max - 2)
            {
                rectT = screenshot_area1;
            }

            yield return new WaitForEndOfFrame();
        }
       
        merge_image = MergeImage(texture2ds); //图片合并
#if UNITY_EDITOR
        byte[] bytes = merge_image.EncodeToJPG();
        string filename = Application.streamingAssetsPath + "/Screenshot" + UnityEngine.Random.Range(0, 1000) + ".png";
        File.WriteAllBytes(filename, bytes);
#endif
        
        DownLoad(merge_image);//下载图片
    }
    #endregion
    #region 下载图片
    Sprite sprite;
    private void DownLoad(Texture2D screenShot)
    {
        sprite = Sprite.Create(screenShot, new Rect(0, 0, screenShot.width, screenShot.height), new Vector2(0.5f, 0.5f));

        byte[] photoByte = getImageSprite();//获取jpeg图像的字节流
        if (photoByte != null)
        {
            DownloadImage(photoByte, image_name+".jpg");
        }
        else
        {
            Debug.LogError("<color=red>下载失败</color>");
        }
    }
    private byte[] getImageSprite()
    {
        if (sprite)
        {
            return sprite.texture.EncodeToJPG();
        }
        return null;
    }
    #endregion
    #region 调用js方法下载
    [DllImport("__Internal")]
    private static extern void ImageDownloader(string str, string fn);
    public void DownloadImage(byte[] imageData, string imageFileName = "newpic")
    {
#if UNITY_EDITOR
        Debug.Log("<color=blue>编辑器无法下载</color>");
#else
        if (imageData != null)
        {
            Debug.Log("Downloading..." + imageFileName);
            ImageDownloader(System.Convert.ToBase64String(imageData), imageFileName);
        }
#endif
    }
    #endregion
    #region 合并多张图片
    public Texture2D MergeImage(Texture2D[] tex)
    {
        if (tex.Length == 0)
            return null;

        //定义新图的宽高, 合并分为两种情况水平方向合并、垂直方向合并
        int width = 0, height = 0;
        for (int i = 0; i < tex.Length; i++)
        {
            if (isHorizontal == false)
            {
                //新图的高度
                height += tex[i].height;
                if (i > 0)
                {
                    //新图的宽度,这里筛选为最宽
                    if (tex[i].width > tex[i - 1].width)
                    {
                        width = tex[i].width;
                    }
                }
                else width = tex[i].width; //只有一张图
            }
            else
            {
                //新图的宽度
                width += tex[i].width;
                if (i > 0)
                {
                    //新图的高度,这里筛选为最高
                    if (tex[i].height > tex[i - 1].height)
                    {
                        height = tex[i].height;
                    }
                }
                else height = tex[i].height; //只有一张图
            }
        }
        //初始Texture2D
        Texture2D texture2D = new Texture2D(width, height);
        int x = 0, y = 0;
        for (int i = 0; i < tex.Length; i++)
        {
            //取图
            Color32[] color = tex[i].GetPixels32(0);

            //赋给新图
            if (i > 0)
            {
                if (isHorizontal == false)
                {
                    texture2D.SetPixels32(x, y += tex[i - 1].height, tex[i].width, tex[i].height, color); //高度
                }
                else
                {
                    texture2D.SetPixels32(x += tex[i - 1].width, y, tex[i].width, tex[i].height, color); //宽度
                }
            }
            else
            {
                texture2D.SetPixels32(x, y, tex[i].width, tex[i].height, color);
            }
        }
        //应用
        texture2D.Apply();
        return texture2D;
    }
    #endregion
}
四、调用js方法下载图片

在Plugins文件夹下新建

ImageDownloader.jslib

放入下面代码

var ImageDownloaderPlugin = {
    ImageDownloader: function (str, fn) {
        console.log("start jslib download");
        var msg = UTF8ToString(str);
        var fname = UTF8ToString(fn);
        var contentType = 'image/jpeg';

        function fixBinary(bin) {
            var length = bin.length;
            var buf = new ArrayBuffer(length);
            var arr = new Uint8Array(buf);
            for (var i = 0; i < length; i++) {
                arr[i] = bin.charCodeAt(i);
            }
            return buf;
        }
        var binary = fixBinary(atob(msg));
        var data = new Blob([binary], { type: contentType });
        var link = document.createElement('a');
        link.download = fname;
        link.innerHTML = 'DownloadFile';
        link.setAttribute('id', 'ImageDownloaderLink');
        link.href = window.URL.createObjectURL(data);
        link.onclick = function () {
            var child = document.getElementById('ImageDownloaderLink');
            child.parentNode.removeChild(child);
        };
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        window.URL.revokeObjectURL(link.href);
    }
};
mergeInto(LibraryManager.library, ImageDownloaderPlugin)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2259161.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【2025最新计算机毕业设计】基于SprintBoot+Vue乡村振兴民宿管理系统【提供源码+答辩PPT+文档+项目部署】

作者简介&#xff1a;✌CSDN新星计划导师、Java领域优质创作者、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和学生毕业项目实战,高校老师/讲师/同行前辈交流。✌ 主要内容&#xff1a;&#x1f31f;Java项目、Python项目、前端项目、PHP、ASP.NET、人工智能…

在Docker中运行MySQL的思考:挑战与解决方案

引言 在云计算和容器化技术日益普及的今天&#xff0c;Docker作为一种轻量级的容器化平台&#xff0c;已经成为开发和部署应用的首选工具之一。其提供的便携性、可扩展性和环境一致性对于无状态微服务来说无疑是巨大的福音。然而&#xff0c;并非所有应用都适合在Docker容器中…

【Linux网络】网络基础:传输层TCP协议(二)

&#x1f4dd;个人主页&#x1f339;&#xff1a;Eternity._ ⏩收录专栏⏪&#xff1a;Linux “ 登神长阶 ” &#x1f339;&#x1f339;期待您的关注 &#x1f339;&#x1f339; ❀ 传输层UDP/TCP协议 确认应答机制超时重传机制连接管理机制理解 TIME_WAIT 状态 滑动窗口流量…

virtualbox 搭建ubuntu

环境&#xff1a;VirtualBox-6.1.32 1、下载安装virtualbox 略 2、新建ubuntu 3、配置ubuntu 选择虚拟盘 4、安装ubuntu 5、安装ssh sudo apt install openssh-server openssh-client 查看ip 6、安装samba sudo apt install samba 查看ssh启动状态 sudo systemctl stat…

智能人体安全防护:3D 视觉技术原理、系统架构与代码实现剖析

随着工业化程度的提高&#xff0c;生产安全已成为企业关注的重点。尤其是在一些存在禁区的工业厂区和车间&#xff0c;人员误入或违规进入将带来严重的安全隐患。为了解决这一问题&#xff0c;迈尔微视推出了智能人体安全检测解决方案&#xff0c;为企业提供全方位的人员安全监…

Javaweb web后端maven介绍作用安装

自动导入到这个项目 src是源代码 main主程序&#xff0c;核心代码 java是Java源代码 resources是项目配置文件 test测试相关的 maven概述 介绍 依赖在本地仓库查找&#xff0c;如果本地仓库有&#xff0c;用本地仓库的依赖&#xff0c;本地没有&#xff0c;连接中央仓库&…

独家原创 | CEEMDAN-CNN-GRU-GlobalAttention + XGBoost组合预测

往期精彩内容&#xff1a; 时序预测&#xff1a;LSTM、ARIMA、Holt-Winters、SARIMA模型的分析与比较 全是干货 | 数据集、学习资料、建模资源分享&#xff01; EMD变体分解效果最好算法——CEEMDAN&#xff08;五&#xff09;-CSDN博客 拒绝信息泄露&#xff01;VMD滚动分…

网络基础概念

协议 协议在我的理解看来其实就是为了让全部计算机做通信而设计出来的一种约定 计算机之间的传输媒介是光信号和电信号. 通过 "频率" 和 "强弱" 来表示 0 和 1 这样的信息. 要想传递各种不同的信息, 就需要约定好双方的数据格式 而制定协议这件事情并不是…

向量数据库Faiss C++

目录 1. Faiss简介2. FAISS 的主要特点2.1 高效性2.2 支持多种索引类型2.3 灵活性2.4 GPU 加速2.5 易于集成 3. 应用场景4. 安装4.1 安装依赖4.2 编译源码4.2.1 下载Faiss源码4.2.2 编译 5. Demo5.1 代码5.2 编译5.3 运行 1. Faiss简介 FAISS&#xff08;Facebook AI Similari…

群控系统服务端开发模式-应用开发-获取登录者今天操作日志

一、后端api开放路由 在根目录下route文件夹下app.php文件中&#xff0c;在perimission的group中添加如下代码&#xff1a; Route::get(member/personal_log,permission.Member/personalLog);// 获取个人信息操作接口 二、后端api添加方法 在根目录下app文件夹下controller文…

淘宝/天猫获得淘宝商品详情高级版 API 接口获取

要获取淘宝/天猫商品详情高级版API接口&#xff0c;您可以按照以下步骤操作&#xff1a; 注册淘宝开放平台账号&#xff1a; 访问淘宝开放平台官网&#xff0c;点击“开发者中心”&#xff0c;使用淘宝账号登录或注册新账号。这是获取API权限和密钥的第一步。 创建应用并获取AP…

腾讯云系统盘扩容

在腾讯云申请空间后&#xff0c;只要执行三行命令 云硬盘 在线扩展系统盘分区及文件系统-操作指南-文档中心-腾讯云 安装工具 yum install -y cloud-utils-growpart 给/eav/vda1扩分区 LC_ALLen_US.UTF-8 growpart /dev/vda 1 挂载扩容 ext4 文件系统 resize2fs /dev/vda1 …

数据结构 ——二叉树转广义表

数据结构 ——二叉树转广义表 1、树转广义表 如下一棵树&#xff0c;转换为广义表 root(c(a()(b()()))(e(d()())(f()(j(h()())())))) (根&#xff08;左子树&#xff09;&#xff08;右子树&#xff09;) 代码实现 #include<stdio.h> #include<stdlib.h>//保存…

人工智能大语言模型起源篇(二),从通用语言微调到驾驭LLM

上一篇&#xff1a;《人工智能大语言模型起源篇&#xff08;一&#xff09;&#xff0c;从哪里开始》 &#xff08;5&#xff09;Howard 和 Ruder 于2018年发表的《Universal Language Model Fine-tuning for Text Classification》&#xff0c;https://arxiv.org/abs/1801.06…

设置笔记本同时连接内外网

原理&#xff1a;通过笔记本和手机相连&#xff0c;实现双网卡功能能。笔记本连接内网wifi、同时手机端开启usb网络共享&#xff0c;笔记本就有了两个网&#xff0c;然配置那个访问外网&#xff0c;那个访问内网。 1.笔记本wifi连接内网wifi 2.手机端共享网络。 手机打开 -【…

【Hexo】Hexo基本使用

Hexo官网&#xff1a;https://hexo.io/ Hexo Github: https://github.com/hexojs/hexo Hexo Awesome: https://github.com/hexojs/awesome-hexo 1、初始化 需要node 环境&#xff0c;不再赘述node安装过程 推荐使用cnpm进行安装 npm install -g cnpm --registryhttps://regi…

PPO系列4 - Reward模型训练

流程&#xff1a; 训练Reward模型 训练数据&#xff1a; 相比给每条回答进行打分&#xff0c;人类更容易给出两者的比较结果。这样标注出来的数据&#xff0c;准确性更高。 模型&#xff1a; 可以使用和生成模型能力差不多的模型&#xff08;或者更强的模型&#xff09;&#x…

5.11如何用PyTorch实现ResNet34

ResNet34是由16个残差块和一个全局平局池化层和一个全连接层组成&#xff0c;即32个卷积层1个pooling层1和fc层。 训练的数据集是cifar10数据集&#xff0c;训练次数5&#xff0c;损失函数为CrossEntropyLoss()&#xff0c;optimizer torch.optim.SGD。 1.先定义残差块&#…

yolov,coco,voc标记的睡岗检测数据集,可识别在桌子上趴着睡,埋头睡觉,座椅上靠着睡,平躺着睡等多种睡姿的检测,6549张图片

yolov&#xff0c;coco,voc标记的睡岗检测数据集&#xff0c;可识别在桌子上趴着睡&#xff0c;埋头睡觉&#xff0c;座椅上靠着睡&#xff0c;平躺着睡等多种睡姿的检测&#xff0c;6549张图片 数据集分割 6549总图像数 训练组91&#xff05; 5949图片 有效集9&#x…

【C++游记】string的使用和模拟实现

枫の个人主页 你不能改变过去&#xff0c;但你可以改变未来 算法/C/数据结构/C Hello&#xff0c;这里是小枫。C语言与数据结构和算法初阶两个板块都更新完毕&#xff0c;我们继续来学习C的内容呀。C是接近底层有比较经典的语言&#xff0c;因此学习起来注定枯燥无味&#xf…