You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
84 lines
2.3 KiB
84 lines
2.3 KiB
11 months ago
|
using System.Text;
|
||
|
using System.Collections;
|
||
|
using System.Collections.Generic;
|
||
|
using System.Runtime.InteropServices;
|
||
|
using UnityEngine;
|
||
|
using UnityEngine.UI;
|
||
|
using UnityEngine.EventSystems;
|
||
|
using SFB;
|
||
|
using UnityEngine.Events;
|
||
|
using UniRx;
|
||
|
using System;
|
||
|
using UnityEngine.Networking;
|
||
|
|
||
|
[RequireComponent(typeof(Button))]
|
||
|
public class OpenImage : MonoBehaviour, IPointerDownHandler
|
||
|
{
|
||
|
public Image Output;
|
||
|
public UnityAction<Texture2D> OnLoadTextureFinished;
|
||
|
public bool PreserveAspect = true;
|
||
|
|
||
|
//public ViewOriginalImage OriginalImage;
|
||
|
|
||
|
#if UNITY_WEBGL && !UNITY_EDITOR
|
||
|
//
|
||
|
// WebGL
|
||
|
//
|
||
|
[DllImport("__Internal")]
|
||
|
private static extern void UploadFile(string gameObjectName, string methodName, string filter, bool multiple);
|
||
|
|
||
|
public void OnPointerDown(PointerEventData eventData) {
|
||
|
if(eventData.button== PointerEventData.InputButton.Left)
|
||
|
{
|
||
|
UploadFile(gameObject.name, "OnFileUpload", ".png, .jpg,.bmp", false);
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
// Called from browser
|
||
|
public void OnFileUpload(string url) {
|
||
|
StartCoroutine(OutputRoutine(url));
|
||
|
}
|
||
|
#else
|
||
|
public void OnPointerDown(PointerEventData eventData)
|
||
|
{
|
||
|
}
|
||
|
// Start is called before the first frame update
|
||
|
void Start()
|
||
|
{
|
||
|
GetComponent<Button>().OnClickAsObservable()
|
||
|
.Subscribe(_ => OnClick());
|
||
|
}
|
||
|
|
||
|
private void OnClick()
|
||
|
{
|
||
|
var extensions = new[] {
|
||
|
new ExtensionFilter("Image Files", "png", "jpg", "jpeg" ),
|
||
|
};
|
||
|
var paths = StandaloneFileBrowser.OpenFilePanel("Title", "", extensions, false);
|
||
|
if (paths.Length > 0)
|
||
|
{
|
||
|
StartCoroutine(OutputRoutine(new Uri(paths[0]).AbsoluteUri));
|
||
|
}
|
||
|
}
|
||
|
#endif
|
||
|
private IEnumerator OutputRoutine(string url)
|
||
|
{
|
||
|
UnityWebRequest uwr = new UnityWebRequest(url);
|
||
|
DownloadHandlerTexture downloadTexture = new DownloadHandlerTexture(true);
|
||
|
uwr.downloadHandler = downloadTexture;
|
||
|
yield return uwr.SendWebRequest();
|
||
|
if (!(uwr.isNetworkError || uwr.isHttpError))
|
||
|
{
|
||
|
var loader = downloadTexture.texture;
|
||
|
Output.sprite = Sprite.Create(loader, new Rect(0, 0, loader.width, loader.height), Vector2.zero);
|
||
|
Output.preserveAspect = PreserveAspect;
|
||
|
|
||
|
OnLoadTextureFinished?.Invoke(loader);
|
||
|
|
||
|
}
|
||
|
}
|
||
|
|
||
|
|
||
|
}
|