Java setImageURI不工作
当用户从多媒体资料中选择照片或使用相机拍照时,我尝试设置图像按钮的图像。问题是,我的imageButtons刚刚更改为空白图像,但我得到的是文件目录。我做错了什么?我已经根据这个答案创建了我的ImageIntent和onActivityResult。但以下是我的onActivityResult方法:Java setImageURI不工作,java,android,Java,Android,当用户从多媒体资料中选择照片或使用相机拍照时,我尝试设置图像按钮的图像。问题是,我的imageButtons刚刚更改为空白图像,但我得到的是文件目录。我做错了什么?我已经根据这个答案创建了我的ImageIntent和onActivityResult。但以下是我的onActivityResult方法: protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
final boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action
.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
} else {
selectedImageUri = data == null ? null : data.getData();
}
ImageButton pic1 = (ImageButton) findViewById(R.id.ibPic1);
Toast.makeText(this, "Image saved to:\n" + selectedImageUri,
Toast.LENGTH_LONG).show();
pic1.setImageURI(selectedImageUri);
}
}
}
所以我从祝酒辞中知道我得到了Uri。我已经试过了,还有其他各种涉及位图的解决方案,但这些都会导致应用程序崩溃和内存不足异常
编辑
OnClick方法启动图像意图:
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.ibPic1:
openImageIntent();
break;
}
}
图像意图法
private void openImageIntent() {
// Determine Uri of camera image to save.
final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "Klea" + File.separator);
root.mkdirs();
final String fname = Sell.getUniqueImageFilename();
final File sdImageMainDirectory = new File(root, fname);
outputFileUri = Uri.fromFile(sdImageMainDirectory);
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(
captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName,
res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent,
"Vælg kilde");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
cameraIntents.toArray(new Parcelable[] {}));
startActivityForResult(chooserIntent, REQUEST_IMAGE_CAPTURE);
}
另一种方法是从文件中创建位图并进行设置。我还包括从内容uri到实际uri的转换(对于post文件,您需要实际uri)和图像采样,以避免OOM:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
final boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action
.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
} else {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = activity.getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
selectedImageUri = cursor.getString(columnIndex);
cursor.close();
}
ImageButton pic1 = (ImageButton) findViewById(R.id.ibPic1);
Toast.makeText(this, "Image saved to:\n" + selectedImageUri,
Toast.LENGTH_LONG).show();
//.setImageURI(selectedImageUri);
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImageUri, options);
options.inSampleSize = calculateInSampleSize(options, dpToPx(100),
dpToPx(100));
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bMapRotate = BitmapFactory.decodeFile(filePath, options);
int width = bMapRotate.getWidth();
int height = bMapRotate.getHeight();
if (width > height)
para = height;
else
para = width;
if (bMapRotate != null) {
pic1.setImageBitmap(bMapRotate);
}
}
}
private int dpToPx(int dp) {
float density = activity.getResources().getDisplayMetrics().density;
return Math.round((float) dp * density);
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
activityresult上受保护的void(int-requestCode、int-resultCode、Intent-data){
if(resultCode==RESULT\u OK){
if(requestCode==请求\图像\捕获){
最终布尔isCamera;
如果(数据==null){
isCamera=真;
}否则{
最后一个字符串action=data.getAction();
if(action==null){
isCamera=假;
}否则{
isCamera=行动
.equals(android.provider.MediaStore.ACTION\u IMAGE\u CAPTURE);
}
}
Uri选择图像Uri;
如果(isCamera){
选择edimageri=outputFileUri;
}否则{
Uri selectedImage=data.getData();
字符串[]filePathColumn={MediaStore.Images.Media.DATA};
Cursor Cursor=activity.getContentResolver().query(
选择图像、文件路径列、null、null、null);
cursor.moveToFirst();
int columnIndex=cursor.getColumnIndex(filePathColumn[0]);
选择edimageri=cursor.getString(columnIndex);
cursor.close();
}
ImageButton pic1=(ImageButton)findViewById(R.id.ibPic1);
Toast.makeText(此“图像保存到:\n”+selectedImageUri,
Toast.LENGTH_LONG).show();
//.setImageURI(selectedImageUri);
final BitmapFactory.Options=new BitmapFactory.Options();
options.inJustDecodeBounds=true;
BitmapFactory.decodeFile(选择图像URI,选项);
options.inSampleSize=计算样本大小(options,dpToPx(100),
dpToPx(100));
//使用inSampleSize集合解码位图
options.inJustDecodeBounds=false;
位图bMapRotate=BitmapFactory.decodeFile(文件路径,选项);
int-width=bMapRotate.getWidth();
int height=bMapRotate.getHeight();
如果(宽度>高度)
para=高度;
其他的
para=宽度;
if(bMapRotate!=null){
pic1.设置图像位图(bMapRotate);
}
}
}
专用int dpToPx(int dp){
浮动密度=activity.getResources().getDisplayMetrics().density;
返回数学圆((浮点)dp*密度);
}
公共静态int-calculateInSampleSize(BitmapFactory.Options、,
输入要求宽度,输入要求高度){
//图像的原始高度和宽度
最终内部高度=options.outHeight;
最终整数宽度=options.outWidth;
int inSampleSize=1;
如果(高度>要求高度| |宽度>要求宽度){
//计算高度和宽度与所需高度和宽度的比率
//宽度
最终整数高度比=数学圆((浮动)高度
/(浮动)高度);
最终整数宽度比=数学圆((浮动)宽度/(浮动)宽度);
//选择最小比率作为采样值,这将
//保证
//最终图像的两个尺寸均大于或等于
//要求的高度和宽度。
inSampleSize=高度比<宽度比?高度比:宽度比;
}
返回样本大小;
}
画廊和相机都不工作吗?你能检查一下吗?两者都不工作。祝酒词说“file://.....“用于摄像头和”content://......"对于gallery。在照相机中,你将获得准确的uri,但在gallery中,你将获得内容uri。但他们中的任何人都没有将图像设置为空白。在我插入新图像之前有一张图片,我可以通过单击按钮设置另一张图片,因此我认为这方面没有错误。不确定为什么它不起作用。但我可以提供另一种。将图像转换为位图,然后设置位图。它可以工作,但在我使用相机时无法工作,这就是我获取:outputFileUri=Uri.fromFile(sdImageMainDirectory)的方式;我更改了:else if(requestCode==camera\u REQUEST&&resultCode=-1){filePath=outputFileUri;to outputFileUri.toString();另外,我不知道这是否意味着我没有摄像头请求代码,因为我正在从一个意图启动openImageIntent,以从摄像头或其他图像库中进行选择。你想让我发布意图方法吗?@KæmpeKlunker只需要根据你做一些修改。就像你使用布尔值来检查摄像头或画廊,我可以检查请求代码。摄像头请求只是摄像头请求代码的一个数字。是的,我知道,但你有结果加载图像和摄像头请求,我有:startActivityForResult(选择内容,int);所以我不知道如何定义每个数字?你可以先查看我的问题链接“摄像头和画廊”要查看代码,这是投票最多的答案。我不太清楚为什么这会在bMapRotate.getWidth()中引发空指针异常;对于摄影机和画廊都是如此。@KæmpeKlunker可能位图变为空。检查文件路径是否存在/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
final boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action
.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
} else {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = activity.getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
selectedImageUri = cursor.getString(columnIndex);
cursor.close();
}
ImageButton pic1 = (ImageButton) findViewById(R.id.ibPic1);
Toast.makeText(this, "Image saved to:\n" + selectedImageUri,
Toast.LENGTH_LONG).show();
//.setImageURI(selectedImageUri);
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImageUri, options);
options.inSampleSize = calculateInSampleSize(options, dpToPx(100),
dpToPx(100));
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bMapRotate = BitmapFactory.decodeFile(filePath, options);
int width = bMapRotate.getWidth();
int height = bMapRotate.getHeight();
if (width > height)
para = height;
else
para = width;
if (bMapRotate != null) {
pic1.setImageBitmap(bMapRotate);
}
}
}
private int dpToPx(int dp) {
float density = activity.getResources().getDisplayMetrics().density;
return Math.round((float) dp * density);
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}