簡單實用的android 圖片的壓縮

pszh發表於2016-04-28

上傳圖片的時候我們經常因為圖片太大問題要進行壓縮圖片的;本例子通過拍照得到一張圖片來進行壓縮展示的


直接貼程式碼了(因為都比較簡單,註釋的話很清楚,主要的操作還是在最後一步):

首先看下工具類

<span style="font-size:14px;">package com.example.compressphoto;

import java.io.ByteArrayOutputStream;
import java.io.File;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.util.Base64;

public class PictureUtil {


	/**
	 * 把bitmap轉換成String
	 * 
	 * @param filePath
	 * @return
	 */
	public static String bitmapToString(String filePath) {

		Bitmap bm = getSmallBitmap(filePath);
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
		byte[] b = baos.toByteArray();
		
		return Base64.encodeToString(b, Base64.DEFAULT);
		
	}

	/**
	 * 計算圖片的縮放值
	 * 
	 * @param options
	 * @param reqWidth
	 * @param reqHeight
	 * @return
	 */
	public static 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;
	}

	
	/**
	 * 根據路徑獲得突破並壓縮返回bitmap用於顯示
	 * 
	 * @param imagesrc
	 * @return
	 */
	public static Bitmap getSmallBitmap(String filePath) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, options);

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, 480, 800);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;

		return BitmapFactory.decodeFile(filePath, options);
	}

	/**
	 * 根據路徑刪除圖片
	 * 
	 * @param path
	 */
	public static void deleteTempFile(String path) {
		File file = new File(path);
		if (file.exists()) {
			file.delete();
		}
	}

	/**
	 * 新增到相簿
	 */
	public static void galleryAddPic(Context context, String path) {
		Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		File f = new File(path);
		Uri contentUri = Uri.fromFile(f);
		mediaScanIntent.setData(contentUri);
		context.sendBroadcast(mediaScanIntent);
	}

	/**
	 * 獲取儲存圖片的目錄
	 * 
	 * @return
	 */
	public static File getAlbumDir() {
		File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				getAlbumName());
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return dir;
	}

	/**
	 * 獲取 儲存圖片資料夾名稱
	 * 
	 * @return
	 */
	public static String getAlbumName() {
		return "picture";
	}
}</span>

首先是呼叫拍照

<span style="font-size:14px;">/**
	 * 拍照*/
	public void takephono(View view){
		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		try {
			// 指定存放拍攝照片的位置
			File f = createImageFile();
			takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
			startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}</span>


<span style="font-size:14px;">/**
	 * 把程式拍攝的照片放到 SD卡的 Pictures目錄中 picture 資料夾中
	 * 照片的命名規則為:wzy_20160428_173729.jpg
	 * 
	 * @return
	 * @throws IOException
	 */
	@SuppressLint("SimpleDateFormat")
	private File createImageFile() throws IOException {

		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss"); 
		String timeStamp = format.format(new Date());
		String imageFileName = "wzy_" + timeStamp + ".jpg";

		File image = new File(PictureUtil.getAlbumDir(), imageFileName);
		
		mCurrentPhotoPath = image.getAbsolutePath();
		return image;
	}</span>



再是對拍照返回的操作

<span style="font-size:14px;">@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_TAKE_PHOTO) {
			if (resultCode == Activity.RESULT_OK) {
				// 新增到相簿,這樣可以在手機的相簿程式中看到程式拍攝的照片
				PictureUtil.galleryAddPic(this, mCurrentPhotoPath);
				againImage.setImageBitmap(BitmapFactory.decodeFile(mCurrentPhotoPath));//不知道為啥就是顯示不出來
			} else {
				
				// 取消照相後,刪除已經建立的臨時檔案。
				PictureUtil.deleteTempFile(mCurrentPhotoPath);
				mCurrentPhotoPath =null;
			}
		}
	}</span>

然後就是我們關注的壓縮的操作(給壓縮之後的圖片建立一個新的檔案,所以我們上傳伺服器的檔案路徑就得用這個了)

<span style="font-size:14px;">/**
	 * 壓縮
	 * (多檔案壓縮使用迴圈的方法就,可以了)
	 * */
	public void compressPhoto(View view){
		if (mCurrentPhotoPath != null) {
			try {
				
				File f = new File(mCurrentPhotoPath);
				Bitmap bm = PictureUtil.getSmallBitmap(mCurrentPhotoPath);
				//新的壓縮之後的圖片的路徑是“原路徑,只不過在名字之前加了一個small_”
				FileOutputStream fos = new FileOutputStream(new File(PictureUtil.getAlbumDir(), "small_" + f.getName()));
				bm.compress(Bitmap.CompressFormat.JPEG, 40, fos);//這裡壓縮40%,把壓縮後的資料存放到fos中  
				
				nowImage.setImageBitmap(PictureUtil.getSmallBitmap(PictureUtil.getAlbumDir()+"/"+"small_" + f.getName()));
				Log.i("原始檔案的大小", f.length()+"");
				Log.i("壓縮後檔案的大小",new File(PictureUtil.getAlbumDir(), "small_" + f.getName()).length()+"");

			} catch (Exception e) {
				e.printStackTrace();
			}

		} else {
			Toast.makeText(this, "請先點選拍照按鈕拍攝照片", Toast.LENGTH_SHORT).show();
		}
	}</span>


最後demo下載連結http://www.oschina.net/code/snippet_2702417_55777



看到的一個圖片壓縮 框架 luban(魯班):https://github.com/bai53229/Luban


相關文章