bir bitmap nasıl 90 derece döndürülür


123

Android'de bir açıklama var canvas.drawBitmap(visiblePage, 0, 0, paint);

Eklediğimde canvas.rotate(90)hiçbir etkisi olmuyor. Ama yazarsam

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

Bit eşlem çizilmiyor. Peki neyi doğru yapmıyorum?


Yanıtlar:


254

Bunu da deneyebilirsin

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);

Ardından, görüntü görünümünüzde ayarlamak için döndürülmüş görüntüyü kullanabilirsiniz.

imageView.setImageBitmap(rotatedBitmap);

1
İstediğiniz scaledBitmap için düşünüyorum (bitmapOrg, genişlik, yükseklik, doğru)
Jameo 01

2
Hangi matris içe aktarılıyor? android.graphics veya android.opengl?
Poutrathor


4
bu çok fazla bellek kullanır. Büyük bitmapler için, bellekteki birden çok bitmap kopyası nedeniyle sorunlar yaratabilir.
Moritz İkisi de

1
Orijinal bitmap'e ihtiyacınız yoksa, bitmap.recycle()emin olmak için arayın .
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'i kaynaklardan almak için:

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

1
Android konusunda yeniyim. Bitmap yapıp yapmadığımı merak ediyorum newBitmap = RotateBitmap (oldBitmap, 90), 'kodu çözülmüş bitmap'imde iki bellek bloğu var mı (eski ve yeni için) veya aynı belleğe mi atıfta bulunuyorlar, ancak birinin dönüşü yok, diğerinin dönüşü var ? .... Endişem şu ki, eğer R.drawable.picture'ı oldBitmap olarak çözersem, 2 MB bellek kapladığını varsayarsam (Heap sanırım?), NewBitmap'in ek 2 MB bellek alması (yani 4MB toplam)? veya newBitmap yalnızca oldBitmap'e mi başvurur (ve bu nedenle fazladan 2MB gerekmez)? ......... Ne pahasına olursa olsun outOfMemory Hatasından kaçınmak istiyorum!
Shishir Gupta

4
@ShishirGupta Test edilmedi ancak android dokümanlar tarafından: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 Hey arvis Önerinizi denedim ve oryantasyon için çalışıyor ancak şimdi çok daha küçük bir portre merkezli görüntü elde ediyorum. Herhangi bir fikir ?
Doug Ray

44

Kotlin için kısa uzantı

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

Ve kullanım:

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

13

Android'de resminizi döndürmek veya yeniden boyutlandırmak için kod aşağıdadır

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);
    }
}

Ayrıntılar için bu bağlantıyı da kontrol edebilirsiniz: http://www.anddev.org/resize_and_rotate_image_-_example-t621.html


6

Varsayılan olarak döndürme noktası Canvas'ın (0,0) noktasıdır ve benim tahminime göre onu merkez etrafında döndürmek isteyebilirsiniz. Ben bunu yaptım:

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

Ben basitleştirmek olur comm1x 'ın Kotlin uzatma fonksiyonunu daha:

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

4

Java createBitmap()yöntemini kullanarak dereceleri geçebilirsiniz.

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

Bitmap'i döndürürseniz, 90180270360 tamamdır, ancak diğer dereceler için tuval farklı boyutta bitmap çizecektir.

Yani, en iyi yol

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

0

Hedefiniz bir imageView veya dosyada döndürülmüş bir görüntüye sahip olmaksa, bunu başarmak için Exif'i kullanabilirsiniz. Destek kitaplığı artık şunları sunuyor: https://android-developers.googleblog.com/2016/12/introducing-the-exifinterface-support-library.html

Aşağıda kullanımı verilmiştir, ancak hedefinize ulaşmak için bunun için kütüphane api belgelerine bakmanız gerekir. Bitmap'i döndürmenin her zaman en iyi yol olmadığına dair bir ipucu vermek istedim.

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;
}

bağımlılık

"com.android.support:exifinterface:25.1.0" derleyin


0

Java platform çağrısından Bitmap türüne dikkat edin. Comm1x ve Gnzlt yanıtlarında olduğu , çünkü boş dönebilir. Parametrenin herhangi bir Sayı olabilmesi ve okunabilirlik için infix kullanması kodlama stilinize bağlı olarak daha esnek olduğunu düşünüyorum.

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

Nasıl kullanılır?

bitmap rotate 90
// or
bitmap.rotate(90)
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.