如何从内部存储中拍照并将捕获图像保存在内部存储器android中?

时间:2014-04-04 06:09:33

标签: android image local-storage

我正在使用此代码来拍照并拍摄照片。当设备有SD卡但没有SD卡给我吐司时工作正常请插入SD卡。那有什么解决方案吗?

这是我的代码:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case 1:
        if (resultCode == RESULT_OK) {
            Uri chosenImageUri = data.getData();
            String imagepath = getpath(chosenImageUri);
            extension = imagepath.substring(imagepath.lastIndexOf(".")+1);
            Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
            saveToInternalSorage(bitmap, "image1");
            Constant._profilePhotoUrl = Constant.convertBitmapToBase64(bitmap);
            if(flag == 1){
                _uploadImageView1.setImageBitmap(Bitmap.createScaledBitmap(
                        bitmap,100,100,false));
                _uploadImageView1.setScaleType(ImageView.ScaleType.FIT_XY);
                _chooseLayout.setVisibility(View.GONE);
                _footerLayout.setVisibility(View.VISIBLE);
            }else if (flag == 2) {
                _uploadImageView2.setImageBitmap(Bitmap.createScaledBitmap(
                        bitmap,100,100,false));
                _uploadImageView2.setScaleType(ImageView.ScaleType.FIT_XY);
                _footerLayout.setVisibility(View.VISIBLE);
                _chooseLayout.setVisibility(View.GONE);
            }else if (flag == 3) {
                _uploadImageView3.setImageBitmap(Bitmap.createScaledBitmap(
                        bitmap,100,100,false));
                _uploadImageView3.setScaleType(ImageView.ScaleType.FIT_XY);
                _footerLayout.setVisibility(View.VISIBLE);
                _chooseLayout.setVisibility(View.GONE);
            }

        } else {
            Toast.makeText(UploadFileActivity.this, "Unable to get Image",
                    Toast.LENGTH_SHORT).show();
        }
        break;
    case 2:
        if (resultCode == RESULT_OK) {
            try {
                Bitmap bitmap = (Bitmap) data.getExtras().get("data");
                /*_uploadImageView1.setImageBitmap(Bitmap
                        .createScaledBitmap(bitmap, 120, 120, false));*/
                if(flag == 1){
                    _uploadImageView1.setImageBitmap(Bitmap.createScaledBitmap(
                            bitmap,100,100,false));
                    _uploadImageView1.setRotation(90);
                    _uploadImageView1.setScaleType(ImageView.ScaleType.FIT_XY);
                    _chooseLayout.setVisibility(View.GONE);
                    _footerLayout.setVisibility(View.VISIBLE);
                    Constant._profilePhotoUrl = Constant.convertBitmapToBase64(bitmap);
                }else if (flag == 2) {
                    _uploadImageView2.setImageBitmap(Bitmap.createScaledBitmap(
                            bitmap,100,100,false));
                    _uploadImageView2.setRotation(90);
                    _uploadImageView1.setScaleType(ImageView.ScaleType.FIT_XY);
                    _chooseLayout.setVisibility(View.GONE);
                    _footerLayout.setVisibility(View.VISIBLE);
                }else if (flag == 3) {
                    _uploadImageView3.setImageBitmap(Bitmap.createScaledBitmap(
                            bitmap,100,100,false));
                    _uploadImageView3.setRotation(90);
                    _uploadImageView3.setScaleType(ImageView.ScaleType.FIT_XY);
                    _chooseLayout.setVisibility(View.GONE);
                    _footerLayout.setVisibility(View.VISIBLE);
                }
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(UploadFileActivity.this, "Unable to get Image",
                    Toast.LENGTH_SHORT).show();
        }
        break;
    }
}
private String getpath(Uri chosenImageUri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(chosenImageUri, projection, null, null,
            null);
    int column = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column);
}

3 个答案:

答案 0 :(得分:0)

尝试以下代码:

public Bitmap loadBitmap(String url)
{
    Bitmap bm = null;
    InputStream is = null;
    BufferedInputStream bis = null;
    try 
    {
        URLConnection conn = new URL(url).openConnection();
        conn.connect();
        is = conn.getInputStream();
        bis = new BufferedInputStream(is, 8192);
        bm = BitmapFactory.decodeStream(bis);
    }
    catch (Exception e) 
    {
        e.printStackTrace();
    }
    finally {
        if (bis != null) 
        {
            try 
            {
                bis.close();
            }
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        }
        if (is != null) 
        {
            try 
            {
                is.close();
            }
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        }
    }
    return bm;
}


private String saveInInternalSorage(Bitmap bImage){
        ContextWrapper cw = new ContextWrapper(getApplicationContext());

        File dir = cw.getDir("image", Context.MODE_PRIVATE);

        File path=new File(dir,"img.jpg");

        FileOutputStream fos = null;
        try {           

            fos = new FileOutputStream(path);
            bImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dir.getAbsolutePath();
    }

Bitmap btm = loadBitmap(yourUri);
saveInInternalSorage(btm);

答案 1 :(得分:0)

您将尝试以下功能将文件存储到内存...

以下功能用于读取磁盘上可用的外部存储器...

String state = Environment.getExternalStorageState();

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        mExternalStorageAvailable = mExternalStorageWriteable = true;
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        mExternalStorageAvailable = true;
        mExternalStorageWriteable = false;
    } else {
        mExternalStorageAvailable = mExternalStorageWriteable = false;
    }

