popupwindow,拍照,相册,裁剪,压缩,保存sd卡,imageloader圆形加载到本地

这个博客展示了如何使用PopupWindow弹窗实现拍照、从相册选择图片,接着进行裁剪并压缩图片,最终将图片保存到SD卡,并通过ImageLoader加载圆形显示。整个流程包括调用相机、选择相册、裁剪图片、压缩图片到指定尺寸,并将其保存到外部存储。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.gc.flashview;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.td.app.xyf.pay.R;
import com.td.three.mmb.pay.view.BaseActivity;

</pre><pre name="code" class="java">
//整体步骤为:先调用popupwindow弹出选择项,选择拍照或者相册,图片送到裁剪程序进行处理,可以在对图片进行压缩,讲图片保存到SD卡,用ImageLoader读图片。
</pre><pre name="code" class="java">public class KtActivityAccountInfo extends BaseActivity implements
		OnClickListener {
	public static final int TAKE_PHOTO = 1;
	public static final int PICK_PHOTO = 2;
	public static final int CORP_PHOTO = 3;
	LinearLayout ll_icon;
	ImageView iv_icon;
	PopupWindow mPopupWindow;
	private final static String pictureLastName = "ktHeadImage.png";
	private File file = new File(Environment.getExternalStorageDirectory(),pictureLastName);
	int imageWidth = 120;
	int imageHeigth = 120;
	DisplayImageOptions options;

	// 裁剪后图片的宽(X)和高(Y),240 X 240的正方形。(生成bitmap貌似有时要报错?可试下把大小弄小点)
	private static int output_X = 240;
	private static int output_Y = 240;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.kt_activity_account_info);
		initKtView();
	}

	private void initKtView() {
		ll_icon = (LinearLayout) findViewById(R.id.kt_accountinfo_iconitem);
		ll_icon.setOnClickListener(this);
		iv_icon = (ImageView) findViewById(R.id.kt_accountinfo_icon);
		
		
		//设置 ImageLoader的参数
		 options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.kt_myaccount_auth) // 设置图片下载期间显示的图片
				.showImageForEmptyUri(R.drawable.kt_myaccount_head) // 设置图片Uri为空或是错误的时候显示的图片
				.showImageOnFail(R.drawable.kt_myaccount_help) // 设置图片加载或解码过程中发生错误显示的图片
				.resetViewBeforeLoading(false) // default 设置图片在加载前是否重置、复位
				.displayer(new RoundedBitmapDisplayer(94)) // 设置圆角图片
				.build();
		 
//		 加载头像
		ImageLoader.getInstance().displayImage("file://" + file.getPath(),iv_icon, options);
		
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		//头像
		case R.id.kt_accountinfo_iconitem:

			// make a popwindow
			mPopupWindow = new PopupWindow(KtActivityAccountInfo.this);
			View view = getLayoutInflater()
					.inflate(R.layout.kt_popwindow, null);
			LinearLayout tv_takaphoto = (LinearLayout) view
					.findViewById(R.id.kt_popwindow_takaphoto);
			LinearLayout tv_pickphoto = (LinearLayout) view
					.findViewById(R.id.kt_popwindow_pickphoto);
			LinearLayout tv_cancel = (LinearLayout) view
					.findViewById(R.id.kt_popwindow_cancel);
			RelativeLayout rv_popwindow = (RelativeLayout) view
					.findViewById(R.id.kt_popwindow_rl);
			rv_popwindow.setOnClickListener(this);
			tv_cancel.setOnClickListener(this);
			tv_pickphoto.setOnClickListener(this);
			tv_takaphoto.setOnClickListener(this);
			mPopupWindow.setContentView(view);
			mPopupWindow.setHeight(LayoutParams.MATCH_PARENT);
			mPopupWindow.setWidth(LayoutParams.MATCH_PARENT);
                        mPopupWindow.setAnimationStyle(R.style.kt_AnimBottom);
                        mPopupWindow.showAtLocation(KtActivityAccountInfo.this
					.findViewById(R.id.kt_accountinfo), Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);

			break;
//			拍照
		case R.id.kt_popwindow_takaphoto:
			takePicture();
			mPopupWindow.dismiss();
			break;
//			从相册中选择
		case R.id.kt_popwindow_pickphoto:
			pickPicture();
			mPopupWindow.dismiss();
			break;
//			取消
		case R.id.kt_popwindow_cancel:
			mPopupWindow.dismiss();
			break;
//			点击取消popupwindow
		case R.id.kt_popwindow_rl:
			Log.e("sydlog", "kt_popwindow_rl");
			mPopupWindow.dismiss();

			break;

		default:
			break;
		}

	}

	//调用系统照相机,拍照
	private void takePicture() {

		try {
			if (file.exists()) {
				file.delete();
			}
			file.createNewFile();
		} catch (Exception e) {
		}
		Intent intent = new Intent();
		intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
		startActivityForResult(intent, TAKE_PHOTO);
	}

	
//	从相册中选择图片
	private void pickPicture() {

		Intent intentPickPicture = new Intent();
		intentPickPicture.setAction(Intent.ACTION_GET_CONTENT);
		intentPickPicture.setType("image/*");
		startActivityForResult(intentPickPicture, PICK_PHOTO);

	}

//	处理拍照,相册选择,裁剪图片
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		switch (requestCode) {

		case TAKE_PHOTO:
			if (resultCode == RESULT_OK) {
				cropPhoto(Uri.fromFile(file));
			}
			break;
		case PICK_PHOTO:
			if (resultCode == RESULT_OK) {
				cropPhoto(data.getData());
			}
			break;
		case CORP_PHOTO:
			if (resultCode == RESULT_OK) {
				setImage(data);
			}

			break;
		}
	}

	/**
	 * 裁剪原始的图片
	 */
	public void cropPhoto(Uri uri) {

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");

		// 设置裁剪
		intent.putExtra("crop", "true");

		// aspectX , aspectY :宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);

		// outputX , outputY : 裁剪图片宽高
		intent.putExtra("outputX", output_X);
		intent.putExtra("outputY", output_Y);
		intent.putExtra("return-data", true);

		startActivityForResult(intent, CORP_PHOTO);
	}

	/**
	 * 提取保存裁剪之后的图片数据,并设置头像部分的View
	 */
	private void setImage(Intent intent) {
		Bundle extras = intent.getExtras();
		if (extras != null) {

			Bitmap photo = extras.getParcelable("data");
			try {
				// 存到SD卡中,下次启动APP直接从SD卡中读取
				saveBitmap(photo, file);
			} catch (Exception e) {
				e.printStackTrace();
			}

			
			ImageLoader.getInstance().displayImage("file://" + file.getPath(),iv_icon, options);
		} else {
			Toast.makeText(this, "拍照失败", Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * 计算一个bitmap图片的大小,大小单位为ByteA
	 * 
	 * @param bitmap
	 * @return
	 */

	public int getBitmapSize(Bitmap bitmap) {

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // API 19
			return bitmap.getAllocationByteCount();
		}
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {// API
																			// 12
			return bitmap.getByteCount();
		}
		return bitmap.getRowBytes() * bitmap.getHeight(); // earlier version
	}

	/**
	 * 对图片进行压缩,这种压缩为等质压缩,对png图片,基本没有效果,图片大小基本不变。
	 * 
	 * @param bm
	 * @param fileName
	 * @throws Exception
	 */
	public void saveBitmap(Bitmap bm, File fileName) throws Exception {
		try {
			if (file.exists()) {
				file.delete();
			}
			file.createNewFile();
		} catch (Exception e) {
		}
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(fileName));
		// 100表示不进行压缩,70表示压缩率为30%
		bm.compress(Bitmap.CompressFormat.PNG, 100, bos);
		bos.flush();
		bos.close();
	}

	/**
	 * 检测手机是否支持将拍照的图片放入到SD卡
	 * 
	 * @return
	 */
	protected boolean isSupportSDCard() {
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 按照给定的宽和高,进行压缩
	 * 
	 * @param pathName
	 *            文件路径
	 * @param targetWidth
	 *            压缩的宽度
	 * @param targetHeight
	 *            压缩的高度
	 * @return
	 */
	public Bitmap compressBySize(String pathName, int targetWidth,
			int targetHeight) {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = true;// 不去真的解析图片,只是获取图片的头部信息,包含宽高等;
		Bitmap bitmap = BitmapFactory.decodeFile(pathName, opts);
		// 得到图片的宽度、高度;
		float imgWidth = opts.outWidth;
		float imgHeight = opts.outHeight;
		Log.e("sydlog", "压缩前图片的宽度=" + imgWidth);
		Log.e("sydlog", "压缩前图片的高度=" + imgHeight);
		// 分别计算图片宽度、高度与目标宽度、高度的比例;取大于等于该比例的最小整数;
		int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);
		int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);
		opts.inSampleSize = 1;
		if (widthRatio > 1 || widthRatio > 1) {
			if (widthRatio > heightRatio) {
				opts.inSampleSize = widthRatio;
			} else {
				opts.inSampleSize = heightRatio;
			}
		}
		// 设置好缩放比例后,加载图片进内容;
		opts.inJustDecodeBounds = false;
		bitmap = BitmapFactory.decodeFile(file.getPath(), opts);

		Log.e("sydlog", "压缩后图片的宽度=" + bitmap.getWidth());
		Log.e("sydlog", "压缩后图片的高度=" + bitmap.getHeight());

		return bitmap;
	}
	
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值