You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin.iOS图片缩放后上传服务器显示灰色/空白问题求助

Xamarin.iOS图片缩放后上传显示灰色/损坏问题解决

问题场景

  • 相机拍摄的图片缩小至800*600后上传服务器,图片显示为灰色/损坏状态
  • 使用以下缩放代码处理后,上传的图片呈现灰色/空白

原有缩放代码

var sourceSize = sourceImage.Size;
var maxResizeFactor = Math.Min(newSize.Width / sourceSize.Width, newSize.Height / sourceSize.Height);

if (maxResizeFactor > 1) return sourceImage;
var width = maxResizeFactor * sourceSize.Width;
var height = maxResizeFactor * sourceSize.Height;
UIGraphics.BeginImageContext(new CGSize(width, height));
sourceImage.Draw(new CGRect(0, 0, width, height));
var resultImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return resultImage;

问题原因

UIGraphics.BeginImageContext默认使用1.0的缩放因子,在Retina设备上生成的图片像素密度与设备不匹配,导致图片数据异常,上传后显示为灰色或空白。

修复代码

替换为UIGraphics.BeginImageContextWithOptions方法,传入设备原生缩放比例,确保图片渲染正确:

var sourceSize = sourceImage.Size;
var maxResizeFactor = Math.Min(newSize.Width / sourceSize.Width, newSize.Height / sourceSize.Height);

if (maxResizeFactor > 1) return sourceImage;
var width = maxResizeFactor * sourceSize.Width;
var height = maxResizeFactor * sourceSize.Height;
// 启用Retina适配的绘图上下文
UIGraphics.BeginImageContextWithOptions(new CGSize(width, height), false, UIScreen.MainScreen.Scale);
sourceImage.Draw(new CGRect(0, 0, width, height));
var resultImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return resultImage;

核心修改点

  • 第二个参数opaque设为false,支持图片透明通道(若图片无透明需求可设为true提升性能)
  • 第三个参数scale传入UIScreen.MainScreen.Scale,匹配设备的Retina缩放比例,保证生成的图片像素数据完整

内容的提问来源于stack exchange,提问作者Gouri Anavatti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 03:12:42