以下代码用于将数据存储到内部存储器中。

    public class StartingActivity extends Activity {

Camera camera;
CameraPreview preview;

@SuppressWarnings("unused")
private static final int VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;

public static final String DIR_NAME = "My_Album";

private File file;

ImageButton cap;
ImageButton video;
ImageButton gallery;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.starting);
    cap = (ImageButton) findViewById(R.id.cap);
    video = (ImageButton) findViewById(R.id.video);
    gallery = (ImageButton) findViewById(R.id.gallery);
    camera = getInstance();
    preview = new CameraPreview(this, camera);
    FrameLayout layout = (FrameLayout) findViewById(R.id.image_frame);
    layout.addView(preview);
    cap.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            camera.takePicture(null, null, picture);

        }
    });
    gallery.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(StartingActivity.this,
                    GridViewActivity.class);
            startActivity(intent);
        }
    });

}

public boolean checkCameraFeature(Context context) {
    if (context.getPackageManager().hasSystemFeature(
            PackageManager.FEATURE_CAMERA)) {
        return true;
    } else {
        return false;
    }
}

public static Camera getInstance() {
    Camera c = null;
    try {
        c = Camera.open();
    } catch (Exception exception) {
        // Nothing....
    }
    return c;
}

private File getOutputMediaFile(int imageRequestCode) {

    ContextWrapper cw = new ContextWrapper(getApplicationContext());
    File directory = cw.getDir("My_Album", Context.MODE_PRIVATE);

    if (!directory.exists()) {
        if (!directory.mkdirs()) {
            Log.d("MyCameraApp", "failed to create directory");
            directory.mkdirs();
        }
    }
    String name = null;
    Calendar cal = Calendar.getInstance();
    System.out.println("TIME->" + cal.getTime());
    SimpleDateFormat date = new SimpleDateFormat("dd_MM_yyyy_hh_mm_ss");
    String value = date.format(cal.getTime());
    name = "Image_" + value + ".jpg";
    File image_file = new File(directory, name);
    return image_file;
}

PictureCallback picture = new PictureCallback() {

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

        File image_file = getOutputMediaFile(MEDIA_TYPE_IMAGE);
        if (image_file == null) {

        }
        try {
            FileOutputStream o = new FileOutputStream(image_file);
            o.write(data);
            o.close();
            Toast.makeText(getBaseContext(), "Image saved",
                    Toast.LENGTH_SHORT).show();

        } catch (FileNotFoundException exception) {

        } catch (IOException e) {

        }

        camera.startPreview();
    }
};

 }

相机预览课程..

   public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {

Camera myCamera;
SurfaceHolder mySurfaceHolder;

@SuppressWarnings("deprecation")
public CameraPreview(Context context,Camera cam) 
{
    super(context);
    this.myCamera=cam;
    this.mySurfaceHolder=getHolder();
    mySurfaceHolder.addCallback(this);
    mySurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,int height)
{
    if(mySurfaceHolder.getSurface()==null)
    {
    try
    {
        myCamera.stopPreview();
    }
    catch(Exception exception)
    {

    }
    }
    try
    {
        myCamera.setPreviewDisplay(mySurfaceHolder);
        myCamera.startPreview();
    }
    catch(Exception e)
    {
        Log.d(null,"Error Starting Camera preview :"+e.getMessage());
    }

}

@Override
public void surfaceCreated(SurfaceHolder holder) {
    try {
        myCamera.setPreviewDisplay(holder);
        myCamera.startPreview();            
    } catch (IOException e) {
        Log.d( "Error setting camera preview: " + e.getMessage(), null);
    }

}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {

}

  }

答案 2 :(得分:0)

一样打电话
 getallimages(Environment.getExternalStorageDirectory());

以下是方法

private void getallimages(File dir)
    {


        String[] STAR = { "*" };
        controller.images.clear();

        final String orderBy = MediaStore.Images.Media.DEFAULT_SORT_ORDER;
        Cursor imagecursor = cntx.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STAR, null, null, orderBy);
        int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);

        int count = imagecursor.getCount();
        for (int i = 0; i < count; i++) {
            imagecursor.moveToPosition(i);
            int id = imagecursor.getInt(image_column_index);
            ImageItem imageItem = new ImageItem();

            if(new File(imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA))).length()<=10485760)
            {
                imageItem.filePath = imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA));

                    imageItem.id = id;
                    imageItem.selection = false; //newly added item will be selected by default
                    controller.images.add(imageItem);   //in this i add all image in wrapper class 
         }
 }
 }

最后,我想给出一个刷新代码,它会刷新您的Android图库,用于新添加或下载或新点击的图片,以便在扫描开始或上面的方法粘贴它

sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(filePath))));