Unity3D中截圖並修改圖片畫素重新儲存至本地
阿新 • • 發佈:2019-02-18
第一次開始寫部落格,想把自己在平時遇到的一點小問題記錄下來,也方便其他人蔘考
最近在用Unity3D做一個綠幕摳像的應用(囧一個,不要問我為什麼用unity3D做),過程中需要對圖片進行一些處理。
首先你需要一個 System.Drawing.dll。對image進行操作,這個dll檔案在unity目錄下可以搜到,如果找不到在下方下載。說明我的unity版本是5.3.5,如果dll錯誤,或者是版本差異過大,或者是你的這個dll檔案是從其他地方拷過來的有可能會出一些bug。在byte[]轉image時會導致unity崩潰。
下面附上第一步截圖操作
public IEnumerator Capture2() { System.DateTime now = System.DateTime.Now; Rect rect = new Rect(); // 先建立一個的空紋理,大小可根據實現需要來設定 rect.width = Screen.width; rect.height = Screen.height; Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false); // 讀取螢幕畫素資訊並存儲為紋理資料 yield return new WaitForEndOfFrame(); screenShot.ReadPixels(rect, 0, 0, false); screenShot.Apply(); // 然後將這些紋理資料,成一個png圖片檔案 byte[] bytes = screenShot.EncodeToPNG(); Image image = GetImage(bytes);//這裡做 byte[] 轉 image string filename = Application.streamingAssetsPath +"/"+now.Year+now.Month+now.Day+now.Hour+now.Minute+now.Second+ ".jpg"; //以時間結尾命名圖片 //這裡對image進行重新繪製,注意用image.save方法,如果使用io進行寫入操作圖片格式會出錯,不能再次讀取,這裡我儲存的是jpg格式照片 KiResizeImage(new Bitmap( image), Width, Height).Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg); Debug.Log(string.Format("截圖了一張圖片: {0}", filename)); } // <summary> // 二進位制陣列轉image public Image GetImage(Byte[] byteArrayIn) { if (byteArrayIn == null) return null; using (System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArrayIn)) { System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms); ms.Flush(); return returnImage; } } // Resize圖片 // 原始Bitmap // 新的寬度 // 新的高度 // 處理以後的圖片 public static Bitmap KiResizeImage(Bitmap bmp, int newW, int newH) { try { Bitmap b = new Bitmap(newW, newH); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(b); // 插值演算法的質量 g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel); g.Dispose(); return b; } catch { return null; } }