我对使用手机相机拍摄的照片有些疑问。当我拍照并保存时,我的手机会以原始尺寸显示,但当我尝试在我的应用程序上打开相同的照片时,它会输出一张旋转的照片,就像这样:
原始照片:
旋转照片:
只有在用手机拍照时才会出现此问题。
我使用以下代码选择图库:
private void selectImage() {
final CharSequence[] options = {"My gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(PhotosActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("My gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
选择照片:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
if (thumbnail.getWidth() > thumbnail.getHeight()) {
Matrix matrix = new Matrix();
matrix.postRotate(90);
thumbnail = Bitmap.createBitmap(thumbnail , 0, 0, thumbnail.getWidth(), thumbnail.getHeight(), matrix, true);
}
int nh = (int) ( thumbnail.getHeight() * (612.0 / thumbnail.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(thumbnail, 612, nh, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
scaled.compress(Bitmap.CompressFormat.JPEG, 90, stream);
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
newtask = new saveImage();
newtask.execute(image_str,sessionid);
Toast.makeText(getBaseContext(), "Nice!",
Toast.LENGTH_LONG).show();
}
}
}
我尝试使用以下代码修复它,但它不适用于横向照片,我想获得一个代码来输出原始尺寸。
if (thumbnail.getWidth() > thumbnail.getHeight()) {
Matrix matrix = new Matrix();
matrix.postRotate(90);
thumbnail = Bitmap.createBitmap(thumbnail , 0, 0, thumbnail.getWidth(), thumbnail.getHeight(), matrix, true);
}
感谢。
答案 0 :(得分:0)
您需要从mediastore查询方向(它是ImageColumns.ORIENTATION)
请尝试更改此行:matrix.postRotate(90);
至matrix.postRotate(270);