我正在处理两个问题,试图在我的 Android 应用程序中显示图库中的照片。我想做的很简单:从图库中获取一张照片并将其放入我的 MainActivity 中的 ImageView(100dp*100dp)中。
第一个问题是在某些手机上,例如 Sony Xperia,在 ImageView 上设置照片时会旋转照片。为了解决这个问题,我在 SO 答案中找到了那段代码:
public Bitmap decodeFile(String path)
{
int orientation;
try {
if (path == null) {
return null;
}
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 0;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale++;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bm = BitmapFactory.decodeFile(path, o2);
Bitmap bitmap = bm;
ExifInterface exif = new ExifInterface(path);
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Log.e("ExifInteface .........", "rotation =" + orientation);
// exif.setAttribute(ExifInterface.ORIENTATION_ROTATE_90, 90);
Log.e("orientation", "" + orientation);
Matrix m = new Matrix();
if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
m.postRotate(180);
// m.postScale((float) bm.getWidth(), (float) bm.getHeight());
// if(m.preRotate(90)){
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), m, true);
return bitmap;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
m.postRotate(90);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), m, true);
return bitmap;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
m.postRotate(270);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), m, true);
return bitmap;
}
return bitmap;
} catch (Exception e) {
return null;
}
}
这很完美,但我还希望图像是正方形,但现在不是这种情况。
为此,在位图上使用第一个方法后,我还调用了那个方法:
public static Bitmap cropToSquare(Bitmap bitmap)
{
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = (height > width) ? width : height;
int newHeight = (height > width)? height - ( height - width) : height;
int crop = (width - height) / 2;
crop = (crop < 0)? 0: crop;
Bitmap cropImg = Bitmap.createBitmap(bitmap, crop, 0, newWidth, newHeight);
return cropImg;
}
它确实将位图变成了正方形,但问题是它剪切了照片而不是重新缩放它。 (基本上丢了一半图片)
我很确定我想做的很简单,我该怎么做?
最佳答案
而不是使用,
Bitmap.createBitmap(bitmap, crop, 0, newWidth, newHeight);
使用下面这行,
Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, false);
关于android - 如何正确显示位图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29446948/