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

.NET MAUI Blazor Android端Base64图片裁剪实现问询

.NET MAUI Blazor Android平台裁剪图片并生成新Base64字符串

针对Android平台的Android.Graphics.Bitmap,可以直接使用其原生裁剪方法完成需求,步骤如下:

1. 验证裁剪区域合法性

先确保指定的裁剪区域不超出原图边界,避免运行时报错:

bool isRegionValid = x >= 0 && y >= 0 && width > 0 && height > 0 
                     && x + width <= bitmap.Width 
                     && y + height <= bitmap.Height;

if (!isRegionValid)
{
    // 按需处理越界情况,比如抛出异常或返回空值
    throw new ArgumentOutOfRangeException(nameof(x), "裁剪区域超出原图范围");
}

2. 执行图片裁剪

使用Android.Graphics.Bitmap.CreateBitmap静态方法完成裁剪,该方法直接返回裁剪后的新Bitmap对象:

using var croppedBitmap = Android.Graphics.Bitmap.CreateBitmap(bitmap, x, y, width, height);

3. 将裁剪后的Bitmap转换为Base64字符串

将裁剪后的Bitmap压缩为流,再转换为Base64:

string croppedBase64;
using var stream = new MemoryStream();
// 可根据需求替换为CompressFormat.Jpeg,Jpeg需传入质量参数(0-100)
croppedBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, stream);
croppedBase64 = Convert.ToBase64String(stream.ToArray());

完整代码示例

string imageValue = "sdfghjkhgjkjhgj"; // 你的Base64图片字符串
int x = 20;
int y = 30;
int width = 150;
int height = 180;

// 转换为Android.Graphics.Bitmap
Microsoft.Maui.Graphics.IImage image = PlatformImage.FromStream(new MemoryStream(Convert.FromBase64String(imageValue)));
using var bitmap = image.AsBitmap();

// 裁剪并生成新Base64
string croppedBase64 = null;
bool isRegionValid = x >= 0 && y >= 0 && width > 0 && height > 0 
                     && x + width <= bitmap.Width 
                     && y + height <= bitmap.Height;

if (isRegionValid)
{
    using var croppedBitmap = Android.Graphics.Bitmap.CreateBitmap(bitmap, x, y, width, height);
    using var stream = new MemoryStream();
    croppedBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, stream);
    croppedBase64 = Convert.ToBase64String(stream.ToArray());
}
else
{
    throw new ArgumentOutOfRangeException("裁剪区域参数不合法,超出原图范围");
}

// croppedBase64即为裁剪后的图片Base64字符串

注意:使用using语句包裹Bitmap和流对象,确保原生资源被及时释放,避免内存泄漏。

内容的提问来源于stack exchange,提问作者kinda-wired

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 18:36:24