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

news/2024/12/19 17:09:30/

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

一、全屏截图并保存到StreamingAssets路径下
   Texture2D screenShot;//保存截取的纹理public Image image;  //显示截屏的Imagepublic 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;//保存到streamingAssetsbyte[] bytes = screenShot.EncodeToJPG();string filename = Application.streamingAssetsPath + "/Images/Screenshot" + DateTime.UtcNow.Ticks + ".png";File.WriteAllBytes(filename, bytes);}
二、区域截图并保存到StreamingAssets路径下
  Texture2D screenShot;//保存截取的纹理public Image image;  //显示截屏的Imagepublic 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;//保存到streamingAssetsbyte[] bytes = texture2ds.EncodeToJPG();string filename = Application.streamingAssetsPath + "/Images/Screenshot" + DateTime.UtcNow.Ticks + ".png";File.WriteAllBytes(filename, bytes);}
unityWebGLjpg_65">三、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_EDITORbyte[] bytes = merge_image.EncodeToJPG();string filename = Application.streamingAssetsPath + "/Screenshot" + UnityEngine.Random.Range(0, 1000) + ".png";File.WriteAllBytes(filename, bytes);
#endifDownLoad(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_EDITORDebug.Log("<color=blue>编辑器无法下载</color>");
#elseif (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; //只有一张图}}//初始Texture2DTexture2D 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.ppmy.cn/news/1556434.html

相关文章

StarRocks:存算一体模式部署

目录 一、StarRocks 简介 二、StarRocks 架构 2.1 存算一体 2.2 存算分离 三、前期准备 3.1前提条件 3.2 集群规划 3.3 配置环境 3.4 准备部署文件 四、手动部署 4.1 部署FE节点 4.2 部署BE节点 4.3 部署CN节点&#xff08;可选&#xff09; 4.4 FE高可用…

Redis篇-11--数据结构篇3--字符串内存模型(简单动态字符串SDS)

Redis 5 中的基础数据类型包括字符串&#xff08;String&#xff09;、列表&#xff08;List&#xff09;、集合&#xff08;Set&#xff09;、有序集合&#xff08;Sorted Set&#xff09;和哈希&#xff08;Hash&#xff09;。每种数据类型的底层结构和优化机制都经过了精心设…

HTTP 协议报文结构 | 返回状态码详解

注&#xff1a;本文为 “HTTP 历史 | 协议报文结构 | 返回状态码” 相关文章合辑。 未整理去重。 HTTP 历史 wangjunliang 最后更新: 2024/3/16 上午10:29 超文本传输协议(英语:HyperTextTransferProtocol,缩写:HTTP)是 万维网(World Wide Web)的基础协议&#xff61;自 蒂姆…

gitlab代码推送

点击这个√ 修改的文件全部选上 填好提交的名称 点击commit 选取提交的 gitlab 库 点击Push

芯片级IO (Pad) Ring IP Checklist

SoC top顶层数字后端实现都会涉及到IO Ring &#xff08;PAD Ring&#xff09;的设计。这里面包括VDD IO,VDDIO IO, Signal IO, Corner IO&#xff0c;Filler IO&#xff0c;IO power cut cell等等。 数字后端零基础入门系列 | Innovus零基础LAB学习Day2 数字IC后端实现TOP F…

BigBlueButton有哪些优点和缺点

BigBlueButton有哪些优点和缺点 作者&#xff1a;BBBEasy中国区团队&#xff0c;Github地址&#xff1a;https://github.com/lihaiya/bbbeasy BigBlueButton作为一个开源的在线会议和协作平台&#xff0c;在教育、企业等多个领域得到了广泛应用。以下是BigBlueButton的优点和…

如何部署和配置项目管理工具 Plane - 开源 Jira 替代方案

简介 Plane 是一个高度可扩展的开源项目管理工具&#xff0c;支持多种框架类型&#xff0c;如敏捷、看板、瀑布和时间线。它是 Jira、Asana 和 Linear 等平台的替代方案&#xff0c;允许您使用 Docker 或 Kubernetes 等工具在容器化环境中自托管所有应用程序资源。 本指南将介…

Vue.js前端框架教程5:Vue数据拷贝和数组函数

文章目录 Vue数组函数 filtermapreducelength使用示例Vue 拷贝展开运算符 (...)Object.assign()JSON.stringify() 和 JSON.parse()注意事项 Vue数组函数 在 Vue 中&#xff0c;处理列表时经常需要用到数组的内置方法&#xff0c;如 filter、map、reduce 以及检查数组长度的 le…