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

Xamarin Form中旋转图片存入数据库异常:旋转后字节数组未变化

问题分析与解决

你的代码核心问题是没有使用旋转后的位图:你创建了旋转后的rotated对象,也通过Canvas完成了绘制,但最后返回的SKImage是从原始的bitmap生成的,等于完全没用到旋转后的结果。

修正后的代码

如果需要直接返回旋转后的图片字节数组,可以修改成这样:

public static byte[] RotateAndGetBytes(byte[] imageBytesArray)
{
    using (var bitmap = SKBitmap.Decode(imageBytesArray))
    {
        // 创建对应旋转后尺寸的空位图
        var rotated = new SKBitmap(bitmap.Height, bitmap.Width);

        using (var surface = new SKCanvas(rotated))
        {
            // 平移+旋转操作,确保图片旋转后位置正确
            surface.Translate(rotated.Width, 0);
            surface.RotateDegrees(90);
            surface.DrawBitmap(bitmap, 0, 0);
        }

        // 将旋转后的位图编码为字节数组
        using (var image = SKImage.FromBitmap(rotated))
        using (var encodedData = image.Encode(SKEncodedImageFormat.Png, 100))
        using (var stream = encodedData.AsStream())
        {
            byte[] result = new byte[stream.Length];
            stream.Read(result, 0, result.Length);
            return result;
        }
    }
}

关键说明

  • 替换了返回的SKImage来源:从bitmap改成rotated,确保是旋转后的结果。
  • 新增了编码步骤:把SKImage直接转为字节数组,不需要额外处理就能存入数据库。
  • 编码格式可调整:如果需要JPG格式,把SKEncodedImageFormat.Png换成SKEncodedImageFormat.Jpeg,第二个参数是质量(0-100)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:15:08