调用系统相机拍照,照片储存到数据库之中,并且获取相册路径,在recyclerview中显示出来
时间: 2023-10-07 17:08:25 浏览: 168
首先需要在AndroidManifest.xml文件中添加相机和存储权限:
```xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
然后创建一个布局文件activity_main.xml,包含一个按钮和一个RecyclerView:
```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn_take_photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Take photo"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_photos"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@+id/btn_take_photo"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
```
接下来创建一个Photo实体类,用于存储照片信息:
```java
public class Photo {
private int id;
private String imagePath;
public Photo(int id, String imagePath) {
this.id = id;
this.imagePath = imagePath;
}
public int getId() {
return id;
}
public String getImagePath() {
return imagePath;
}
}
```
然后创建一个PhotosAdapter类,用于RecyclerView的显示:
```java
public class PhotosAdapter extends RecyclerView.Adapter<PhotosAdapter.ViewHolder> {
private List<Photo> photos;
public PhotosAdapter(List<Photo> photos) {
this.photos = photos;
}
public void setPhotos(List<Photo> photos) {
this.photos = photos;
notifyDataSetChanged();
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_photo, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Photo photo = photos.get(position);
Glide.with(holder.itemView.getContext())
.load(photo.getImagePath())
.into(holder.ivPhoto);
}
@Override
public int getItemCount() {
return photos.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
ImageView ivPhoto;
ViewHolder(@NonNull View itemView) {
super(itemView);
ivPhoto = itemView.findViewById(R.id.iv_photo);
}
}
}
```
接下来创建一个MainActivity类,实现拍照、保存到数据库和显示相册的功能:
```java
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE_TAKE_PHOTO = 1;
private SQLiteDatabase db;
private PhotosAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DBHelper(this).getWritableDatabase();
adapter = new PhotosAdapter(new ArrayList<>());
RecyclerView rvPhotos = findViewById(R.id.rv_photos);
rvPhotos.setLayoutManager(new GridLayoutManager(this, 3));
rvPhotos.setAdapter(adapter);
Button btnTakePhoto = findViewById(R.id.btn_take_photo);
btnTakePhoto.setOnClickListener(v -> {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
}
});
showPhotos();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_TAKE_PHOTO && resultCode == RESULT_OK && data != null) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
if (bitmap != null) {
String imagePath = saveImage(bitmap);
if (imagePath != null) {
addPhoto(imagePath);
showPhotos();
} else {
Toast.makeText(this, "Failed to save image", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Failed to get image", Toast.LENGTH_SHORT).show();
}
}
}
private String saveImage(Bitmap bitmap) {
String fileName = "IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date()) + ".jpg";
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileName);
try (FileOutputStream fos = new FileOutputStream(file)) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
return file.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private void addPhoto(String imagePath) {
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.COLUMN_IMAGE_PATH, imagePath);
db.insert(DBHelper.TABLE_NAME, null, contentValues);
}
private void showPhotos() {
List<Photo> photos = new ArrayList<>();
Cursor cursor = db.query(DBHelper.TABLE_NAME, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_ID));
String imagePath = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_IMAGE_PATH));
photos.add(new Photo(id, imagePath));
} while (cursor.moveToNext());
}
cursor.close();
adapter.setPhotos(photos);
}
}
```
最后在res文件夹下创建一个布局文件item_photo.xml,用于显示每个照片:
```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="4dp"
android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackground">
<ImageView
android:id="@+id/iv_photo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop" />
</androidx.cardview.widget.CardView>
```
这样就完成了调用系统相机拍照,照片储存到数据库之中,并且获取相册路径,在recyclerview中显示出来的功能。
阅读全文