我想用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 wireshark抓不到vlan
- ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
- ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
- ¥15 stata安慰剂检验作图但是真实值不出现在图上
- ¥15 c程序不知道为什么得不到结果
- ¥40 复杂的限制性的商函数处理
- ¥15 程序不包含适用于入口点的静态Main方法
- ¥15 素材场景中光线烘焙后灯光失效
- ¥15 请教一下各位,为什么我这个没有实现模拟点击
- ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来