幹了一段時間的android開發,發現還是把基礎搞好了,做實際項目纔會遊刃有餘。故收拾一下努力學習的心情,重新學習一下android的基礎知識。那麼先從media開始吧!
話不多說,今天就先搞一個簡單的Camera實例來熱熱身吧!
需要會的知識點:
BitmapFactory : 提供了很多靜態的方法,用來加載Bitmap image。 下面是屬性和方法的舉例:
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inSampleSize = 4;//inSampleSize是設置圖片顯示爲源圖片的 1/4
Bitmap bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
imv.setImageBitmap(bmp);
載入的是圖片在屏幕的現實大小,而不是圖片本身,可以通過Display來獲取屏幕的height和width
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
下面先來一張效果圖:
下面是源碼及註釋:
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class CameraActivity extends Activity {
final static int CAMERA_RESULT = 0;
ImageView imv;
String imageFilePath;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myPhoto.jpg";//圖片的存儲位置
Log.i("log", imageFilePath);
File imageFile = new File(imageFilePath);
Uri imageFileUri = Uri.fromFile(imageFile);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);//intetn的action
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);//獲取源圖片的map
startActivityForResult(intent, CAMERA_RESULT);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK)
{
imv = (ImageView) findViewById(R.id.image);
Display currentDisplay = getWindowManager().getDefaultDisplay();//獲取屏幕屬性 高和寬
int dw = currentDisplay.getWidth();
int dh = currentDisplay.getHeight();
BitmapFactory.Options bmpFacOptions = new BitmapFactory.Options();
bmpFacOptions.inJustDecodeBounds = true; //開始解析圖片,但載入的不是圖片本身
Bitmap bmp = BitmapFactory.decodeFile(imageFilePath, bmpFacOptions);
int heightRatio = (int) Math.ceil(bmpFacOptions.outHeight/(float)dh);//獲取壓縮比率
int widthRatio = (int) Math.ceil(bmpFacOptions.outWidth/(float)dw);
// 如果這個ratio都比 1 大, 顯示最大的作爲inSampleSize屬性的值
if (heightRatio > 1 && widthRatio > 1)
{
if (heightRatio > widthRatio)
{
bmpFacOptions.inSampleSize = heightRatio; //顯示爲原圖片的 1/heightRatio
}
else
{
bmpFacOptions.inSampleSize = widthRatio; //顯示爲原圖片的 1/widthRatio
}
}
// 開始真正的decode
bmpFacOptions.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeFile(imageFilePath, bmpFacOptions);
// 顯示
imv.setImageBitmap(bmp);
}
}
}