首页 > 学院 > 开发设计 > 正文

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

2019-11-06 08:05:06
字体:
来源:转载
供稿:网友

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

最近在用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";   //以时间结尾命名图片        string filename = Application.streamingAssetsPath + "/" + SetFileName() + ".jpg"; //以PlayerPRefs存储命名图片
	//这里对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    /// </summary>    /// <param name="byteArrayIn"></param>    /// <returns></returns>    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;        }    } 应该米有什么遗漏,如果有问题可以给我留言,


上一篇:HDU1282 回文数猜想

下一篇:十二、####

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表