うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】UnityEditor 上で指定した URL から画像を取得して保存する処理

#if UNITY_EDITOR
 
using System.IO;
using System.Collections;
using Unity.EditorCoroutines.Editor;
using UnityEditor;
using UnityEngine;
using UnityEngine.Networking;
 
public static class DownloadAndSaveImageEditor
{
    // URLから画像をダウンロードして保存する
    [MenuItem("Custom/Download And Save Image")]
    public static void DownloadAndSave()
    {
        string imageUrl = EditorGUIUtility.systemCopyBuffer;
        string pathToSaveImage = Application.dataPath;
        EditorCoroutineUtility.StartCoroutineOwnerless(DownloadAndSaveRoutine(imageUrl, pathToSaveImage, (texture) =>
        {
            Debug.Log("Image saved!");
        }));
    }
     
    public static IEnumerator DownloadAndSaveRoutine(string imageUrl, string pathToSaveImage, System.Action<Texture2D> onCompleted)
    {
        using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(imageUrl))
        {
            yield return www.SendWebRequest();
            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.Log(www.error);
            }
            else
            {
                // Get downloaded asset bundle
                var texture = DownloadHandlerTexture.GetContent(www);
                byte[] bytes;
                bytes = texture.EncodeToPNG();
                string path = Path.Combine(pathToSaveImage, "DownloadedImage.png");
                File.WriteAllBytes(path, bytes);
                onCompleted?.Invoke(texture);
            }
        }
    }
}
 
#endif