我试图解码位图,但函数返回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是否为空
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;
}
无需使用实际文件,因为您引用的是内容提供商(它将为您执行此操作)
Uri imgselect = data.getData();
Bitmap bm = BitmapFactory.decodeFile(imgselect.getPath());
无法检查它是否有效,您可能需要先解码Uri。