ビットマップを90度回転する方法


123

アンドロイドに声明があります canvas.drawBitmap(visiblePage, 0, 0, paint);

追加してcanvas.rotate(90)も効果がありません。でも書けば

canvas.rotate(90)
canvas.drawBitmap(visiblePage, 0, 0, paint);

ビットマップが描画されません。それで、私は何を正しくしていませんか?


私はここで、このに答えています stackoverflow.com/questions/8608734/...
EyalBellishaを

回答:


253

こちらもお試しいただけます

Matrix matrix = new Matrix();

matrix.postRotate(90);

Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmapOrg, width, height, true);

Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);

次に、回転した画像を使用して、イメージビューで設定できます

imageView.setImageBitmap(rotatedBitmap);

1
あなたが望むscaledBitmap(bitmapOrg、width、height、true)について
Jameo

2
どのマトリックスをインポートしますか?android.graphicsまたはandroid.opengl?
Poutrathor 2015

6
android.graphicsをインポートする
kirtan403

4
これは多くのメモリを使用します。大きなビットマップの場合、メモリ内にビットマップの複数のコピーがあるため、問題が発生する可能性があります。
モリッツ

1
元のビットマップが必要ない場合は、bitmap.recycle()確実に呼び出してください。
Nick Bedford

174
public static Bitmap RotateBitmap(Bitmap source, float angle)
{
      Matrix matrix = new Matrix();
      matrix.postRotate(angle);
      return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}

リソースからビットマップを取得するには:

Bitmap source = BitmapFactory.decodeResource(this.getResources(), R.drawable.your_img);

1
私はアンドロイドで新しいです。ビットマップnewBitmap = RotateBitmap(oldBitmap、90)を実行しているかどうか疑問に思っていますが、「デコードされたビットマップ」には2つのメモリブロック(古いものと新しいもの)がありますか、それとも同じメモリを参照していますが、1つはローテーションがなく、もう1つはローテーションがあります?....私の懸念は、R.drawable.pictureをoldBitmapにデコードした場合、2 MBのメモリ(ヒープ)を占有すると想定すると、newBitmapは追加の2 MBのメモリ(つまり2 + 2 =合計4MB)?またはnewBitmapはoldBitmapのみを参照しますか(したがって、追加の2MBは必要ありません)?.........どうしてもoutOfMemoryエラーを回避したい!
Shishir Gupta 2014

4
@ShishirGuptaテストされていませんが、Android docsによる:If the source bitmap is immutable and the requested subset is the same as the source bitmap itself, then the source bitmap is returned and no new bitmap is created.
Arvis

1
@Arvisちょっとarvis私はあなたの提案を試してみましたが、それは方向付けに役立ちますが、今ははるかに小さい縦長の中央の画像を取得しています。何か案は ?
Doug Ray

44

Kotlinの短い拡張

fun Bitmap.rotate(degrees: Float): Bitmap {
    val matrix = Matrix().apply { postRotate(degrees) }
    return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
}

そして使い方:

val rotatedBitmap = bitmap.rotate(90F) // value must be float

13

以下は、Androidで画像を回転またはサイズ変更するコードです

public class bitmaptest extends Activity {
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        LinearLayout linLayout = new LinearLayout(this);

        // load the origial BitMap (500 x 500 px)
        Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
               R.drawable.android);

        int width = bitmapOrg.width();
        int height = bitmapOrg.height();
        int newWidth = 200;
        int newHeight = 200;

        // calculate the scale - in this case = 0.4f
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        // createa matrix for the manipulation
        Matrix matrix = new Matrix();
        // resize the bit map
        matrix.postScale(scaleWidth, scaleHeight);
        // rotate the Bitmap
        matrix.postRotate(45);

        // recreate the new Bitmap
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
                          width, height, matrix, true);

        // make a Drawable from Bitmap to allow to set the BitMap
        // to the ImageView, ImageButton or what ever
        BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);

        ImageView imageView = new ImageView(this);

        // set the Drawable on the ImageView
        imageView.setImageDrawable(bmd);

        // center the Image
        imageView.setScaleType(ScaleType.CENTER);

        // add ImageView to the Layout
        linLayout.addView(imageView,
                new LinearLayout.LayoutParams(
                      LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT
                )
        );

        // set LinearLayout as ContentView
        setContentView(linLayout);
    }
}

