介绍
在移动应用中,允许用户上传图片是一项常见的功能。Android提供了相机(Camera)和图库(Gallery)来选择和拍摄照片。以下是一个简单的Android应用程序,演示了如何使用相机拍摄照片,并将其保存到设备的存储中。在另一个活动中,展示了如何从存储中加载并显示这张照片。
步骤
1. 请求权限
在AndroidManifest.xml文件中,你已经声明了读取和写入外部存储以及使用相机的权限。这确保了应用能够访问设备的相机和存储。
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2. 布局文件
在activity_main.xml
中,你创建了一个简单的布局,包含一个ImageView
用于显示拍摄的照片和一个按钮触发相机。
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:layout_width="400dp"
android:layout_height="400dp"
android:scaleType="fitXY"
android:id="@+id/imgCamera" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnCamera"
android:layout_marginTop="21dp"
android:text="Open Camera"></Button>
</LinearLayout>
3. 拍摄照片
在MainActivity.java
中,你使用了Intent
打开相机应用,并在拍摄后将照片保存到设备的存储中。
// 请求相机权限
askPermission();
// 找到ImageView和Button
imgCamera = findViewById(R.id.imgCamera);
Button btnCamera = findViewById(R.id.btnCamera);
// 设置按钮点击事件
btnCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 打开相机
Intent iCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(iCamera, CAMERA_REQ_CODE);
}
});
4. 保存照片
在onActivityResult
方法中,你获取相机拍摄的照片,并将其保存到设备的存储中。
// 检查拍照结果
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQ_CODE) {
// 获取拍摄的照片
if (data != null) {
Bitmap img = (Bitmap) data.getExtras().get("data");
imgCamera.setImageBitmap(img);
// 保存照片到设备的MediaStore
// ...
}
}
}
5. 显示照片
在ShowActivity.java
中,你获取之前保存的照片的URI,然后通过URI加载并显示照片。
// 获取之前保存的照片的URI
Uri uri = MainActivity.uri;
// 查询MediaStore获取文件路径
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
// 获取文件路径
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String filePath = cursor.getString(column_index);
cursor.close();
// 使用文件路径加载照片并显示
File imgFile = new File(filePath);
if(imgFile.exists()){
Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView imageView = findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
}
}
以下是完整的代码,包括MainActivity.java
、ShowActivity.java
、和activity_show.xml
:
MainActivity.java
package com.example.test;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.ContentValues;
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.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private final int CAMERA_REQ_CODE = 100;
static Uri uri;
ImageView imgCamera;
private static final String FOLDER_NAME = "MyAppImages";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
askPermission();
imgCamera = findViewById(R.id.imgCamera);
Button btnCamera = findViewById(R.id.btnCamera);
btnCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent iCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(iCamera, CAMERA_REQ_CODE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQ_CODE) {
if (data != null) {
Bitmap img = (Bitmap) data.getExtras().get("data");
imgCamera.setImageBitmap(img);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
File folder = new File(Environment.getExternalStorageDirectory(), FOLDER_NAME);
if (!folder.exists()) {
folder.mkdirs();
}
String fileName = timeStamp + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + "/" + FOLDER_NAME);
uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
try {
OutputStream outputStream = getContentResolver().openOutputStream(uri);
if (outputStream != null) {
img.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
outputStream.close();
Toast.makeText(this, "Image saved successfully", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
private void askPermission() {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
}, 0);
}
}
ShowActivity.java
package com.example.test;
import android.annotation.SuppressLint;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
public class ShowActivity extends AppCompatActivity {
ImageView imageView;
@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
imageView = findViewById(R.id.imageView);
Uri uri = MainActivity.uri;
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String filePath = cursor.getString(column_index);
cursor.close();
File imgFile = new File(filePath);
if (imgFile.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView imageView = findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
}
}
}
}
activity_show.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ShowActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout_editor_absoluteX="171dp"
tools:layout_editor_absoluteY="395dp"
tools:srcCompat="@tools:sample/avatars" />
</LinearLayout>