package com.leju.esf.utils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.format.DateFormat;
import com.leju.esf.application.AppContext;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Date;
/**
* Description: 图片处理类
*/
public class ImageUtils {
//计算图片的缩放值
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 ? heightRatio : widthRatio;
}
return inSampleSize;
}
// 根据路径获得图片并压缩
public static File compressImage(String filePath) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, 640, 960);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bm = BitmapFactory.decodeFile(filePath, options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
int size = baos.toByteArray().length / 1024;
baos.reset();//重置baos即清空baos
if(size > 1024 * 4) { //判断如果图片大于4M,进行40%压缩
return getSmallBitmap(bm, 40);
}else if(size > 1024 * 2) { //判断如果图片大于2M,进行60%压缩
return getSmallBitmap(bm, 60);
}else if(size > 1024) { //判断如果图片大于1M,进行80%压缩
return getSmallBitmap(bm, 80);
}else if(size > 512) { //判断如果图片大于512k,进行90%压缩
return getSmallBitmap(bm, 90);
}
return getSmallBitmap(bm,100);
}
public static File getSmallBitmap(Bitmap bm, int quality){
String imageFolderPath = AppContext.getImageFolderPath();
if (imageFolderPath == null) {
return null;
}
String photo_path = imageFolderPath + DateFormat.format("yyyy-MM-dd-hh-mm-ss", new Date()) + ".jpg";
File file = new File(photo_path);
try {
bm.compress(Bitmap.CompressFormat.JPEG, quality, new FileOutputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
return file;
}
}
</pre><pre name="code" class="html">调用相机拍照
photo_path = AppContext.getImageFolderPath() + DateFormat.format("yyyy-MM-dd-hh-mm-ss", new Date()) + ".jpg";
imageUrl = Uri.fromFile(new File(photo_path));
if(imageUrl != null){
Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUrl);
startActivityForResult(intentCamera, SELECT_CRMERA);
}
</pre><pre name="code" class="html">.
上传服务器把图片的路径
if(imageUrl != null) {
filePath = getRealFilePath(mContext,imageUrl); //根据url获取图片的路径
file = ImageUtils.compressImage(filePath); //压缩后的图路径
params.put("file", file);
}
</pre><pre name="code" class="html">