当前位置:   article > 正文

Unity批量压缩图片的功能实现_unity 批量压缩图片

unity 批量压缩图片

在不同平台下开发时,可能会遇到改变图片压缩格式的需求。这里把我之前实现的功能分享给各位。
可以学到的知识点如下:

  • 拿到原始图片的大小
  • 判断一个数是不是2的次幂
  • 编辑器扩展之增加菜单按钮、显示对话框、显示进度条
  • 安卓和IOS平台的图片压缩格式
public class TextureCompressOnPhone
{
    private const string AndroidPlatformName = "Android";

    private const string IOSPlatformName = "iPhone";
    
	[MenuItem( "Tools/Android/CompressTexture" )]
	private static void CompressTextureOnAndroid()
    {
        CompressInPlotform(AndroidPlatformName);
    }

    [MenuItem( "Tools/IOS/CompressTexture" )]
    private static void CompressTextureOnIOS()
    {
        CompressInPlotform(IOSPlatformName);
    }

    private static void CompressInPlotform( string platform )
    {
        var message = "You are going to perform the following operation to ALL Texture2D! Continue?\n";

        //弹出对话框进行二次确认
        if (EditorUtility.DisplayDialog("Change Max Size", message, "OK", "Cancel") == false)
        {
            return;
        }
        
        // 显示进度条
        EditorUtility.DisplayProgressBar("Change Max Size", "", 0.0f);
        
        // 找到所有纹理
        var guids = AssetDatabase.FindAssets("t:Texture2D");
        for (int i = 0; i < guids.Length; i++)
        {
            var dialogTitle = "Change Max Size" + " (" + i + "/" + guids.Length + ")";
            var progress = (float)i / guids.Length;
            var guid = guids[i];
            var path = AssetDatabase.GUIDToAssetPath(guid);
            var go = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
            if (go == null)
            {
                continue;
            }

            EditorUtility.DisplayProgressBar(dialogTitle, go.name, progress);

            //拿到TextureImporter才能对图片进行压缩
            var assetImporter = AssetImporter.GetAtPath(path);
            if (assetImporter != null)
            {
                var textureImporter = assetImporter as TextureImporter;
                if (textureImporter == null)
                {
                    Debug.LogWarningFormat(go, "MissingImporter Texture2D: '{0}'", go.name);
                    continue;
                }
                //拿到不压缩前的size
                var defaultMaxSize = textureImporter.maxTextureSize;
                TextureImporterPlatformSettings platformImporter = textureImporter.GetPlatformTextureSettings(platform);
                platformImporter.overridden = true;
                platformImporter.maxTextureSize = defaultMaxSize / 4;
                var width = 0;
                var height = 0;
                //拿到宽高
                GetTextureRealWidthAndHeight(textureImporter, ref width, ref height);

                //判断有无alpha
                var haveAlpha = textureImporter.DoesSourceTextureHaveAlpha();
                platformImporter.format = GetCompressFormat(platform, width, height, haveAlpha);

                textureImporter.SetPlatformTextureSettings(platformImporter);

                EditorUtility.SetDirty(go);
                Debug.LogFormat(go, "Processed Texture2D: '{0}'", go.name);
                textureImporter.SaveAndReimport();
            }
        }

        AssetDatabase.SaveAssets();
        EditorUtility.ClearProgressBar();
    }

    // 得到目标压缩格式
    private static TextureImporterFormat GetCompressFormat( string platform , int width, int height ,bool haveAlpha )
    {
    
        //分几种情况讨论,是不是2的次幂以及是不是有alpha通道
        var isPowerOfTwo = WidthAndHeightIsPowerOfTwo(width, height);
        if ( isPowerOfTwo == false )
        {
            if ( haveAlpha )
            {
                return TextureImporterFormat.RGBA16;
            }
            else
            {
                return TextureImporterFormat.RGB16;
            }
        }
        else
        {
            if ( platform == AndroidPlatformName )
            {
                if( haveAlpha )
                {
                    return TextureImporterFormat.ETC2_RGBA8Crunched;
                }
                else
                {
                    return TextureImporterFormat.ETC_RGB4Crunched;
                }
            }
            else if( platform == IOSPlatformName)
            {
                if( haveAlpha )
                {
                    return TextureImporterFormat.PVRTC_RGBA4;
                }
                else
                {
                    return TextureImporterFormat.PVRTC_RGB4;
                }
            }
        }
        return TextureImporterFormat.RGBA16;
    }
    
    // 判断宽和高是否是2的次幂
    private static bool WidthAndHeightIsPowerOfTwo( int width, int height )
    {
        if ( IsPowerOfTwo(width) && IsPowerOfTwo(height) )
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    //用二进制与运算,如果一个数是2的次幂,n&(n-1) = 0
    private static bool IsPowerOfTwo( int number )
    {
        if ( number <= 0 )
        {
            return false;
        }

        return ( number & ( number - 1 ) ) == 0;
    }

    //得到要压缩成几分之一,这里是二分之一
    private static int GetCompressedMaxSize( int sourceMaxSize )
	{
		return sourceMaxSize / 2;
	}
	
    //用反射得到纹理宽高
	public static void GetTextureRealWidthAndHeight( TextureImporter texImpoter, ref int width, ref int height )
	{
		System.Type type = typeof( TextureImporter );
		System.Reflection.MethodInfo method = type.GetMethod( "GetWidthAndHeight", BindingFlags.Instance | BindingFlags.NonPublic );
		var args = new object[] { width, height };
		method.Invoke( texImpoter, args );
		width = (int)args[0];
		height = (int)args[1];
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/636999
推荐阅读
相关标签
  

闽ICP备14008679号