詳細については、このリンクを確認することもできますhttp : //www.anddev.org/resize_and_rotate_image_-_example-t621.html


6

デフォルトでは、回転ポイントはCanvasの(0,0)ポイントであり、中心を軸に回転させたいと思うかもしれません。私はそれをしました:

protected void renderImage(Canvas canvas)
{
    Rect dest,drawRect ;

    drawRect = new Rect(0,0, mImage.getWidth(), mImage.getHeight());
    dest = new Rect((int) (canvas.getWidth() / 2 - mImage.getWidth() * mImageResize / 2), // left
                    (int) (canvas.getHeight()/ 2 - mImage.getHeight()* mImageResize / 2), // top
                    (int) (canvas.getWidth() / 2 + mImage.getWidth() * mImageResize / 2), //right
                    (int) (canvas.getWidth() / 2 + mImage.getHeight()* mImageResize / 2));// bottom

    if(!mRotate) {
        canvas.drawBitmap(mImage, drawRect, dest, null);
    } else {
        canvas.save(Canvas.MATRIX_SAVE_FLAG); //Saving the canvas and later restoring it so only this image will be rotated.
        canvas.rotate(90,canvas.getWidth() / 2, canvas.getHeight()/ 2);
        canvas.drawBitmap(mImage, drawRect, dest, null);
        canvas.restore();
    }
}

4

comm1xKotlin拡張関数をさらに簡略化します。

fun Bitmap.rotate(degrees: Float) =
    Bitmap.createBitmap(this, 0, 0, width, height, Matrix().apply { postRotate(degrees) }, true)

4

Java createBitmap()メソッドを使用して、度を渡すことができます。

Bitmap bInput /*your input bitmap*/, bOutput;
float degrees = 45; //rotation degree
Matrix matrix = new Matrix();
matrix.setRotate(degrees);
bOutput = Bitmap.createBitmap(bInput, 0, 0, bInput.getWidth(), bInput.getHeight(), matrix, true);

1

ビットマップを回転させる場合、90 180 270 360は問題ありませんが、他の角度ではキャンバスは異なるサイズのビットマップを描画します。

したがって、最良の方法は

canvas.rotate(degree,rotateCenterPoint.x,rotateCenterPoint.y);  
canvas.drawBitmap(...);
canvas.rotate(-degree,rotateCenterPoint.x,rotateCenterPoint.y);//rotate back

0

imageViewまたはファイルで回転した画像を作成することが目的の場合は、Exifを使用してそれを実現できます。サポートライブラリは次の機能を提供します:https : //android-developers.googleblog.com/2016/12/introducing-the-exifinterface-support-library.html

以下はその使用方法ですが、目標を達成するには、ライブラリAPIのドキュメントを確認する必要があります。ビットマップの回転が常に最良の方法であるとは限らないというヒントを与えたかっただけです。

Uri uri; // the URI you've received from the other app
InputStream in;
try {
  in = getContentResolver().openInputStream(uri);
  ExifInterface exifInterface = new ExifInterface(in);
  // Now you can extract any Exif tag you want
  // Assuming the image is a JPEG or supported raw format
} catch (IOException e) {
  // Handle any errors
} finally {
  if (in != null) {
    try {
      in.close();
    } catch (IOException ignored) {}
  }
}

int rotation = 0;
int orientation = exifInterface.getAttributeInt(
    ExifInterface.TAG_ORIENTATION,
    ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
  case ExifInterface.ORIENTATION_ROTATE_90:
    rotation = 90;
    break;
  case ExifInterface.ORIENTATION_ROTATE_180:
    rotation = 180;
    break;
  case ExifInterface.ORIENTATION_ROTATE_270:
    rotation = 270;
    break;
}

依存

「com.android.support:exifinterface:25.1.0」をコンパイルします


0

nullを返す可能性があるため、comm1xGnzltの回答などのJavaプラットフォーム呼び出しからのビットマップタイプに注意してください。コーディングスタイルに応じて、パラメーターを任意の数値にして読みやすくするためにインフィックスを使用することもできます。

infix fun Bitmap.rotate(degrees: Number): Bitmap? {
    return Bitmap.createBitmap(
        this,
        0,
        0,
        width,
        height,
        Matrix().apply { postRotate(degrees.toFloat()) },
        true
    )
}

使い方?

bitmap rotate 90
// or
bitmap.rotate(90)
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.