我是编程新手,特别是Android 。我正在制作一个简单的应用程序,我正在调用相机并拍照,然后图片显示在ImageView
中,但我也希望它在存储在库中时单击按钮查看存储的图片
我的代码:
package com.example.picture.app;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
public class MainActivity extends AppCompatActivity {
public static final int CAMERA_REQUEST = 10;
private ImageView imgView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get access to the image view
imgView = findViewById(R.id.imgView);
}
//this method will be called when the take photo button is clicked
public void btnTakePhotoClicked(View v) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
public void onImageGalleryClicked(View v) {
//invoke the image gallery using n implicit intent
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
//where do we want to find the data
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureDirectoryPath = pictureDirectory.getPath();
//get a uri representation
Uri data = Uri.parse(pictureDirectoryPath);
//set the data and the type. Get all image types
photoPickerIntent.setDataAndType(data, "image/*");
startActivityForResult(photoPickerIntent, 20);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//DID THE USER CHOOSE OK? If so code inside this code will execute
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST) {
//WE ARE HEARING BACK FROM THE CAMERA
Bitmap cameraImage = (Bitmap) data.getExtras().get("data");
//at this point we have the image from the camera
imgView.setImageBitmap(cameraImage);
}
}
}
答案 0 :(得分:1)
您可以使用compress()
方法将其保存在外部存储空间中。
您可以尝试
try
{
FileOutputStream out = new FileOutputStream(new File(Environment.getExternalStorageDirectory().toString() + "/bmp.png"));
cameraImage.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
catch (Exception e)
{
Toast.makeText(getBaseContext(),e.getMessage(), Toast.LENGTH_SHORT);
}
此外,您还必须添加使用权限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>