尝试旋转位图但没有成功

时间:2016-02-07 17:09:13

标签: android bitmap xamarin xamarin.android

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

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

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

2 个答案:

答案 0 :(得分:0)

这种方法一直对我有用

Matrix matrix = new Matrix();
   //myBitmap is the bitmap which is to be rotated
    matrix.postRotate(rotateDegree);
    Bitmap bitmap = Bitmap.createBitmap(myBitmap, 0, 0, myBitmap.getWidth(), myBitmap.getHeight(), matrix, true);//Rotated Bitmap

如果您从网址生成此位图,请继续使用此功能

public Bitmap decodeBitmap(File f) {

    try {
        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f), null, o);

        //The new size we want to scale to
        final int REQUIRED_SIZE = 490;

        //Find the correct scale value. It should be the power of 2.
        int scale = 1;
        while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
            scale *= 2;

        //Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {
    }
    return null;
}

答案 1 :(得分:0)

这是我用来在我的项目中轮换byte[]的代码片段。它接收并返回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,因此请确保在删除之前知道自己在做什么。