最近自己弄了一个小项目,具体就是调用摄像头拍照并把照片上传到服务器
网络编程我用的是Okhttp框架,具体实现过程如下:
第一步:
定义一个HttpUtil类
public class HttpUtil {
//Post请求
public static void sendOkHttpPostRequest(String address, RequestBody requestBody, okhttp3.Callback callback){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(address).post(requestBody).build();
client.newCall(request).enqueue(callback);
}
}
第二步:
在方法中使用上面的类
private void saveToServer(File mFile) {
String address = "http://122.51.247.132:8987/infer";
RequestBody image = RequestBody.create(MediaType.parse("image/jpg"), mFile);
//构建请求体
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("img",mFile.getName(),image)
.build();
HttpUtil.sendOkHttpPostRequest(address,requestBody,new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
Log.d(TAG, "onFailure: "+"访问失败");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String Text = response.body().string();
Log.d(TAG, "onResponse: "+Text);
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(Text);
}
});
}
});
}
调用摄像头拍照并获取照片过程
首先获取权限
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED
&&ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,new String[]{
Manifest.permission.CAMERA
,Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
}else {
SaveInSD();//或者调用SaveInHuanCun()
}
拍照并获取图片,获取图片有两种获取方式
第一种:从缓存数据中获取图片,通过这种方式获取可以不用申请读写SD的权限
public void SaveInHuancun(){
// 获取文件,getExternalCacheDir()方法用于获取应用关联缓存目录,即SD卡中专门用于存放当前应用缓存数据的位置
outputImage = new File(getExternalCacheDir(),"picture.jpg");
Log.d(TAG, "onClick: "+outputImage.getPath());
try {
if (outputImage.exists()){
outputImage.delete();
}
outputImage.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
//拍照后原图回存入此路径
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
uri = Uri.fromFile(outputImage);
} else {
//7.0 调用系统相机拍照不再允许使用Uri方式,应该替换为FileProvider
uri = getUriForFile(MainActivity.this, "com.example.picture.fileprovider", outputImage);
}
//启动相机拍照
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 1);
}
第二种:从SD卡中获取拍摄图片,要申请SD卡读写权限
public void SaveInSD(){
//判断SD卡是否存在
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)){
String path = Environment.getExternalStorageDirectory().getPath();
//创建拍摄图片的目录
File file = new File(path+"/"+"scene");
if (!file.exists()) {
if (!file.mkdirs()) {
Toast.makeText(MainActivity.this, "创建目录失败!", Toast.LENGTH_SHORT).show();
}
}
outputImage = new File(file.getAbsolutePath(), "/" + "picture" + ".jpg");
//拍照后原图回存入此路径
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
uri = Uri.fromFile(outputImage);
} else {
//7.0 调用系统相机拍照不再允许使用Uri方式,应该替换为FileProvider
uri = getUriForFile(MainActivity.this, "com.example.picture.fileprovider", outputImage);
}
//启动相机拍照
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 1);
}else {
Toast.makeText(MainActivity.this,"未找到储存卡",Toast.LENGTH_SHORT).show();
}
}
特别注意:
通过应用缓存获取图片时共享路径file_paths为
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path path="Android/data/com.example.picture/cache/" name="files_root" />
</paths>
通过SD卡获取图片时共享路径file_paths为
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path path="scene/" name="files_root" />
</paths>
完整代码:
package com.example.picture;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Locale;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.Response;
import static android.support.v4.content.FileProvider.getUriForFile;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button button;
private ImageView picture;
private TextView textView;
private File outputImage;
private File file1=null;
private Uri uri;
private TextToSpeech tts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
picture = (ImageView)findViewById(R.id.pciture);
button = (Button) findViewById(R.id.take_photo);
textView = (TextView) findViewById(R.id.text);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED
&&ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,new String[]{
Manifest.permission.CAMERA
,Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
}else {
SaveInHuancun();//或者调用SaveInSD()
}
}
});
}
public void SaveInSD(){
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)){
String path = Environment.getExternalStorageDirectory().getPath();
File file = new File(path+"/"+"scene");
if (!file.exists()) {
if (!file.mkdirs()) {
Toast.makeText(MainActivity.this, "创建目录失败!", Toast.LENGTH_SHORT).show();
}
}
outputImage = new File(file.getAbsolutePath(), "/" + "picture" + ".jpg");
Log.d(TAG, "onClick: "+outputImage.getPath());
//拍照后原图回存入此路径
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
uri = Uri.fromFile(outputImage);
} else {
//7.0 调用系统相机拍照不再允许使用Uri方式,应该替换为FileProvider
uri = getUriForFile(MainActivity.this, "com.example.picture.fileprovider", outputImage);
}
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 1);
}else {
Toast.makeText(MainActivity.this,"未找到储存卡",Toast.LENGTH_SHORT).show();
}
}
public void SaveInHuancun(){
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// 获取文件
outputImage = new File(getExternalCacheDir(),"picture.jpg");
Log.d(TAG, "onClick: "+outputImage.getPath());
try {
if (outputImage.exists()){
outputImage.delete();
}
outputImage.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
//拍照后原图回存入此路径
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
uri = Uri.fromFile(outputImage);
} else {
//7.0 调用系统相机拍照不再允许使用Uri方式,应该替换为FileProvider
uri = getUriForFile(MainActivity.this, "com.example.picture.fileprovider", outputImage);
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 1);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode==1) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);
}
}
}
//将返回的图片显示出来
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
picture.setImageBitmap(bitmap);
saveToServer(outputImage);
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
private void saveToServer(File mFile) {
String address = "http://122.51.247.132:8987/infer";
RequestBody image = RequestBody.create(MediaType.parse("image/jpg"), mFile);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("img",mFile.getName(),image)
.build();
HttpUtil.sendOkHttpPostRequest(address,requestBody,new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
Log.d(TAG, "onFailure: "+"访问失败");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String Text = response.body().string();
Log.d(TAG, "onResponse: "+Text);
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(Text);
}
});
}
});
}
}