Android/画像/画像向き回転
提供: 初心者エンジニアの簡易メモ
- Main.java
import BitmapUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.IOException;
import java.io.InputStream;
import android.net.Uri;
import android.provider.MediaStore;
import android.content.ContentResolver;
import android.database.Cursor;
ContentResolver cr = _context.getContentResolver();
InputStream in = cr.openInputStream(uri);
// 写真の角度取得
Cursor query = MediaStore.Images.Media.query(cr, uri,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null);
query.moveToFirst();
int orientation = query.getInt(0);
Bitmap bitmap = BitmapFactory.decodeStream(in);
// 回転しない
if (orientation == 0) {
return bitmap;
// 回転させる
} else {
return BitmapUtil.createChangeRotaBmp(bitmap, orientation);
}
- BitmapUtil.java
import android.graphics.Matrix;
/**
* Bitmapユーティリティクラス
*/
public class BitmapUtil {
/**
* 画像を回転して取得
* @param int degrees 0~360度数
*/
public static Bitmap createChangeRotaBmp(Bitmap src, int degrees) {
int w = src.getWidth();
int h = src.getHeight();
// 回転後の高さ幅。最後の+0.5は四捨五入のため(参考:http://homepage2.nifty.com/tsugu/sotuken/rotation/
int height = (int)(Math.abs(w * Math.cos(degrees / 180 * Math.PI)) + Math.abs(h * Math.sin(degrees / 180 * Math.PI) + 0.5));
int width = (int)(Math.abs(w * Math.sin(degrees / 180 * Math.PI)) + Math.abs(h * Math.cos(degrees / 180 * Math.PI) + 0.5));
Matrix matrix = new Matrix();
matrix.postRotate(degrees); // 回転させる角度を指定(45度は45.0f
Bitmap bmp = Bitmap.createBitmap(src, 0, 0, height, width, matrix, true);
matrix = null;
if (src != null) {
// Bitmapデータの解放
//src.recycle();
src = null;
}
return bmp;
}
}
