【问题标题】:How to take picture from internal storage and save capture image in internal memory android?如何从内部存储器中拍照并将捕获的图像保存在内部存储器android中?
【发布时间】:2014-05-16 07:08:27
【问题描述】:

我正在使用此代码拍照和拍照。当设备有 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);
}

【问题讨论】:

  • 亲爱的你调试你的代码了吗??
  • 那么请调试你的代码亲爱的你可以自己找到问题亲爱的在你尝试存储数据的地方逐行调试你的代码并找到你得到错误的那一行
  • 因为这个调试习惯你可以学到更多关于代码的知识,因为一个好的程序员也是一个好的调试者:)
  • 哦,你在哪里出错了
  • intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);

标签: android image local-storage


【解决方案1】:

试试下面的代码:

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);

【讨论】:

    【解决方案2】:

    您将尝试使用以下函数将文件存储到内存中...

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

    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) {
    
    }
    
      }
    

    【讨论】:

    • 以及如何在没有sd卡的情况下打开画廊?
    • 不,我为用户定义的相机编写了这段代码,在这里我使用单独的文件路径来存储图像,我将只显示特定路径中的图像库...
    • 但我使用的是默认相机
    • 这不是问题,我会发布整个用户定义的相机类,你试试吧..
    【解决方案3】:

    像这样打电话

     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))));
    

    【讨论】:

    • Environment.getExternalStorageDirectory() 这是用于 sd 卡的吗?
    • 感谢您的帮助.. 但这对我没有用,因为有时我需要显示单个图像...
    • 不,亲爱的,这是用于默认存储,只要制造任何设备,则此 Environment.getExternalStorageDirectory() 将用于主存储
    • 就像你只想要你的相机当前捕获的图像是吗??
    • 我只是想打开画廊来挑选图像并存储捕获图像天气 sd 卡安装与否..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    • 2017-12-11
    • 2013-01-16
    • 2012-06-27
    • 1970-01-01
    相关资源
    最近更新 更多