我正在尝试解码位图,但该函数返回 null,我不知道为什么。
代码:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == SELECT_FOTO)
{
Uri imgselect = data.getData();
String imgpath = imgselect.getPath();
File f = new File (imgpath);
Bitmap bm = BitmapFactory.decodeFile(f.getAbsolutePath());
Toast.makeText(Insertarlugar.this, "Bitmap es" + bm, Toast.LENGTH_LONG).show();
}
toast 表明 bm 为空。我将 f.getAbsolutePath() 更改为 f.getPath() 但结果是一样的。 Uri imgselect 和 String imgpath 有值。我不使用 SD 卡,我从图库中获取位图。
如何调整位图的大小?
谢谢。
最佳答案
尝试这个并在 imagepath 不为 null 之前检查
Uri imgselect = data.getData();
String imgpath = imgselect.getPath();
if(imgpath !=null)
{
Bitmap bm = BitmapFactory.decodeFile(imgpath);
}
如果图像很大,它无法解码图像路径,所以你试试这个,并将宽度和高度设置为 60 和 60
public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth,
int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bmp = BitmapFactory.decodeFile(path, options);
return bmp;
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
关于android - 解码位图返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18510831/