Singularity/Assets/Scripts/BackgroundImageHandler.cs
2024-05-06 11:45:45 -07:00

77 lines
2.6 KiB
C#

using System;
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class BackgroundImageHandler : MonoBehaviour
{
[SerializeField] private string BackgroundImage;
[SerializeField] private RawImage Background;
[SerializeField] private RawImage ModListBackground;
[SerializeField] private RawImage OriginalBackground;
[SerializeField] private string ImagePath;
void Start() {
ImagePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)+@"\Schaken-Mods®\Singularity\Background.png";
if (File.Exists(ImagePath)) {
StartCoroutine(LoadImage(ImagePath, Background, false));
StartCoroutine(LoadImage(ImagePath, ModListBackground, false));
}
}
public void SetNewImageFromClipboard() {
if (!GUIUtility.systemCopyBuffer.Contains("http") ) {
Background.texture = ClipboardImage.Copy();
Background.SetNativeSize();
Background.SizeToParent();
SaveImageToFile(Background.texture as Texture2D);
} else {
StartCoroutine(LoadImage(GUIUtility.systemCopyBuffer, Background));
StartCoroutine(LoadImage(GUIUtility.systemCopyBuffer, ModListBackground));
}
}
public void ImportImageDragNDrop(string file) {
StartCoroutine(LoadImage(file, Background));
StartCoroutine(LoadImage(file, ModListBackground));
}
private IEnumerator LoadImage(string B, RawImage A, bool TF = true) {
UnityWebRequest WWW = UnityWebRequestTexture.GetTexture(B);
yield return WWW.SendWebRequest();
if (WWW.result != UnityWebRequest.Result.ConnectionError) {
A.texture = DownloadHandlerTexture.GetContent(WWW);
A.SetNativeSize();
A.SizeToParent();
A.gameObject.SetActive(true);
if (TF)
SaveImageToFile(A.texture as Texture2D);
}
}
public void SaveImageToFile(Texture2D texture) {
if (texture != null) {
byte[] pngData = texture.EncodeToPNG();
if (File.Exists(ImagePath)) {
File.Delete(ImagePath);
}
File.WriteAllBytes(ImagePath, pngData);
} else {
Debug.LogError("The texture is null.");
}
}
public void ApplyOriginalImageToBackground() {
if (OriginalBackground != null && Background != null) {
Background.texture = OriginalBackground.texture;
} else {
Debug.LogError("originalImage or backgroundImage is not assigned.");
}
if (File.Exists(ImagePath)) {
File.Delete(ImagePath);
}
}
}