我正在处理两个问题,试图在我的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;
}
它确实将位图变成了正方形,但问题是它会切割照片而不是重新缩放它。 (基本上丢失了一半图像)
我很确定我想做的很简单,我该怎么做?
答案 0 :(得分:2)
而不是使用,
Bitmap.createBitmap(bitmap, crop, 0, newWidth, newHeight);
使用以下行,
Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, false);
答案 1 :(得分:0)
无论如何,官方文件是最好的老师,请查看here