- 依赖和权限
依赖
implementation 'com.github.bumptech.glide:glide:3.8.0' //解析图片(glide图片加载框架)
implementation 'com.squareup.picasso:picasso:2.3.2' //解析图片
implementation 'com.squareup.okhttp3:okhttp:3.10.0'//okhttp3
implementation 'com.google.code.gson:gson:2.2.4'//gson
权限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
- 内容提供者
首先在res文件夹下创建xml文件夹,在其中创建 file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android"
>
<root-path name="upload" path=""/>
</paths>
清单文件配置:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.gl10.photo_loadimg.abc"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
- 写布局
<?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"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="拍照" />
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="相册" />
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
- 创建要使用的实体类 UpLoadBean .java
public class UpLoadBean {
/**
* code : 200
* res : 上传文件成功
* data : {"url":"http://yun918.cn/study/public/uploadfiles/123/944365-ee747d1e331ed5a4.png"}
*/
private int code;
private String res;
private DataBean data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getRes() {
return res;
}
public void setRes(String res) {
this.res = res;
}
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public static class DataBean {
/**
* url : http://yun918.cn/study/public/uploadfiles/123/944365-ee747d1e331ed5a4.png
*/
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
}
- 在Activity 中实现效果
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
/**
* 拍照
*/
private Button mBtn1;
/**
* 相册
*/
private Button mBtn2;
private ImageView mImg;
private File mFile;
private Uri mImageUri;
private int CAMERA_CODE = 100;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
mBtn1 = (Button) findViewById(R.id.btn1);
mBtn1.setOnClickListener(this);
mBtn2 = (Button) findViewById(R.id.btn2);
mBtn2.setOnClickListener(this);
mImg = (ImageView) findViewById(R.id.img);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
default:
break;
case R.id.btn1:
takePhoto();
break;
case R.id.btn2:
break;
}
}
/**
* 判断照相的权限是否添加
*/
private void takePhoto() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED) {
openCamera();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 100);
}
}
/**
* 请求权限返回的结果
*
* @param requestCode
* @param permissions
* @param grantResults
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (requestCode == 100) {
openCamera();
}
}
}
/**
* 打开相机
*/
private void openCamera() {
// 创建文件用于保存图片
mFile = new File(getExternalCacheDir(), System.currentTimeMillis() + ".jpg");
if (!mFile.exists()) {
try {
mFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
// 适配7.0,等到对应的mImageUri路径地址
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
mImageUri = Uri.fromFile(mFile);
} else {
// 第二个参数要和清单文件中的配置保持一致
mImageUri = FileProvider.getUriForFile(this, "com.example.gl10.photo_loadimg.abc", mFile);
}
// 启动相机
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
startActivityForResult(intent, CAMERA_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) { // 判断回调成功
if (requestCode == CAMERA_CODE) {
// 显示拍照后的图片
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(mImageUri));
mImg.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 拍照后的图片上传
// uploadFile(mFile);
}
}
}
private void uploadFile(File file) {
String url = "http://yun918.cn/study/public/file_upload.php";
OkHttpClient client = new OkHttpClient.Builder()
.build();
RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), mFile);
MultipartBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("key", "fafda")
.addFormDataPart("file", mFile.getName(), requestBody)
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
Gson gson = new Gson();
final UpLoadBean upLoadBean = gson.fromJson(result, UpLoadBean.class);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (upLoadBean != null) {
if (upLoadBean.getCode() == 200) {
Toast.makeText(MainActivity.this, upLoadBean.getRes(), Toast.LENGTH_SHORT).show();
Glide.with(MainActivity.this).load(upLoadBean.getData().getUrl()).into(mImg);
Log.d(TAG, "run: " + upLoadBean.getData().getUrl());
} else {
Toast.makeText(MainActivity.this, upLoadBean.getRes(), Toast.LENGTH_SHORT).show();
}
}
}
});
}
});
}
}
网友评论