비트 맵을 90도 회전하는 방법


123

안드로이드에 진술이 있습니다 canvas.drawBitmap(visiblePage, 0, 0, paint);

를 추가 canvas.rotate(90)해도 효과가 없습니다. 하지만 내가 쓰면

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

비트 맵이 그려지지 않습니다. 그래서 내가 옳지 않은 것은 무엇입니까?


답변:


254

당신은 또한 이것을 시도 할 수 있습니다

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에서 설정할 수 있습니다.

imageView.setImageBitmap(rotatedBitmap);

1
원하는 scaledBitmap (bitmapOrg, width, height, true)에 대해 생각합니다
Jameo

2
어떤 매트릭스 가져 오기? android.graphics 또는 android.opengl?
Poutrathor

6
android.graphics 가져 오기
kirtan403

4
이것은 많은 메모리를 사용합니다. 큰 비트 맵의 ​​경우 메모리에 여러 비트 맵 복사본이 있기 때문에 문제가 발생할 수 있습니다.
Moritz Both 모두

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
나는 안드로이드를 처음 사용합니다. Bitmap newBitmap = RotateBitmap (oldBitmap, 90)을 수행하는지 궁금합니다. '디코딩 된 비트 맵'에 두 개의 메모리 블록 (이전 및 신규용)이 있는지 아니면 동일한 메모리를 참조하고 있지만 하나는 회전이없고 다른 하나는 회전이 있습니다. ? .... 내 우려는 R.drawable.picture를 oldBitmap으로 디코딩하면 2MB의 메모리를 차지한다고 가정하면 (내가 추측하는 힙?) newBitmap이 추가로 2MB의 메모리를 차지하게 될 것입니다 (예 : 2 + 2 = 총 4MB)? 또는 newBitmap이 oldBitmap만을 참조합니까 (따라서 추가 2MB가 필요하지 않음)? ......... 어떤 대가를 치르더라도 outOfMemory 오류를 피하고 싶습니다!
Shishir Gupta

4
@ShishirGupta 테스트되지 않았지만 안드로이드 문서에 의해 :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

비트 맵을 회전하면 90180270360은 괜찮지 만 다른 각도에서는 캔버스가 다른 크기로 비트 맵을 그립니다.

그래서, 가장 좋은 방법은

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

단지에서 같은 자바 플랫폼 호출에서 비트 맵 형식의주의 comm1x 의와 Gnzlt 이 널 (null)을 반환 할 수 있기 때문에,의 답변. 매개 변수가 숫자가 될 수 있고 가독성을 위해 중위를 사용하면 코딩 스타일에 따라 더 유연하다고 생각합니다.

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.