簡體   English   中英

將相機捕獲的圖像保存在android的外部存儲中

[英]save image captured by camera in external storage in android

我通過在我的應用程序本身中調用camera api在我的應用程序中使用camera(我並不是要打開android的主攝像頭應用程序)。

我在打開相機預覽時在屏幕上顯示疊加圖像,該疊加圖像會根據方向傳感器的變化進行動畫處理。

我的問題是,每當我捕獲圖像時,都會捕獲該圖像並將其顯示在屏幕上,但是它沒有保存在外部目錄中,我已盡力而為,但是我沒有成功,plz。 幫我,我如何將圖像保存到外部目錄中,您的幫助將不勝感激。 提前致謝。 我正在發布我的整個代碼,請幫助我在什么地方以及在哪里實現.....

package com.example.compassapp;

 import java.io.File;
 import java.io.FileOutputStream;
 import java.util.Random;

 import android.app.Activity;
 import android.app.AlertDialog;
 import android.content.DialogInterface;
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
 import android.graphics.Canvas;
 import android.hardware.Camera;
 import android.hardware.Camera.PictureCallback;
 import android.hardware.Sensor;
 import android.hardware.SensorEvent;
 import android.hardware.SensorEventListener;
 import android.hardware.SensorManager;
 import android.os.Bundle;
 import android.os.Environment;
 import android.util.Log;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.view.animation.Animation;
 import android.view.animation.RotateAnimation;
 import android.widget.FrameLayout;
 import android.widget.ImageButton;
 import android.widget.ImageView;
 import android.widget.TextView;
 import android.widget.Toast;

 public class MainActivity extends Activity implements SensorEventListener {

// define the display assembly compass picture
private ImageView image;


// record the compass picture angle turned
private float currentDegree = 0f;

// device sensor manager
private SensorManager mSensorManager;

TextView tvHeading;
Canvas canvas;
FrameLayout preview;
ImageButton button_capture;
private Camera cameraObject;
   private ShowCamera showCamera;
   private ImageView pic;
   public static Camera isCameraAvailiable(){
      Camera object = null;
      try {
         object = Camera.open(); 
      }
      catch (Exception e){
      }
      return object; 
   }

   private PictureCallback capturedIt = new PictureCallback() {

      @Override
      public void onPictureTaken(byte[] data, Camera camera) {

      Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data .length);
      if(bitmap==null){
         Toast.makeText(getApplicationContext(), "not taken", Toast.LENGTH_SHORT).show();
      }
      else
      {
         Toast.makeText(getApplicationContext(), "taken", Toast.LENGTH_SHORT).show();       
      }
      cameraObject.release();
   }
      private void SaveImage(Bitmap finalBitmap){
          String root = Environment.getExternalStorageDirectory().toString();
            File myDir = new File(root + "/saved_images");    
            myDir.mkdirs();
            Random generator = new Random();
            int n = 10000;
            n = generator.nextInt(n);
            String fname = "Image-"+ n +".jpg";
            File file = new File (myDir, fname);
            if (file.exists ()) file.delete (); 
            try {
                   FileOutputStream out = new FileOutputStream(file);
                   finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                   out.flush();
                   out.close();

            } catch (Exception e) {
                   e.printStackTrace();
            }
      }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    image=(ImageView)findViewById(R.id.image);
    button_capture=(ImageButton)findViewById(R.id.button_capture);        


    cameraObject = isCameraAvailiable();
    //showCamera = new ShowCamera(this, cameraObject);
    showCamera = new ShowCamera(this, cameraObject);
     preview = (FrameLayout) findViewById(R.id.preview);
     preview.addView(showCamera);

     button_capture.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub


                cameraObject.takePicture(null, null, capturedIt);
            //cameraObject.takePicture(null, null, capturedIt);


        }
    });        




    // our compass image


    // TextView that will tell the user what degree is he heading
    tvHeading = (TextView) findViewById(R.id.tvHeading);

    // initialize your android device sensor capabilities
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
}



@Override
protected void onResume() {
    super.onResume();

    // for the system's orientation sensor registered listeners
    mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
            SensorManager.SENSOR_DELAY_GAME);
}

@Override
protected void onPause() {
    super.onPause();

    // to stop the listener and save battery
    mSensorManager.unregisterListener(this);
}

@Override
public void onSensorChanged(SensorEvent event) {

    // get the angle around the z-axis rotated
    float degree = Math.round(event.values[0]);

    tvHeading.setText("Heading: " + Float.toString(degree) + " degrees");

    // create a rotation animation (reverse turn degree degrees)

    RotateAnimation ra = new RotateAnimation(
            currentDegree, 
            -degree,
            Animation.RELATIVE_TO_SELF, 0.5f, 
            Animation.RELATIVE_TO_SELF,
            0.5f);

    // how long the animation will take place
    ra.setDuration(210);

    // set the animation after the end of the reservation status
    ra.setFillAfter(true);

    // Start the animation
    image.startAnimation(ra);
    currentDegree = -degree;


}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // not in use
}


public void onBackPressed() {

    //super.onBackPressed();
    Log.d("back button", "back button pressed");
    AlertDialog.Builder ad1=new AlertDialog.Builder(this);
    ad1.setMessage("Are you sure you want to exit? ");
    ad1.setCancelable(false);


    ad1.setNegativeButton("NO", new DialogInterface.OnClickListener() {             
        @Override
        public void onClick(DialogInterface arg0, int arg1) {   


        }
    });

    ad1.setPositiveButton("YES", new DialogInterface.OnClickListener() {                
        @Override
        public void onClick(DialogInterface arg0, int arg1) {   

            MainActivity.this.finish();
        }
    });
    AlertDialog alert=ad1.create();
    alert.show();   

            }
  }
add this code in onActivityResult. This will store your image in a folder named "FolderName"

String extr = Environment.getExternalStorageDirectory().toString()
        + File.separator + "YourFolderName";
File myPath = new File(extr, FolderName);
FileOutputStream fos = null;
try {
    fos = new FileOutputStream(myPath);
    bitMap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    fos.flush();
    fos.close();
    MediaStore.Images.Media.insertImage(context.getContentResolver(),
            bitMap, myPath.getPath(), uniqueFileName);
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

還需要在清單上設置權限

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

參考這個

您是否已將此滲透性放入AndroidManifest中

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM