java如何从gallery(或drawable)获取图像以更新ImageView?
在我的代码中,我使用了一个意图来拍照,但我真的不明白在那之后我在哪里可以得到这个图像。我在这个小应用程序中的目标是拍摄一张照片,然后用这张照片更新ImageView(并以其他目的打开google地图)。这两个按钮由两个按钮激活
主要活动。爪哇:
import 安卓.net.Uri;
import 安卓.os.Bundle;
import 安卓.provider.MediaStore;
import 安卓.support.v7.app.AppCompatActivity;
import 安卓.view.View;
import 安卓.widget.EditText;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
static final int REQUEST_IMAGE_CAPTURE = 1;
public void activerCamera(View view) {
Intent prendrePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (prendrePhoto.resolveActivity(getPackageManager()) != null) {
startActivityForResult(prendrePhoto, REQUEST_IMAGE_CAPTURE);
}
}
public void googleMaps(View view) {
EditText nameField = (EditText) findViewById(R.id.name_field);
String name = nameField.getText().toString();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:" + name));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
}
我的活动是主要的。xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
xmlns:tools="http://schemas.安卓.com/tools"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent"
安卓:orientation="vertical"
tools:context="com.example.安卓.photoapp.MainActivity">
<EditText
安卓:id="@+id/name_field"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:hint="Exemple : 47.6, -122.3"
安卓:layout_gravity="center_horizontal"
安卓:layout_marginTop="24dp"/>
<Button
安卓:layout_marginTop="24dp"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:text="Aller sur google maps"
安卓:layout_gravity="center_horizontal"
安卓:textAllCaps="true"
安卓:onClick="googleMaps"/>
<Button
安卓:layout_marginTop="24dp"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:text="Prendre une photo"
安卓:layout_gravity="center_horizontal"
安卓:textAllCaps="true"
安卓:onClick="activerCamera"/>
<ImageView
安卓:id="@+id/imageFondEcran"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content" />
</LinearLayout>
我在很多论坛和教程中看到了这样的方法(down),但我无法让它正常工作
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri photoUri = data.getData();
// Do something with the photo based on Uri
Bitmap selectedImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
// Load the selected image into a preview
ImageView ivPreview = (ImageView) findViewById(R.id.ivPreview);
ivPreview.setImageBitmap(selectedImage);
} }
# 1 楼答案
因为大多数摄像头应用程序的代码都是错误的,所以它对你不起作用并不奇怪
您正在发出
ACTION_IMAGE_CAPTURE
请求,但没有包括EXTRA_OUTPUT
以说明图像应该放在哪里。因此,你的照片应该是一张Bitmap
,通过调用getParcelableExtra("data")
发送到onActivityResult()
的Intent
上的getParcelableExtra("data")
来获得所以,改变:
致:
# 2 楼答案
试试这个:
在您的活动中,您可以调用此选项,以将您的可绘制资源作为可绘制对象:
如果要在ImageView中显示可绘制图像,可以执行以下操作:
或者在xml文件中:
祝你好运