1.首先我们需要声明几个变量
TreeMap<String, String> paramsMap;.
RequestBody requestBody = null;
Request request;
Response response;
String result;
2.上传图片需要用到的方法
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();//单一一个线程
private void startUpload(List<File> files) {
for (File file : files) {
final File tempFiles = file;
// 保存上传文件的对象
final File tempFile = tempFiles;
// 开启异步请求
singleThreadExecutor.execute(new Runnable() {
@Override
public void run() {
Okhttp3Utils okhttp3Utils = new Okhttp3Utils();
// // 封装 OkHttpClient
final OkHttpClient client = okhttp3Utils.getOkhttpClict(60 * 2, 2, 2);
// 封装 MultipartBody
final MultipartBody.Builder builder = new MultipartBody
.Builder().setType(MultipartBody.FORM);
try {
String fileName = tempFile.getName();
Log.e(TAG, "fileName:" + fileName);
builder.addFormDataPart("file", file.getName(),
RequestBody.create(MediaType.parse("image/*"), file));
requestBody = builder.build();
request = new Request
.Builder()
.post(requestBody)
.url(getUrl(paramsMap))
.build();
response = client
.newCall(request)
.execute();
result = response.body().string();
Log.e(TAG, "result = " + result);
} catch (Exception e) {
//添加 上传失败的图片对象
Log.e(TAG, e.getMessage() + "||" + e.toString());
}
}
});
}
}
//本方法主要是拼接上传图片资源地址
private String getUrl(TreeMap<String, String> map) {
String url = Urls.uploadMediaURL;//上传图片地址
String module = map.get(Params.module);//模块名称
String year = map.get(Params.year);//年
String month = map.get(Params.month);//月
url += "/" + module + "/" + year + "/" + month;//拼接
Log.e(TAG, "URL:" + url);//打印地址
return url;//返回值
}
3.调用图片上传方法+赋值图片资源
String compassPicPath = CompassPicUtils.compassPic(context, registrationBean.getPictureimage2(), mSaveFilePath);//图片压缩
Log.e("查看上传地址", compassPicPath);
jiedianbean.setPictureimage2(compassPicPath);//图片名称上传所需要的bean,在这里赋值,如果上传过可以把这里注释掉
// 3、封装参数
Calendar calendar = Calendar.getInstance();
final TreeMap<String, String> paramsMap = new TreeMap<>();
paramsMap.put(Params.year, calendar.get(Calendar.YEAR) + "");
paramsMap.put(Params.month, (calendar.get(Calendar.MONTH) + 1) + "");
paramsMap.put(Params.module, "设备验收");
// 上传失败需要用的参数:
paramsMap.put(ConstantValue.FailQueue_MoudleTypeKey, "1");
this.paramsMap = paramsMap;
final List<File> fileList = new ArrayList<>();
fileList.add((new File(compassPicPath)));
startUpload(fileList);
4.CompassPicUtils压缩图片类
package cn.kaitong.com.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import me.android.framework.base.L;
/**
* Created by ${MaXiaoYin} on 2017/5/15.
*/
public class CompassPicUtils {
static String TAG = "CompassPicUtils";
/********************************** 在转换的时候使用绝对路径,避免出错 ****************************
* @param compassDir 需要保存的路径: 如:c:\\XunJian
* @param sourcePath 需要压缩图片的路径:如: d:\\Safe\\3.jpg
*/
public static String compassPic(Context context, String sourcePath, String compassDir) {
int targetDensity = context.getResources().getDisplayMetrics().densityDpi;
// int width =700;
// int height =850;
// int width =1080;
// int height =1920;
// int width =1080 ;
// int height =960 ;
int width = 960;
int height = 1080;
File oldFile = new File(sourcePath);
String fileName = oldFile.getName();
Log.e(TAG, "fileName:" + fileName);
String compassFileName = DatePicerUtil.long2String(System.currentTimeMillis(), ConstantValue.Data_DateFormat)
+ "_" + (int) (Math.random() * 100) + "_" + fileName.hashCode() + ".jpg";
File newDirFile = new File(compassDir);
if (!newDirFile.exists())
newDirFile.mkdirs();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// options.inPreferredConfig = Bitmap.Config.RGB_565;
// ************密度*********
// options.inTargetDensity = (int) (targetDensity*0.6);
BitmapFactory.decodeFile(oldFile.getAbsolutePath(), options);
long halfM = 500;
int inSampleSize = calculateInSampleSize(options, width, height);
// 压缩后的绝对路径:
String compassFilePath = compassDir + File.separator + compassFileName;
compassFilePath = new File(compassFilePath).getAbsolutePath();
long fileSize = FileUtils.getFileSize(sourcePath);
long fileSize2 = FileUtils.getFileSize(compassFilePath);
Log.e(TAG, "源文件大小:" + fileSize + " 压缩后的文件大小:" + fileSize2);
// 如果已经压缩过,或者文件质量小于(1/3)M的时候不在压缩:
int qualityNum = 90;
if (inSampleSize > 1 || FileUtils.getFileSize(sourcePath) / 1024 > halfM) {
// 1、将文件压缩到指定的目录:
options.inSampleSize = inSampleSize;
options.inJustDecodeBounds = false;
options.outWidth = 960;
options.outHeight = 1080;
int degree = readPictureDegree(sourcePath);
Bitmap bitmap = rotateBitmap(degree, BitmapFactory.decodeFile(sourcePath, options));
// bitmap = BitmapFactory.decodeFile(sourcePath, options);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(compassFilePath);
// *************80%的质量*********** 如果不压缩是100,表示压缩率为0
// boolean isOk = bitmap.compress(Bitmap.CompressFormat.JPEG, 60, fos);
boolean isOk = bitmap.compress(Bitmap.CompressFormat.JPEG, qualityNum, fos);
Log.e(TAG, "压缩ok:" + isOk);
Log.e(TAG, "源文件大小:" + FileUtils.getFileSize(sourcePath) + " 压缩后的文件大小:" + FileUtils.getFileSize(compassFilePath) + " inSampleSize:" + inSampleSize + " 压缩后的绝对路径:" + compassFilePath);
// 2、删除 之前的文件:
// if (isOk)
//oldFile.delete();
long fileSize1 = FileUtils.getFileSize(compassFilePath);
Log.e(TAG, "压缩后大小:" + fileSize1);
while (FileUtils.getFileSize(compassFilePath) / 1024 > halfM) {
qualityNum -= 10;
isOk = bitmap.compress(Bitmap.CompressFormat.JPEG, qualityNum, fos);
}
} catch (FileNotFoundException e) {
compassFilePath = sourcePath;
Log.e(TAG, "压缩" + e.getMessage() + "||" + e.toString());
}
} else {
// 1、将文件拷贝到指定的目录:
FileInputStream fis;
FileOutputStream fos;
try {
fis = new FileInputStream(sourcePath);
fos = new FileOutputStream(compassFilePath);
byte[] bytes = new byte[1024 * 16];
int length;
long count = 0;
while ((length = fis.read(bytes)) > 0) {
fos.write(bytes, 0, length);
count += length;
Log.e(TAG, "COUNT;" + count);
}
fos.flush();
fis.close();
fos.close();
// 2、删除 之前的文件:
//oldFile.delete();
} catch (Exception e) {
compassFilePath = sourcePath;
Log.e(TAG, "跳过压缩:" + e.getMessage() + "||" + e.toString());
}
}
return compassFilePath;
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio;
}
Log.e(TAG, "width = " + width + " height = " + height + " inSampleSize = " + inSampleSize);
return inSampleSize;
}
/**
* 重命名
*
* @param sourcePath 源文件名
* @param compassDir 文件夹
*/
public static String renameFile(String sourcePath, String compassDir) {
File file = new File(sourcePath);
String compassFileName = DatePicerUtil.long2String(System.currentTimeMillis(), ConstantValue.Data_DateFormat)
+ "_" + (int) (Math.random() * 100) + "_" + file.getName().hashCode() + ".jpg";
File newFile = new File(compassDir + "/" + compassFileName);
boolean isOk = file.renameTo(newFile);
Log.i(TAG, "isOk =" + isOk + " newFile=" + newFile.getAbsolutePath() + " sourcePath=" + sourcePath);
if (isOk) {
return newFile.getAbsolutePath();
} else {
return sourcePath;
}
}
/**
* 图片、视频
* 重命名
*
* @param sourcePath 源文件名
* @param sourcePath2 结果文件名
*/
public static String renameFile2(String sourcePath, String sourcePath2) {
File file = new File(sourcePath);
File newFile = new File(sourcePath2);
boolean isOk = file.renameTo(newFile);
Log.i(TAG, "isOk =" + isOk + " newFile=" + newFile.getAbsolutePath() + " sourcePath=" + sourcePath);
if (isOk) {
return newFile.getAbsolutePath();
} else {
return sourcePath;
}
}
//读取图片旋转角度
public static int readPictureDegree(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
Log.e("readPictureDegree :", "orientation = " + orientation);
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
degree = 90;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
degree = 180;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
degree = 270;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}
//旋转图片
public static Bitmap rotateBitmap(int angle, Bitmap bitmap) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
Bitmap rotation = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
matrix, true);
return rotation;
}
}
5.DatePicerUtil类
/**
* @param dateLongMills 要求是 System.current() 格式:
* @param dateFormat 要返回的 日期格式,如:yyyy-MM-dd HH:mm
* @return
*/
public static String long2String(long dateLongMills, String dateFormat) {
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
return sdf.format(new Date(dateLongMills));
}
6.file类
public static long getFileSize(String path){
if (TextUtils.isEmpty(path))
return 0;
else
return new File(path).length();
}