干了一段时间的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);
}
}
}