看别人天天拿手机拍照,然后呢作为程序员自己就想做一个自己的照相机,下面实现了一个简易的自定义照相机
布局文件就是一个SurfaceView 加上一个按钮Button
<SurfaceView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="@+id/sv_main_surface"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/take"
android:text="拍照"
/>
压缩之后的图片会有点模糊,写入内存卡也是需要权限的
public class TakePhoto extends AppCompatActivity {
private SurfaceView sv_main_surface;
private Button take;
private Camera camera;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take_photo);
sv_main_surface = (SurfaceView) findViewById(R.id.sv_main_surface);
take = (Button) findViewById(R.id.take);
sv_main_surface.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
//打开相机
camera = Camera.open();
//设置参数
Camera.Parameters parameters = camera.getParameters();
parameters.setPictureFormat(PixelFormat.JPEG);
parameters.set("jpeg-quality", 85);
camera.setParameters(parameters);
//将画面展示到surfaceView
try {
camera.setPreviewDisplay(sv_main_surface.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
//开启预览效果
camera.startPreview();
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
}
});
take.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
camera.takePicture(null, null, new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] bytes, Camera camera) {
//图片压缩技术
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
try {
FileOutputStream fos = new FileOutputStream("/mnt/sdcard/G150820_" + System.currentTimeMillis() + ".png");
bitmap.compress(Bitmap.CompressFormat.PNG,85,fos);
camera.stopPreview();
camera.startPreview();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
}
});
}
}
清单文件的配置
<!--写入内存卡-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<!--打开相机的权限-->
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
由于相机问题,我们将它横屏,当然这也可以自己处理成竖屏了
<activity android:name=".TakePhoto"
android:screenOrientation="landscape"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>