1、从Android系统相册选择一张图片getImageFromAlbum():
/**
* 从图库获得照片
*/
protected void getImageFromAlbum() {
isImgs = true;
// MainApplication.changeSettingStateus = true;
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");// 相片类型
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 360);
intent.putExtra("outputY", 360);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
// intent.putExtra("outputFormat",
// Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", true); // no face detection
startActivityForResult(intent, 1);
}
2、在onActivityResult()方法中:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
String text;
switch (requestCode) {
case 1:
Uri selectedImage = data.getData();
CutPic(selectedImage);
break;
case 3:// 对图片进行剪切
if (data != null) {
Bitmap bitmap = data.getParcelableExtra("data");
temps = zoomImage(bitmap, 360, 360);
// 上传图片
uploadImg(temps);
}
break;
default:
break;
}
}
}
3、图片剪切 CutPic(selectedImage);
/**
* 将图片裁剪到指定大小
*
* @param uri
* @param size
* @param flag
*/
public void CutPic(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", true);// 设置Intent中的view是可以裁剪的
// 设置宽高比
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// 设置裁剪图片的宽高
intent.putExtra("outputX", 360);
intent.putExtra("outputY", 360);
intent.putExtra("outputFormat", "JPEG");// 图片格式
// 设置是否返回数据
intent.putExtra("return-data", true);
// 开启一个带有返回值的Activity,请求码为3
startActivityForResult(intent, 3);
}
4、图片压缩剪切zoomImage(bitmap, 360, 360);
/***
* 图片的缩放方法
*
* @param bgimage
* :源图片资源
* @param newWidth
* :缩放后宽度
* @param newHeight
* :缩放后高度
* @return
*/
public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
double newHeight) {
// 获取这个图片的宽和高
float width = bgimage.getWidth();
float height = bgimage.getHeight();
// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
// 计算宽高缩放率
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 缩放图片动作
matrix.postScale(scaleWidth, scaleHeight);
Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
(int) height, matrix, true);
return bitmap;
}
5、上传图片文件至服务器uploadImg(bitMaps);
/**
* 上传图片
*
* @param bitP
*/
private void uploadImg(final Bitmap bitP) {
// 将Bitmap转换成字符串
String string = null;
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
bitP.compress(CompressFormat.JPEG, 100, bStream);
byte[] bytes = bStream.toByteArray();
string = Base64.encodeToString(bytes, Base64.DEFAULT);
try {
bStream.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//string 文件上传服务器...
}