天天看點

Android 圖檔Bitmap儲存到記憶體卡

一、什麼是Android中的Bitmap

Bitmap是Android系統中的圖像處理的最重要類之一。用它可以擷取圖像檔案資訊,進行圖像剪切、旋轉、縮放等操作,并可以指定格式儲存圖像檔案。

二、什麼是記憶體卡

SD卡存儲卡,是用于手機、數位相機、便攜式電腦、MP3和其他數位産品上的獨立存儲媒體,一般是卡片的形态,故統稱為“存儲卡”,又稱為“數位存儲卡”、“數字存儲卡”、“儲存卡”等。

三、圖檔為什麼要存在記憶體卡裡

部分手機的手機記憶體是不夠的,一個程式如果産生的圖檔量太大,很容易占用了寶貴的手機記憶體,是以安全起見,圖檔最好存放在記憶體卡中

四、如何存放

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;


public class BitmaptoCard {
	private static int FREE_SD_SPACE_NEEDED_TO_CACHE = 1;
	private static int MB = 1024 * 1024;


	/**
	 * 儲存Bitmap到sdcard
	 * 
	 * @param dir
	 * @param bm
	 * @param filename
	 * @param quantity
	 */
	public static boolean saveBmpToSd(String dir, Bitmap bm, String filename,
			int quantity, boolean recyle) {
		boolean ret = true;
		if (bm == null) {
			return false;
		}


		if (FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {
			bm.recycle();
			bm = null;
			return false;
		}


		File dirPath = new File(dir);


		if (!exists(dir)) {
			dirPath.mkdirs();
		}


		if (!dir.endsWith(File.separator)) {
			dir += File.separator;
		}


		File file = new File(dir + filename);
		OutputStream outStream = null;
		try {
			file.createNewFile();
			outStream = new FileOutputStream(file);
			bm.compress(Bitmap.CompressFormat.JPEG, quantity, outStream);
			outStream.flush();
			outStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			ret = false;
		} catch (IOException e) {
			e.printStackTrace();
			ret = false;
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
			ret = false;
		} finally {
			if (outStream != null) {
				try {
					outStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (recyle && !bm.isRecycled()) {
				bm.recycle();
				bm = null;
				Log.e("BitmaptoCard", "saveBmpToSd, recyle");
			}
		}


		return ret;
	}


	/**
	 * 儲存Bitmap到sdcard
	 * 
	 * @param dir
	 * @param bm
	 * @param filename
	 * @param quantity
	 */
	public static boolean saveBmpToSd(String dir, Bitmap bm, String filename,
			int quantity) {
		return saveBmpToSd(dir, bm, filename, quantity, false);
	}


	/**
	 * 儲存Bitmap到sdcard
	 * 
	 * @param dir
	 * @param bm
	 * @param filename
	 * @param quantity
	 */
	public static boolean saveBmpToSd(String dir, String srcFile,
			String filename, int quantity) {
		if (srcFile == null) {
			return false;
		}
		Bitmap bmp = BitmapFactory.decodeFile(srcFile);
		return saveBmpToSd(dir, bmp, filename, quantity);
	}


	/**
	 * 儲存Bitmap到sdcard
	 * 
	 * @param dir
	 * @param bm
	 * @param filename
	 * @param quantity
	 */
	public static boolean saveBmpToSd(String dir, String srcFile,
			String filename, int quantity, boolean recyle) {
		if (srcFile == null) {
			return false;
		}
		Bitmap bmp = BitmapFactory.decodeFile(srcFile);
		return saveBmpToSd(dir, bmp, filename, quantity, recyle);
	}


	/**
	 * 儲存Bitmap到sdcard
	 * 
	 * @param dir
	 * @param bm
	 * @param filename
	 * @param quantity
	 */
	public static boolean saveBmpToSd(String dir, String srcFile,
			String filename, int quantity, float size, boolean recyle) {
		if (srcFile == null) {
			return false;
		}
		Bitmap bmp = convertToThumb(readFileToBuffer(srcFile), size);
		return saveBmpToSd(dir, bmp, filename, quantity, recyle);
	}


	/**
	 * 儲存Bitmap到sdcard
	 * 
	 * @param dir
	 * @param bm
	 * @param filename
	 * @param quantity
	 */
	public static boolean saveBmpToSd(String dir, String srcFile,
			String filename, int quantity, float size) {
		if (srcFile == null) {
			return false;
		}
		Bitmap bmp = convertToThumb(readFileToBuffer(srcFile), size);
		return saveBmpToSd(dir, bmp, filename, quantity);
	}


	/**
	 * 儲存Bitmap到sdcard
	 * 
	 * @param dir
	 * @param bm
	 * @param filename
	 * @param quantity
	 */
	public static boolean saveBmpToSd(String dir, Bitmap bmp, String filename,
			int quantity, float size) {
		if (bmp == null) {
			return false;
		}
		bmp = convertToThumb(readBitmap(bmp), size);
		return saveBmpToSd(dir, bmp, filename, quantity);
	}


	/**
	 * 擷取sdcard路徑
	 * 
	 * @return
	 */
	public static String getSdcardPath() {
		return Environment.getExternalStorageDirectory().getPath()
				+ File.separator;
	}


	/**
	 * 驗證檔案是否存在
	 * 
	 * @param url
	 * @return
	 */
	public static boolean exists(String url) {
		File file = new File(url);


		return file.exists();
	}


	/**
	 * 檢測sdcard可用空間
	 * 
	 * @return
	 */
	public static int freeSpaceOnSd() {
		StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
				.getPath());


		double sdFreeMB = ((double) stat.getAvailableBlocks() * (double) stat
				.getBlockSize()) / MB;


		return (int) sdFreeMB;
	}


	/**
	 * Bitmap --> byte[]
	 * 
	 * @param bmp
	 * @return
	 */
	private static byte[] readBitmap(Bitmap bmp) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bmp.compress(Bitmap.CompressFormat.JPEG, 60, baos);
		try {
			baos.flush();
			baos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return baos.toByteArray();
	}


	/**
	 * 儲存Bitmap到sdcard
	 * 
	 * @param dir
	 * @param bm
	 * @param filename
	 * @param quantity
	 */
	public static boolean saveBmpToSd(String filePath, Bitmap bm, int quantity) {
		if (filePath == null) {
			return false;
		}


		int end = filePath.lastIndexOf(File.separator);
		String dir = filePath.substring(0, end);
		String filename = filePath.substring(end);


		return saveBmpToSd(dir, bm, filename, quantity);
	}


	/**
	 * @description: 通過檔案路徑将對應檔案轉為byte[]
	 * @param fileName
	 * @return
	 */
	public static byte[] getByte(String fileName) {
		if (fileName == null || "".equals(fileName)) {
			return new byte[0];
		}
		File file = new File(fileName);
		if (file.exists()) {
			try {
				FileInputStream fin = new FileInputStream(fileName);
				int length = fin.available();
				byte[] buffer = new byte[length];
				fin.read(buffer);
				// res = EncodingUtils.getString(buffer, "UTF-8");
				fin.close();
				return buffer;
			} catch (Exception e) {
				Log.e("BitmaptoCard", "getByte fail:" + fileName);
				return new byte[0];
			}
		} else {
			Log.e("BitmaptoCard", "getByte file no exists :" + fileName);
			return new byte[0];
		}


	}


	/**
	 * 将圖檔、語音或者檔案讀入到byte緩沖數組
	 * 
	 * @param filePath
	 * @return
	 */
	public static byte[] readFileToBuffer(String filePath) {
		if (filePath == null || filePath.trim().equals("")) {
			Log.e("BitmaptoCard", "readFileToBuffer, path is null:" + filePath);
			return null;
		}
		File file = new File(filePath);
		if (!file.exists()) {
			Log.e("BitmaptoCard", "readFileToBuffer, file is not exists:"
					+ filePath);
			return null;
		}


		byte[] buffer = new byte[(int) file.length()];
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			BufferedInputStream bis = new BufferedInputStream(fis);
			bis.read(buffer);
			bis.close();
		} catch (Exception e) {
			e.printStackTrace();
		}


		return buffer;
	}


	/**
	 * 檢查圖檔是否超過一定值,是則縮小
	 * 
	 * @param view
	 * @param strFileName
	 */
	public static Bitmap convertToThumb(byte[] buffer, float size) {
		// 擷取原圖寬度
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;


		options.inPurgeable = true;
		options.inInputShareable = true;


		Bitmap bm = BitmapFactory.decodeByteArray(buffer, 0, buffer.length,
				options);


		// 計算縮放比例
		float reSize = options.outWidth / size;


		if (options.outWidth > options.outHeight) {
			reSize = options.outHeight / size;
		}


		if (reSize <= 0) {
			reSize = 1;
		}


		Log.d("BitmaptoCard", "convertToThumb, reSize:" + reSize);


		// 縮放
		options.inJustDecodeBounds = false;
		options.inSampleSize = (int) reSize;


		if (bm != null && !bm.isRecycled()) {
			bm.recycle();
			bm = null;
			Log.e("BitmaptoCard", "convertToThumb, recyle");
		}


		bm = BitmapFactory.decodeByteArray(buffer, 0, buffer.length, options);


		if (bm == null) {
			Log.e("BitmaptoCard", "convertToThumb, decode fail:" + null);
			return null;
		}


		return bm;
	}


}
           

示例代碼:http://download.csdn.net/detail/stop_pig/7162695