using System.IO;
using UnityEditor;
using UnityEngine;

public class ImageImporter : MonoBehaviour
{
    public static Texture2D ImportImage()
    {
        string path = EditorUtility.OpenFilePanel("Select the image file to import", "", "png,jpg,jpeg,bmp,tga");
        if (string.IsNullOrEmpty(path))
        {
            return null;
        }

        //copyļָĿ¼
        string destination = "Assets/DEETools/Res/Images/" + Path.GetFileName(path);
        if (!Directory.Exists("Assets/DEETools/Res/Images"))
        {
            Directory.CreateDirectory("Assets/DEETools/Res/Images");
        }
        //ͬļ
        while (File.Exists(destination))
        {
            destination = "Assets/DEETools/Res/Images/" + Path.GetFileNameWithoutExtension(destination) + "_1" + Path.GetExtension(path);
        }
        File.Copy(path, destination, true);
        AssetDatabase.Refresh();
        TextureImporter textureImporter = AssetImporter.GetAtPath(destination) as TextureImporter;
        textureImporter.textureType = TextureImporterType.Sprite;
        textureImporter.alphaIsTransparency = false;
        textureImporter.mipmapEnabled = true;
        textureImporter.SaveAndReimport();
        AssetDatabase.SaveAssets();
        Debug.Log("Image file has been successfully imported to: " + destination);
        return AssetDatabase.LoadAssetAtPath<Texture2D>(destination);
    }
}
