【问题标题】:Save image taken to a specific directory with specific name将拍摄的图像保存到具有特定名称的特定目录
【发布时间】:2016-06-13 11:35:00
【问题描述】:

我无法将拍摄的图像保存到具有特定名称的特定目录。我不知道该怎么做。下面是我的代码。

CameraCaptureImage.java

public class CaptureCameraImage extends Activity {

    public static int cameraID = 0;
    public static boolean isBlack = true;
    public static ImageView image;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activitycapturecameraimage);
        image = (ImageView) findViewById(R.id.imgView);
    }



    public void onBackClick(View v){


        cameraID = 0;
        Intent i = new Intent(CaptureCameraImage.this,CameraView.class);
        startActivityForResult(i, 999);
    }

}

CameraView.java

public class CameraView extends Activity implements SurfaceHolder.Callback, OnClickListener{
        private static final String TAG = "CameraTest";
        Camera mCamera;
        boolean mPreviewRunning = false;

        @SuppressWarnings("deprecation")
        public void onCreate(Bundle icicle){
            super.onCreate(icicle);
            Log.e(TAG, "onCreate");

            getWindow().setFormat(PixelFormat.TRANSLUCENT);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
            setContentView(R.layout.cameraview);
            ImageView img = (ImageView) findViewById(R.id.blankImage);

            if(CaptureCameraImage.isBlack)
                img.setBackgroundResource(android.R.color.black);
            else
                img.setBackgroundResource(android.R.color.white);

            mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
            mSurfaceView.setOnClickListener(this);
            mSurfaceHolder = mSurfaceView.getHolder();
            mSurfaceHolder.addCallback(this);
            mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        }

        @Override
        protected void onRestoreInstanceState(Bundle savedInstanceState){
            super.onRestoreInstanceState(savedInstanceState);
        }


        Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {

            public void onPictureTaken(byte[] data, Camera camera) {
                // TODO Auto-generated method stub
                if (data != null){
                    //Intent mIntent = new Intent();
                    //mIntent.putExtra("image",imageData);

                    mCamera.stopPreview();
                    mPreviewRunning = false;
                    mCamera.release();

                     try{
                         BitmapFactory.Options opts = new BitmapFactory.Options();
                         Bitmap bitmap= BitmapFactory.decodeByteArray(data, 0, data.length,opts);
                         bitmap = Bitmap.createScaledBitmap(bitmap, 300, 300, false);
                         int width = bitmap.getWidth();
                         int height = bitmap.getHeight();
                         int newWidth = 300;
                         int newHeight = 300;

                         // calculate the scale - in this case = 0.4f
                         float scaleWidth = ((float) newWidth) / width;
                         float scaleHeight = ((float) newHeight) / height;

                         // createa matrix for the manipulation
                         Matrix matrix = new Matrix();
                         // resize the bit map
                         matrix.postScale(scaleWidth, scaleHeight);
                         // rotate the Bitmap
                         matrix.postRotate(90);
                         Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                                 width, height, matrix, true);
                         CaptureCameraImage.image.setImageBitmap(resizedBitmap);

                     }catch(Exception e){
                         e.printStackTrace();
                     }
                    //StoreByteImage(mContext, imageData, 50,"ImageName");
                    //setResult(FOTO_MODE, mIntent);
                    setResult(585);
                    finish();
                }       
            }
        };

        protected void onResume(){
            Log.e(TAG, "onResume");
            super.onResume();
        }

        protected void onSaveInstanceState(Bundle outState){
            super.onSaveInstanceState(outState);
        }

        protected void onStop(){
            Log.e(TAG, "onStop");
            super.onStop();
        }

        @TargetApi(9)
        public void surfaceCreated(SurfaceHolder holder){
            Log.e(TAG, "surfaceCreated");
            mCamera = Camera.open(CaptureCameraImage.cameraID);
        }

        public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
            Log.e(TAG, "surfaceChanged");

            // XXX stopPreview() will crash if preview is not running
            if (mPreviewRunning){
                mCamera.stopPreview();
            }

            Camera.Parameters p = mCamera.getParameters();
            p.setPreviewSize(300, 300);

            if(CaptureCameraImage.cameraID == 0){
                String stringFlashMode = p.getFlashMode();
                if (stringFlashMode.equals("torch"))
                        p.setFlashMode("on"); // Light is set off, flash is set to normal 'on' mode
                else
                        p.setFlashMode("torch");
            }

            mCamera.setParameters(p);
            try{
                mCamera.setPreviewDisplay(holder);
            }catch (Exception e){
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            mCamera.startPreview();
            mPreviewRunning = true;
            mCamera.takePicture(null, mPictureCallback, mPictureCallback);
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            Log.e(TAG, "surfaceDestroyed");
            //mCamera.stopPreview();
            //mPreviewRunning = false;
            //mCamera.release();
        }

        private SurfaceView mSurfaceView;
        private SurfaceHolder mSurfaceHolder;

        public void onClick(View v) {
            // TODO Auto-generated method stub
            mCamera.takePicture(null, mPictureCallback, mPictureCallback);
        }

    }

【问题讨论】:

  • 我已经试过了,不行。
  • “请立即回复,因为这很紧急”不是称呼志愿者的合适方式。请学习一些时间管理、一些耐心和一些尊重。
  • 它告诉我代码比文本多,所以我不得不添加一些文本......对不起。
  • 要不要添加一个描述你到目前为止所做的调试,以及究竟问题是什么?

标签: java android


【解决方案1】:

要捕获图像并将其保存在特定文件夹中,您必须:

  1. 运行时权限请求 (API 23)
  2. 请求图像捕获
  3. 创建文件夹

首先,如果您以 API 23 为目标,您必须遵循新的权限系统,该系统要求用户仅在第一次使用时授予权限。在您的情况下,您需要授予 WRITE_EXTERNAL_STORAGE。

    boolean hasPermission = (ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);

    if (!hasPermission) {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                REQUEST_WRITE_STORAGE);
    }

然后,您需要创建一个隐式意图来捕捉照片。相机应用可以出现在应用选择器中,也可以根据用户设置和安装的应用自动选择。

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

startActivityForResult(intent, REQUEST_IMAGE_CAPTURE); // final int = 1

最后,您需要创建文件夹并指明额外的输出,以便 Android 知道将图片保存在哪里。

//Intent i = new intent...

                    long timestamp = System.currentTimeMillis();

                    File file = new File("");

                        file = new File(Environment.getExternalStorageDirectory()
                            + File.separator
                            + "DCIM"
                            + File.separator
                            + address
                            + File.separator
                            , "IMG_" + String.valueOf(timestamp) + ".jpg");

intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));

//startActivityForResult...

有很多存储可能性。你可以看看这里: https://developer.android.com/training/basics/data-storage/files.html

我在 onActivityResult 回调方法中没有做任何特别的事情。我只显示一个 toast 来确认用户图片保存成功。在我的例子中,上面的所有代码都在 imageView 的 onClickListener 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-14
    相关资源
    最近更新 更多