Unity 一键修改图片缩放保存为当前的一半大小
用来压缩贴图大小还是比较方便的 支持 png,jpg,tga
话不多说 直接上代码
[MenuItem("Assets/扩展功能/缩放贴图一半尺寸(png | jpg | tga)", false)]static void ScaleHalfTextureSizeMenu(){foreach(var obj in Selection.objects) {Texture texObj = obj as Texture;if(texObj != null) {ScaleHalfTextureSize(texObj);}}}static void ScaleHalfTextureSize(Texture texAsset){if(texAsset == null) {return;}string texAssetPath = AssetDatabase.GetAssetPath(texAsset);string texPathExten = System.IO.Path.GetExtension(texAssetPath).ToLower();bool isTexJPG = texPathExten == ".jpg";bool isTexPNG = texPathExten == ".png";bool isTexTga = texPathExten == ".tga";if (!isTexJPG && !isTexPNG && !isTexTga) {Debug.LogError("不支持的图片格式-->" + texPathExten);return;}int width = texAsset.width;int height = texAsset.height;TextureFormat textureFormat = TextureFormat.RGBA32;Texture2D unCompressOriginTex;if (isTexTga){unCompressOriginTex = AssetDatabase.LoadAssetAtPath<Texture2D>(texAssetPath);}else{texAssetPath = Application.dataPath + texAssetPath.Remove(0, "Assets".Length);byte[] originByteDataArray = System.IO.File.ReadAllBytes(texAssetPath);unCompressOriginTex = new Texture2D(width, height, textureFormat, false);unCompressOriginTex.LoadImage(originByteDataArray, false);unCompressOriginTex.filterMode = FilterMode.Bilinear;unCompressOriginTex.wrapMode = TextureWrapMode.Clamp;unCompressOriginTex.Apply(false, true);}int halfWidth = width / 2;int halfHeight = height / 2;RenderTexture tempRT = RenderTexture.GetTemporary(halfWidth, halfHeight, 0, RenderTextureFormat.ARGB32);Graphics.Blit(unCompressOriginTex, tempRT);Texture2D halfSizeTex = new Texture2D(halfWidth, halfHeight, textureFormat, false);RenderTexture.active = tempRT;halfSizeTex.ReadPixels(new Rect(0, 0, halfWidth, halfHeight), 0, 0);if (isTexJPG) {System.IO.File.WriteAllBytes(texAssetPath, halfSizeTex.EncodeToJPG());}else if (isTexPNG) {System.IO.File.WriteAllBytes(texAssetPath, halfSizeTex.EncodeToPNG());}else if (isTexTga){System.IO.File.WriteAllBytes(texAssetPath, halfSizeTex.EncodeToTGA());}AssetDatabase.Refresh();RenderTexture.ReleaseTemporary(tempRT);if (isTexTga){//不能销毁}else{Object.DestroyImmediate(unCompressOriginTex);} Object.DestroyImmediate(halfSizeTex);}
效果