相机拍照即时保存,即时读取

拍照发feed,进入相机拍照界面,如果拍完了却不想发了,然后回到相册界面,要有你刚刚拍的那张,就是这么一个需求。

首先Camera的拍照方法camera.takePicture(null, null, new MyPictureCallback());
回调接口

1
2
3
4
5
6
7
8
9
10
11
12
13
private final class MyPictureCallback implements Camera.PictureCallback {

@Override
public void onPictureTaken(byte[] data, Camera camera) {
cameraParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(cameraParameters);
try {
saveToSDCard(data); // 保存图片到sd卡中
} catch (Exception e) {
e.printStackTrace();
}
}
}

下面就是这次我们要讲的重点了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
public void saveToSDCard(byte[] data) throws IOException {
File photo = this.getPhotoPath();
if (photo.exists()) {
photo.delete();
}
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
Matrix matrix = new Matrix();
//此处的degree有两个值,预防拍照反转,90度和270度,三星手机操蛋。你要判断处理一下,是90还是270.
matrix.postRotate(degree);
int width = bmp.getWidth();
int height = bmp.getHeight();
bmp = Bitmap.createBitmap(bmp, 0, 0, width, height, matrix, true);
try {
FileOutputStream e = new FileOutputStream(photo.getPath());
BufferedOutputStream bos = new BufferedOutputStream(e);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, e);
bos.write(data);
//如果要想把data保存到disk上面,你必须flush and sync刷新并同步一下
bos.flush();
e.getFD().sync();
bos.close();
if (scanSavedImage) {
MediaScannerConnection.scanFile(getActivity(), new String[]{photo.getPath()}, SCAN_TYPES, null);
}
} catch (IOException ie) {
Log.e(this.getClass().getSimpleName(), "Exception in setPreviewDisplay()", ie);
}
try {
//拍照完成跳到裁剪界面的逻辑处理
Intent intent = this.getIntent();
startActivity(intent);
finish();
}
} catch (Throwable e) {
e.printStackTrace();
}
}

protected File getPhotoPath() {
File dir = this.getPhotoDirectory();
dir.mkdirs();
return new File(dir, this.getPhotoFilename());
}

protected File getPhotoDirectory() {
if (this.photoDirectory == null) {
this.initPhotoDirectory();
}

return this.photoDirectory;
}

private void initPhotoDirectory() {
this.photoDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
}

protected String getPhotoFilename() {
String ts = (new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US)).format(new Date());
return "Photo_" + ts + ".jpg";
}

这些代码拿进你的项目就可以用。

版权声明:



除非注明,本博文章均为原创,转载请以链接形式标明本文地址。

坚持原创技术分享,您的支持将鼓励我继续创作!