本文实例为大家分享了Android剪切和上传图片的具体代码,供大家参考,具体内容如下
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 detectionstartActivityForResult(intent, 1);}
2、在onActivityResult()方法中:
@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {// TODO Auto-generated method stubsuper.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,请求码为3startActivityForResult(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 blocke1.printStackTrace();}//string 文件上传服务器...}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。