提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- 一、编写jslib
- 二、c#代码
- 1.引入插件
- 2.测试调用
- 总结
前言
提示:这里可以添加本文要记录的大概内容:
尊重原著:
原文链接: https://blog.csdn.net/Wrinkle2017/article/details/117660124
以下方法都可以搭配本文使用:
截图的方法:
链接: unity 自由框选截图(两种方法,亲测有效)
模型生成PNG图片:
链接: unity 模型生成PNG图片并导出(可以任意控制方向和大小,本文提供三种方案)
截图拼接,下载PDF:
链接: unity(WebGL) 截图拼接并保存本地,下载PDF
一、编写jslib
新建一个文本复制一下代码,并修改后缀(.jslib):
把这个jslib丢到Plugins目录下,这样它就会作为插件引入Unity
ImageDownloader.jslib
//调用浏览器的下载var ImageDownloaderPlugin = {ImageDownloader: function (str, fn) {console.log("start jslib download");var msg = Pointer_stringify(str);var fname = Pointer_stringify(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;}//atob解码使用base64编码的字符串var binary = fixBinary(atob(msg));var data = new Blob([binary], { type: contentType });//创建一个html dom用于触发blob下载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);}};//并入Unity中,官方写法。mergeInto(LibraryManager.library, ImageDownloaderPlugin)
二、c#代码
1.引入插件
[DllImport("__Internal")]private static extern void ImageDownloader(string str, string fn);public void DownloadImage(byte[] imageData, string imageFileName = "newpic"){if (imageData != null) {Debug.Log("Downloading..." + imageFileName);ImageDownloader(System.Convert.ToBase64String(imageData), imageFileName);}}
2.测试调用
using System;using System.Collections;using System.Collections.Generic;using UnityEngine;public class TestJPEGDownload : MonoBehaviour{public Sprite sprite;public UnityEngine.UI.Button button;private void Start(){button.onClick.AddListener(this.onButtonClick);}private void onButtonClick(){byte[] photoByte = getImageSprite();//获取jpeg图像的字节流if (photoByte != null) {DownloadImage(photoByte, sprite.name + ".jpg");}else{Debug.LogError("不得了");}}private byte[] getImageSprite(){if (sprite) {return sprite.texture.EncodeToJPG();}return null;}}
总结
感谢https://blog.csdn.net/Wrinkle2017/article/details/117660124 大神的无私贡献!