存储从相机拍摄的图像

时间:2013-04-21 15:51:55

标签: android android-camera android-camera-intent

我可以通过以下意图拍摄照片

cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);

然后在onActivityResult方法中,我将拍摄的图像设置为ImageView并尝试使用以下功能将图像存储到SD卡

private void savePic(Bitmap bmp) {
    if(!isSDOK || !isSDWritable)
        return;



        String name = "TESTA";
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File file = new File(path,name+".jpg");


        path.mkdirs();
        ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
        bmp.compress(CompressFormat.JPEG, 100 /*ignored for PNG*/, bos); 
        byte[] bitmapdata = bos.toByteArray();
        ByteArrayInputStream bis = new ByteArrayInputStream(bitmapdata);

        try{
            InputStream is = bis;
            OutputStream os = new FileOutputStream(file);
            byte[] data = new byte[is.available()];
            is.read();
            os.write(data);
            is.close();
            os.close();
        }catch(Exception e){Log.e("IMAGE CONVERT ERR", e.toString());}
        return;
}

当我检查PICTURES文件夹时,我看到了文件,但图像是空白的,总是12kb。我不能使用上面的方法从位图文件中保存图像吗?

1 个答案:

答案 0 :(得分:1)

是的,根据CommonsWare评论,你可以像这样使用EXTRA_OUTPUT:

private void capturePhoto() {
    File root = new File(Environment.getExternalStorageDirectory(), "Folder");
    if (!root.exists()) {
        root.mkdirs();
    }
    File file = new File(root, "filename.jpeg");
    Uri outputFileUri = Uri.fromFile(file);

    Intent photoPickerIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
    photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    photoPickerIntent.putExtra("return-data", true);
    startActivityForResult(photoPickerIntent, TAKE_PICTURE);
}