本文实例为大家分享了Android实现上传图片功能的具体代码,供大家参考,具体内容如下
设定拍照返回的图片路径
/**
* 设定拍照返回的图片路径
* @param image 图片路径
* @param i 约定值
*/
protected void image(String image, int i) {
//创建file对象,用于存储拍照后的图片,这也是拍照成功后的照片路径
outputImage = new File(getExternalCacheDir(),image);
try {
//判断文件是否存在,存在删除,不存在创建
if (outputImage.exists()){
outputImage.delete();
}
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
//相机拍照返回图片路径
Uri photoUri;
//判断当前Android版本
if(Build.VERSION.SDK_INT>=24){
photoUri = FileProvider.getUriForFile(TextActivity.this,"包名.FileProvider",outputImage);
}else {
photoUri = Uri.fromFile(outputImage);
}
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(intent, i);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
调用系统相机拍照接受返回的图片路径
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_Y) {
getImageView(binding.imageY,"0");
}
if (requestCode == IMAGE_Q) {
getImageView(binding.imageQ,"1");
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
上传图片
/**
* 上传图片
* @param view 图片展示 view
*/
protected void getImageView(@NotNull ImageView view, String type) {
Bitmap photo = BitmapFactory.decodeFile(outputImage.getAbsolutePath());
view.setImageBitmap(photo);
int direction = 0;
try {
ExifInterface exif = new ExifInterface(String.valueOf(outputImage));
direction = Integer.parseInt(exif.getAttribute(ExifInterface.TAG_ORIENTATION));
} catch (IOException e) {
e.printStackTrace();
}
Matrix matrix = new Matrix();
Uri uri = Uri.fromFile(outputImage);
String f = uri.getPath();
Bitmap b = rotateBitmap(getBitmapFromUrl(f,900,1200),0);
switch (direction) {
case 1:
Log.d("图片方向","顶部,左侧(水平/正常)");
b = rotateBitmap(getBitmapFromUrl(f,900,1200),0);
break;
case 2:
b = rotateBitmap(getBitmapFromUrl(f,900,1200),0);
Log.d("图片方向","顶部,右侧(水平镜像)");
break;
case 3:
b = rotateBitmap(getBitmapFromUrl(f,900,1200),180);
Log.d("图片方向","底部,右侧(旋转180)");
break;
case 4:
matrix.postScale(1, -1);
b = Bitmap.createBitmap(b,0,0,900,1200,matrix,true);
Log.d("图片方向","底部,左侧(垂直镜像)");
break;
case 5:
matrix.postScale(-1, 1);
b = rotateBitmap(getBitmapFromUrl(f,900,1200),270);
b = Bitmap.createBitmap(b,0,0,900,1200,matrix,true);
Log.d("图片方向","左侧,顶部(水平镜像并顺时针旋转270)");
break;
case 6:
b = rotateBitmap(getBitmapFromUrl(f,900,1200),90);
Log.d("图片方向","右侧,顶部(顺时针旋转90)");
break;
case 7:
matrix.postScale(-1, 1);
b = rotateBitmap(getBitmapFromUrl(f,900,1200),90);
b = Bitmap.createBitmap(b,0,0,900,1200,matrix,true);
Log.d("图片方向","右侧,底部(水平镜像,顺时针旋转90度)");
break;
case 8:
b = rotateBitmap(getBitmapFromUrl(f,900,1200),270);
Log.d("图片方向","左侧,底部(顺时针旋转270)");
break;
default:
break;
}
try {
File files = new File(new URI(uri.toString()));
saveBitmap(b,files);
} catch (URISyntaxException e) {
e.printStackTrace();
}
try {
String file = uploadImage(networkApi.getFormal() + "setImage", uri.getPath(), code, userId);
TextBase.FileInfo fileInfo = new TextBase.FileInfo();
fileInfo.setFilePath(file);
mFileInfos.add(fileInfo);
model.load(file,type);
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* 上传图片
* @param url 上传接口路径
* @param imagePath 图片路径
* @param code 唯一标识
* @return 服务器图片的路径
* @throws IOException
* @throws JSONException
*/
public static String uploadImage(String url, String imagePath, String code, String userId) throws IOException, JSONException {
OkHttpClient okHttpClient = new OkHttpClient();
Log.d("imagePath", imagePath);
File file = new File(imagePath);
RequestBody image = RequestBody.create(MediaType.parse("image/jpg"), file);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", imagePath, image)
.addFormDataPart("fileOid", code)
.addFormDataPart("userId", userId)
.build();
Request request = new Request.Builder()
.url(url)
.addHeader("Authorization",令牌)
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = new JSONObject(response.body().string());
return jsonObject.optString("msg");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
其他工具类
/**
* 压缩图片的方法
* @param url
* @param width
* @param height
* @return
*/
public static Bitmap getBitmapFromUrl(String url, double width, double height) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; // 设置了此属性一定要记得将值设置为false
Bitmap bitmap = BitmapFactory.decodeFile(url);
// 防止OOM发生
options.inJustDecodeBounds = false;
int mWidth = bitmap.getWidth();
int mHeight = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidth = 1;
float scaleHeight = 1;
// 按照固定宽高进行缩放
if(mWidth <= mHeight) {
scaleWidth = (float) (width/mWidth);
scaleHeight = (float) (height/mHeight);
} else {
scaleWidth = (float) (height/mWidth);
scaleHeight = (float) (width/mHeight);
}
// 按照固定大小对图片进行缩放
matrix.postScale(scaleWidth, scaleHeight);
Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, mWidth, mHeight, matrix, true);
// 用完了记得回收
bitmap.recycle();
return newBitmap;
}
/**
* Android保存Bitmap到文件
* @param bitmap
* @param file
* @return
*/
public static boolean saveBitmap(Bitmap bitmap, File file) {
if (bitmap == null)
return false;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
/**
* 旋转图片
* @param bitmap 图片
* @param rotate 角度
* @return
*/
public static Bitmap rotateBitmap(Bitmap bitmap, int rotate) {
if (bitmap == null)
return null;
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix mtx = new Matrix();
mtx.postRotate(rotate);
return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
}