压缩本地图片并上传至服务器

时间:2022-09-18 22:40:15

实现思路 先从本地图库中获取图片路径,再进行压缩保存图片到新的路径,最后上传该图片.

1.获取系统图片路径:

private void getImgPic() {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMG);
}
 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMG&& resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };

Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
mImageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
//todo 压缩文件
if(picturePath!=null)compressImageFile(picturePath);
LogUtil.e("img path--"+picturePath);
}
}

2.压缩图片方法

  private void  compressImageFile(String  path){
//先将所选图片转化为流的形式,path所得到的图片路径
FileInputStream is = null;
try {
is = new FileInputStream(path);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int size = 4;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = size;
//将图片缩小为原来的 1/size ,不然图片很大时会报内存溢出错误
Bitmap image = BitmapFactory.decodeStream(is,null,options);
//显示在本地
// mImageView.setImageBitmap(image);
try {
if(is!=null) is.close();
} catch (IOException e) {
e.printStackTrace();
}

//定义一个file,为压缩后的图片 File f = new File("图片保存路径","图片名称");
newPath=MakeTopicActivity.this.getCacheDir().getAbsolutePath()+"/topicImages.jpg";
File file=new File(newPath);
if(file.exists()){
file.delete();
}
try {
file.createNewFile();
} catch (IOException e) {
LogUtil.e(e.getMessage());
}

ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//这里100表示不压缩,将不压缩的数据存放到baos中
int per = 100;
while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
baos.reset();// 重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, per, baos);// 将图片压缩为原来的(100-per)%,把压缩后的数据存放到baos中
per -= 10;// 每次都减少10
}
//回收图片,清理内存
if(image != null && !image.isRecycled()){
image.recycle();
image = null;
System.gc();
}
//将输出流写入到新文件
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(baos.toByteArray());
fos.flush();
fos.close();
baos.close();
//标记压缩图片成功
isCompressSuccess=true;
}catch (Exception e){
LogUtil.e(e.getMessage());
}
}