我有兴趣将图像视图设置为刚拍摄的照片.相机应用程序工作得很好,它将图像保存在适当位置的SD卡上,但是当我尝试加载图像并将其设置为图像视图时,它保持空白.我没有使用最近拍摄的图像的路径,而是尝试对现有图像的路径进行硬编码,但是我遇到了同样的问题.我检查了其他线程,但我看不出我的代码有任何差异.
这是相机功能:
private void takePicture(){
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "/resources/resources/WI"+job_num);
image_name = username+"_"+date+".png";
File image_file = new File(imagesFolder, image_name);
while(image_file.exists()){
image_name = username+"-"+date+"("+ image_count+").png";
image_count+=1;
image_file = new File(imagesFolder,image_name);
}
image_path = imagesFolder+image_name;
Uri uriSavedImage = Uri.fromFile(image_file);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
int request_code = 100;
startActivityForResult(imageIntent, request_code);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
ImageView thumb = (ImageView) findViewById(R.id.thumbnail);
Bitmap bmp = BitmapFactory.decodeFile(image_path);
thumb.setImageBitmap(bmp);
Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(this,"Error Saving Image", Toast.LENGTH_SHORT).show();
}
最后这里是ImageView:
<ImageView
android:id="@+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/camera"
android:layout_marginTop="10dp"
android:contentDescription="@string/picture_thumbnail"/>
需要改变什么?谢谢!
解决方法:
试试这个 :
final ImageView thumb = (ImageView) findViewById(R.id.thumbnail);
thumb.post(new Runnable() {
@Override
public void run()
{
Bitmap bmp = BitmapFactory.decodeFile(image_path);
thumb.setImageBitmap(bmp);
Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
}
});
但我不建议您在UI线程上解码位图.
从here开始:
The Android Camera application encodes the photo in the return Intent delivered to onActivityResult() as a small Bitmap in the extras, under the key “data”. The following code retrieves this image and displays it in an ImageView.
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(mImageBitmap);
}
Note: This thumbnail image from “data” might be good for an icon, but not a lot more. Dealing with a full-sized image takes a bit more work.
最好的祝愿.