android - 尝试旋转位图但没有成功

标签 android bitmap xamarin xamarin.android

我正在编辑位图以针对 OCR 扫描对其进行优化。我需要做的一件事是将图像旋转 270 度。我正在使用以下代码:

Matrix matrix = new Matrix();
matrix.PostRotate (270);
canvas.DrawBitmap(alteredBitmap, matrix, paint);

显然,这对我不起作用。有人可以指出我错在哪里吗? 位图来自 byte[]

最佳答案

这是我用来在项目中旋转 byte[] 的代码 fragment 。它接收并返回一个 byte[],但通过删除最后 5 行代码,它将返回一个 Bitmap。它创造奇迹:

public async Task<byte[]> RotateImage(byte[] source, int rotation)
{
    //This is optional, use it to reduce your images a little
    var options = new BitmapFactory.Options();
    options.InJustDecodeBounds = false;
    options.InSampleSize = 2;

    var bitmap = await BitmapFactory.DecodeByteArrayAsync(source, 0, source.Length, options);
    Matrix matrix = new Matrix();
    matrix.PostRotate(rotation);
    var rotated = Bitmap.CreateBitmap(bitmap, 0, 0, bitmap.Width, bitmap.Height, matrix, true);

    var stream = new MemoryStream();
    await rotated.CompressAsync(Bitmap.CompressFormat.Jpeg, 100, stream);
    var result = stream.ToArray();

    await stream.FlushAsync();
    return result;
}

所有可等待的调用都有非异步对应项,因此可以将其转换为以阻塞方式运行而不会出现重大问题。请注意,删除 options 变量可能会导致 OutOfMemoryException,因此请确保在删除之前知道自己在做什么。

关于android - 尝试旋转位图但没有成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35256444/

相关文章:

android - 如何从代码覆盖率报告中排除包?

android - LinearLayout、RelativeLayout 等边距不按预期工作

Android Studio 使我的测试模块依赖于应用程序模块

android - 如何创建此 View (布局)?

android半透明位图背景为黑色

c# - 将图像中的每个像素设置为颜色列表中最接近的匹配项

ios - 谷歌登录 Xamarin 绑定(bind)

ios - UILabel 剪切文本顶部

C#在内存中以特定大小剪切图像而不保存文件

android - 如何修复 .NetStandard 上的 HTTPClient 中的 "java.io.IOException: unexpected end of stream on Connection"异常