【Android中使用OKHttp上传图片,从相机和相册中获取图片并剪切】千磨万击还坚劲,任尔东西南北风。这篇文章主要讲述Android中使用OKHttp上传图片,从相机和相册中获取图片并剪切相关的知识,希望能为你提供帮助。
效果:
文章图片
注意:
1:网络权限
< uses-permission android:name="android.permission.INTERNET"> < /uses-permission>
2:我封装了一个OKHttp,需要在build.gradle 中加入
compile \'com.squareup.okhttp3:logging-interceptor:3.4.2\'在同步一在
3:用SharedPreferences 保存和获取图片了,将图片和字符串进行了转换
4: 可以调用相机和相册获取图片,并进行剪切
//-----------------我的布局文件-----------------------------
< ?xml version="1.0" encoding="utf-8"?>
< LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context="tckpicture.bwie.com.tackpicture2.MainActivity">
< ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:scaleType="fitXY"
android:src="https://www.songbingjia.com/android/@mipmap/ic_launcher"
android:id="@+id/iv_img"/>
< Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="相机"
android:id="@+id/bt_camera"/>
< Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="相册"
android:id="@+id/bt_xiangce"/>
< /LinearLayout>
//-------------我的MainActivity -------------------------
package tckpicture.bwie.com.tackpicture2;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import okhttp3.Request;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView iv_img;
private Button bt_camera;
private Button bt_xiangce;
private static final int PHOTO_REQUEST_CAREMA = 1; // 拍照
private static final int PHOTO_REQUEST_GALLERY = 2; // 从相册中选择
private static final int PHOTO_REQUEST_CUT = 3; // 结果
/* 头像名称 */
private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
private File tempFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
iv_img = (ImageView) findViewById(R.id.iv_img);
bt_camera = (Button) findViewById(R.id.bt_camera);
bt_xiangce = (Button) findViewById(R.id.bt_xiangce);
//从SharedPreferences获取图片
getBitmapFromSharedPreferences();
bt_camera.setOnClickListener(this);
bt_xiangce.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_camera:
// 激活相机
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// 判断存储卡是否可以用,可用进行存储
if (hasSdcard()) {
tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
// 从文件中创建uri
Uri uri = Uri.fromFile(tempFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
}
// 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CAREMA
startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
break;
case R.id.bt_xiangce:
// 激活系统图库,选择一张图片
Intent intent1 = new Intent(Intent.ACTION_PICK);
intent1.setType("image/*");
// 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_GALLERY
startActivityForResult(intent1, PHOTO_REQUEST_GALLERY);
break;
}
}
/*
* 判断sdcard是否被挂载
*/
private boolean hasSdcard() {
//判断SD卡手否是安装好的media_mounted
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
}
/*
* 剪切图片
*/
private void crop(Uri uri) {
// 裁剪图片意图
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
// 裁剪框的比例,1:1
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// 裁剪后输出图片的尺寸大小
intent.putExtra("outputX", 250);
intent.putExtra("outputY", 250);
intent.putExtra("outputFormat", "JPEG"); // 图片格式
intent.putExtra("noFaceDetection", true); // 取消人脸识别
intent.putExtra("return-data", true);
// 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CUT
startActivityForResult(intent, PHOTO_REQUEST_CUT);
}
/**
*
* @param requestCode
* @param resultCode
* @param data
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PHOTO_REQUEST_GALLERY) {
// 从相册返回的数据
if (data != null) {
// 得到图片的全路径
Uri uri = data.getData();
crop(uri);
}
} else if (requestCode == PHOTO_REQUEST_CAREMA) {
// 从相机返回的数据
if (hasSdcard()) {
crop(Uri.fromFile(tempFile));
} else {
Toast.makeText(MainActivity.this, "未找到存储卡,无法存储照片!", Toast.LENGTH_SHORT).show();
}
} else if (requestCode == PHOTO_REQUEST_CUT) {
// 从剪切图片返回的数据
if (data != null) {
Bitmap bitmap = data.getParcelableExtra("data");
/**
* 获得图片
*/
iv_img.setImageBitmap(bitmap);
//保存到SharedPreferences
saveBitmapToSharedPreferences(bitmap);
}
try {
// 将临时文件删除
tempFile.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
//保存图片到SharedPreferences
private void saveBitmapToSharedPreferences(Bitmap bitmap) {
// Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
//第一步:将Bitmap压缩至字节数组输出流ByteArrayOutputStream
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
//第二步:利用Base64将字节数组输出流中的数据转换成字符串String
byte[] byteArray = byteArrayOutputStream.toByteArray();
String imageString = new String(Base64.encodeToString(byteArray, Base64.DEFAULT));
//第三步:将String保持至SharedPreferences
SharedPreferences sharedPreferences = getSharedPreferences("testSP", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("image", imageString);
editor.commit();
//上传头像
setImgByStr(imageString,"");
}
/**
* 上传头像此处使用用的OKHttp post请求上传的图片
* @param imgStr
* @param imgName
*/
publicvoid setImgByStr(String imgStr, String imgName) {
String url = "http://appserver。。。。。。。";
Map< String, String> params = new HashMap< String, String> ();
params.put("id", "参数值"); //
params.put("data", imgStr);
OkHttp.postAsync(url, params, new OkHttp.DataCallBack() {
@Override
public void requestFailure(Request request, IOException e) {
Log.i("上传失败", "失败" + request.toString() + e.toString());
}
@Override
public void requestSuccess(String result) throws Exception {
Log.i("上传成功", result);
}
});
}
//从SharedPreferences获取图片
private void getBitmapFromSharedPreferences(){
SharedPreferences sharedPreferences=getSharedPreferences("testSP", Context.MODE_PRIVATE);
//第一步:取出字符串形式的Bitmap
String imageString=sharedPreferences.getString("image", "");
//第二步:利用Base64将字符串转换为ByteArrayInputStream
byte[] byteArray=Base64.decode(imageString, Base64.DEFAULT);
if(byteArray.length==0){
iv_img.setImageResource(R.mipmap.ic_launcher);
}else{
ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(byteArray);
//第三步:利用ByteArrayInputStream生成Bitmap
Bitmap bitmap= BitmapFactory.decodeStream(byteArrayInputStream);
iv_img.setImageBitmap(bitmap);
}
}
}
//下面是我封装的一个 OKHttp
注意:需要在build.gradle 中添加下面这句,然后在同步一下
compile \'com.squareup.okhttp3:logging-interceptor:3.4.2\'
//----------下面是封装的OKHttp类------------------
package tckpicture.bwie.com.tackpicture2;
import android.os.Handler;
import android.os.Looper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
/**
* Created by fan on 2016/11/9.
*/
public class OkHttp {
/**
* 静态实例
*/
private static OkHttp sOkHttpManager;
/**
* okhttpclient实例
*/
private OkHttpClient mClient;
/**
* 因为我们请求数据一般都是子线程中请求,在这里我们使用了handler
*/
private Handler mHandler;
/**
* 构造方法
*/
private OkHttp() {
//// 可以通过实现 Logger 接口更改日志保存位置
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//mClient = new OkHttpClient.Builder().addInterceptor(loggingInterceptor).build();
mClient = new OkHttpClient();
/**
* 在这里直接设置连接超时.读取超时,写入超时
*/
OkHttpClient.Builder builder = mClient.newBuilder();
builder.connectTimeout(10, TimeUnit.SECONDS);
builder.readTimeout(10, TimeUnit.SECONDS);
builder.writeTimeout(10, TimeUnit.SECONDS);
builder.addInterceptor(loggingInterceptor);
mClient = builder.build();
/**
* 如果是用的3.0之前的版本使用以下直接设置连接超时.读取超时,写入超时
*/
//client.setConnectTimeout(10, TimeUnit.SECONDS);
//client.setWriteTimeout(10, TimeUnit.SECONDS);
//client.setReadTimeout(30, TimeUnit.SECONDS);
/**
* 初始化handler
*/
mHandler = new Handler(Looper.getMainLooper());
}
/**
* 单例模式获取OkHttp实例
*
* @return
*/
public static OkHttp getInstance() {
if (sOkHttpManager == null) {
sOkHttpManager = new OkHttp();
}
return <
推荐阅读
- Android 样式 (style) 和主题(theme)
- 用安卓实现斐波那契数和最近点对问题
- Android Studio插件之快速findViewById(butterknife和Android CodeGenerator的使用)
- Android疑难杂症之android:configChanges="orientation" 无效
- Android NFC标签 开发深度解析 触碰的艺术
- 12个最佳门票转售网站推荐合集(适合买家和卖家)
- 如何在Windows 10笔记本电脑或PC上录制Zoom会议(分步指南)
- 如何在Windows 10家庭版或企业版中禁用Cortana(方法介绍)
- 如何自动关闭Windows 10笔记本电脑或计算机(4种方式介绍)