Unity3D中截图并修改图片像素重新保存至本地

来源:互联网 发布:如何下载matlab软件 编辑:程序博客网 时间:2024/05/21 02:48

第一次开始写博客,想把自己在平时遇到的一点小问题记录下来,也方便其他人参考

最近在用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;        }    }
                                             
0 0
原创粉丝点击