我想用Unity读取本地JPG图片然后另存为很小png图片作为icon图标使用,但是IO读取byte[]保存和原来大小一样,读取为Texture后保存比原来还大一倍。怎么才能保存为很小图片?
2条回答
关注 之前做过类似的功能,可以参考一下
#region 压缩得到用户相册图片-- 上传头像使用 private string CompressTexture(string imagePath) { if (string.IsNullOrEmpty(imagePath)) return ""; byte[] fileData = File.ReadAllBytes(imagePath); Texture2D tex = new Texture2D((int) (Screen.width), (int) (Screen.height), TextureFormat.RGB24, true); tex.LoadImage(fileData); float miniSize = Mathf.Max(tex.width, tex.height); float scale = 1200.0f / miniSize; if (scale > 1.0f) { scale = 1.0f; } Texture2D temp = ScaleTexture(tex, (int) (tex.width * scale), (int) (tex.height * scale)); byte[] pngData = temp.EncodeToJPG(); string miniImagePath = imagePath.Replace(".png", "_min.jpg"); File.WriteAllBytes(miniImagePath, pngData); Destroy(tex); Destroy(temp); return miniImagePath; } private Texture2D ScaleTexture(Texture2D source, int targetWidth, int targetHeight) { Texture2D result = new Texture2D(targetWidth, targetHeight, source.format, true); Color[] rpixels = result.GetPixels(0); float incX = ((float) 1 / source.width) * ((float) source.width / targetWidth); float incY = ((float) 1 / source.height) * ((float) source.height / targetHeight); for (int px = 0; px < rpixels.Length; px++) { rpixels[px] = source.GetPixelBilinear(incX * ((float) px % targetWidth), incY * ((float) Mathf.Floor(px / targetWidth))); } result.SetPixels(rpixels, 0); result.Apply(); return result; } #endregion
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用
悬赏问题
- ¥20 关于#硬件工程#的问题,请各位专家解答!
- ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
- ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
- ¥30 截图中的mathematics程序转换成matlab
- ¥15 动力学代码报错,维度不匹配
- ¥15 Power query添加列问题
- ¥50 Kubernetes&Fission&Eleasticsearch
- ¥15 報錯:Person is not mapped,如何解決?
- ¥15 c++头文件不能识别CDialog
- ¥15 Excel发现不可读取的内容