先看代碼:
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; using System.Drawing; using System; /// <summary> /// 圖片壓縮工具 /// </summary> public class CompressPictureHelper :MonoBehaviour { private static CompressPictureHelper _instance; public static CompressPictureHelper Instance { get { if (_instance == null) { // 如果沒有找到 GameObject go = new GameObject ("_CompressPictureHelper"); // 創建一個新的GameObject DontDestroyOnLoad (go); // 防止被銷毀 _instance = go.AddComponent<CompressPictureHelper> (); // 將實例掛載到GameObject上 } return _instance; } } /// <summary> /// 圖片的限制大小 /// </summary> int limitI=300; /// <summary> /// Compresses the picture. /// </summary> /// <param name="imagePath">Image path.</param> /// <param name="action">成功返回原地址,失敗返回null.</param> public void CompressPicture(string imagePath,Action<string> action) { if (File.Exists(imagePath)) { FileInfo f = new FileInfo (imagePath); if ((f.Length/1024)>=limitI) { // Debug.Log ("開始壓縮,圖片原始大小為:" + f.Length/1000+"Kb"); StartCoroutine (Compress(imagePath,delegate(string str) { action(str); })); } } } IEnumerator Compress(string imagePath,Action<string>action) { int qualityI = 100; WWW www = new WWW ("file:///"+imagePath); yield return www; if (www.error!=null) { action (null); //發返回失敗 } else { Texture2D t2d = www.texture; byte[] b = t2d.EncodeToJPG (qualityI); // Debug.Log( "圖原始讀取的字節數 " + (b.Length/1000).ToString()); while((b.Length/1024)>=limitI) { qualityI -= 5; b = t2d.EncodeToJPG (qualityI); // Debug.Log ("當前大小:"+b.Length/1000); } // Debug.Log ("壓縮成功,當前大小:"+b.Length/1000); File.WriteAllBytes (imagePath,b); action (imagePath); } } }
注意點:
1 . myTexture2D.EncodeToJPG();
這里括號中如果不寫,會默認為75.
2 . 壓縮后的圖片會替代原路徑下的原文件