CanvasSampleSaveFileImage.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System.IO;
  2. using System.Text;
  3. using System.Runtime.InteropServices;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. using UnityEngine.EventSystems;
  7. using SFB;
  8. [RequireComponent(typeof(Button))]
  9. public class CanvasSampleSaveFileImage : MonoBehaviour, IPointerDownHandler {
  10. public Text output;
  11. private byte[] _textureBytes;
  12. void Awake() {
  13. // Create red texture
  14. var width = 100;
  15. var height = 100;
  16. Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
  17. for (int i = 0; i < width; i++) {
  18. for (int j = 0; j < height; j++) {
  19. tex.SetPixel(i, j, Color.red);
  20. }
  21. }
  22. tex.Apply();
  23. _textureBytes = tex.EncodeToPNG();
  24. UnityEngine.Object.Destroy(tex);
  25. }
  26. #if UNITY_WEBGL && !UNITY_EDITOR
  27. //
  28. // WebGL
  29. //
  30. [DllImport("__Internal")]
  31. private static extern void DownloadFile(string gameObjectName, string methodName, string filename, byte[] byteArray, int byteArraySize);
  32. // Broser plugin should be called in OnPointerDown.
  33. public void OnPointerDown(PointerEventData eventData) {
  34. DownloadFile(gameObject.name, "OnFileDownload", "sample.png", _textureBytes, _textureBytes.Length);
  35. }
  36. // Called from browser
  37. public void OnFileDownload() {
  38. output.text = "File Successfully Downloaded";
  39. }
  40. #else
  41. //
  42. // Standalone platforms & editor
  43. //
  44. public void OnPointerDown(PointerEventData eventData) { }
  45. // Listen OnClick event in standlone builds
  46. void Start() {
  47. var button = GetComponent<Button>();
  48. button.onClick.AddListener(OnClick);
  49. }
  50. public void OnClick() {
  51. var path = StandaloneFileBrowser.SaveFilePanel("Title", "", "sample", "png");
  52. if (!string.IsNullOrEmpty(path)) {
  53. File.WriteAllBytes(path, _textureBytes);
  54. }
  55. }
  56. #endif
  57. }