通过拍照或者从相册里选择图片通过压缩并上传时很多应用的常用功能,记录一下实现过程
一:创建个临时文件夹用于保存压缩后需要上传的图片
/**
* path:存放图片目录路径
*/
private String path = Environment.getExternalStorageDirectory().getPath() + "/XXX/";
/**
* saveCatalog:保存文件目录
*/
private File saveCatalog; /**
* saveFile:保存的文件
*/
private File saveFile; public String createOrGetFilePath(String fileName, Context mContext) {
saveCatalog = new File(path);
if (!saveCatalog.exists()) {
saveCatalog.mkdirs();
}
saveFile = new File(saveCatalog, fileName);
try {
saveFile.createNewFile();
} catch (IOException e) {
Toast.makeText(mContext, "创建文件失败,请检查SD是否有足够空间", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return saveFile.getAbsolutePath();
}
二:通过对话框选择获得图片方式(拍照或者相册) <string-array name="get_image_way">
<item >拍照</item>
<item >相册</item>
</string-array>
private String[] image;
image = getResources().getStringArray(R.array.get_image_way); /**
* TODO 通过拍照或者图册获得照片
*
* @author {author wangxiaohong}
*/
private void selectImage() {
// TODO Auto-generated method stub
String state = Environment.getExternalStorageState();
if (!state.equals(Environment.MEDIA_MOUNTED)) {
Util.showToast(this, getResources().getString(R.string.check_sd)); //检查SD卡是否可用
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.pick_image).setItems(image,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (image[which].equals(getString(R.string.my_data_image_way_photo))) {
getImageByPhoto();
} else {
getImageByGallery();
}
}
});
builder.create().show();
} private void getImageByGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_RESULT);
}
public String getPath(String carId, String fileName, Context mContext) {
File saveCatalog = new File(Constant.CACHE, carId);
// saveCatalog = new File(path);
if (!saveCatalog.exists()) {
saveCatalog.mkdirs();
}
saveFile = new File(saveCatalog, fileName);
try {
saveFile.createNewFile();
} catch (IOException e) {
Toast.makeText(mContext, "创建文件失败,请检查SD是否有足够空间", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return saveFile.getAbsolutePath(); }
private void getImageByPhoto() {
public static final String CACHE = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/pinchebang/";
path = util.getPath(user.getCar().getCarId() + "", mPhotoName, PersonalInfoActivity.this);
imageUri = Uri.fromFile(new File(path));
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, CAMERA_RESULT);
}
三:在onActivityResult中得到的图片做压缩处理
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) return;
Bitmap bitmap = null;
if (requestCode == CAMERA_RESULT) {
bitmap = util.getSmallBitmap(PersonalInfoActivity.this, path);
boolean flag = util.save(PersonalInfoActivity.this, path, bitmap);
} else if (requestCode == IMAGE_RESULT) {
Uri selectedImage = data.getData();
path = util.getImagePath(PersonalInfoActivity.this, selectedImage);
bitmap = util.getSmallBitmap(PersonalInfoActivity.this, path);
String pcbPathString = util.getPath(user.getCar().getCarId() + "", mPhotoName,
PersonalInfoActivity.this);
;
util.save(PersonalInfoActivity.this, pcbPathString, bitmap);
path = pcbPathString;
}
if (null != bitmap) {
mypicture.setImageBitmap(bitmap);
HttpUtil.uploadFile(PersonalInfoActivity.this, path, "userImg",
Constant.URL_VERIFY_DRIVER);
// MemoryCache memoryCache = new MemoryCache();
// memoryCache.put(url, bitmap);
}
}
上面对应的压缩方法 /**
* TODO filePath:图片路径
*
* @author {author wangxiaohong}
*/
public Bitmap getSmallBitmap(Context mContext, String filePath) {
DisplayMetrics dm;
dm = new DisplayMetrics();
((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(dm);
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, dm.widthPixels, dm.heightPixels);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
} public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) { // Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth); // Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
} /**
* TODO 保存并压缩图片 将bitmap 保存 到 path 路径的文件里
*
* @author {author wangxiaohong}
*/
public boolean save(Context mContext, String path, Bitmap bitmap) {
DisplayMetrics dm;
dm = new DisplayMetrics();
((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(dm);
if (path != null) {
try {
// FileCache fileCache = new FileCache(mContext);
// File f = fileCache.getFile(url);
File f = new File(path);
FileOutputStream fos = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos);
saveMyBitmap(bitmap);
return true;
} catch (Exception e) {
return false;
}
} else {
return false;
}
} private void saveMyBitmap(Bitmap bm) {
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(saveFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bm.compress(Bitmap.CompressFormat.JPEG, 70, fOut);
try {
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
} public String getPath(String carId, String fileName, Context mContext) {
File saveCatalog = new File(Constant.CACHE, carId);
// saveCatalog = new File(path);
if (!saveCatalog.exists()) {
saveCatalog.mkdirs();
}
saveFile = new File(saveCatalog, fileName);
try {
saveFile.createNewFile();
} catch (IOException e) {
Toast.makeText(mContext, "创建文件失败,请检查SD是否有足够空间", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return saveFile.getAbsolutePath(); } /**
* TODO 获得相册选择图片的图片路径
*
* @author {author wangxiaohong}
*/
public String getImagePath(Context mContext, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = mContext.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String ImagePath = cursor.getString(column_index);
cursor.close();
return ImagePath;
}
四:上传
public static void uploadFile(Context mContext, String path, String modelValue, String url) {
new PhotoUploadAsyncTask(mContext).execute(path, modelValue, url);
} class PhotoUploadAsyncTask extends AsyncTask<String, Integer, String> {
// private String url = "http://192.168.83.213/receive_file.php";
private Context context; public PhotoUploadAsyncTask(Context context) {
this.context = context;
} @Override
protected void onPreExecute() {
} @SuppressWarnings("deprecation")
@Override
protected String doInBackground(String... params) {
// 保存需上传文件信息
MultipartEntityBuilder entitys = MultipartEntityBuilder.create();
entitys.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entitys.setCharset(Charset.forName(HTTP.UTF_8));
File file = new File(params[0]);
entitys.addPart("image", new FileBody(file));
entitys.addTextBody("model", params[1]);
HttpEntity httpEntity = entitys.build();
return HttpUtil.uploadFileWithpost(params[2], context, httpEntity);
} @Override
protected void onProgressUpdate(Integer... progress) {
} @Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
} } /**
* 用于文件上传
*
* @param url
* @param mContext
* @param entity
* @return
*/
@SuppressWarnings("deprecation")
public static String uploadFileWithpost(String url, Context mContext, HttpEntity entity) {
Util.printLog("开始上传");
try {
setTimeout(); httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
// 设置连接超时时间
// httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
// 5000);
HttpPost upPost = new HttpPost(url);
upPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(upPost, httpContext);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return mContext.getString(R.string.upload_success);
}
} catch (Exception e) {
Util.printLog("上传报错");
e.printStackTrace();
}
// finally {
// if (httpClient != null && httpClient.getConnectionManager() != null)
// {
// httpClient.getConnectionManager().shutdown();
// }
// }
Util.printLog("上传成功");
return mContext.getString(R.string.upload_fail);
}