Android: Saving image to storage

[亡魂溺海] 提交于 2020-01-03 00:39:28

问题


Currently my application, takes a photo, and put's the data into a ImageView.

public void openCamera() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        imageView.setImageBitmap(photo);
    }
}

Now, i want it to do this: When the user clicks the button 'Save Button' I would like it to save to storage. How would i do this? I have my button set up with an OnClick listener.

public void save_btn() {

}

回答1:


Step #1: Hold onto the Bitmap somewhere

Step #2: When the button is clicked, fork a background thread, AsyncTask, IntentService, etc. to do the work

Step #3: In the background thread (or whatever), call compress() on the Bitmap, providing an OutputStream on whatever file you want to write to




回答2:


use Bitmap compress method to store bitmap into the android data storage. and if you want to store full size of image then please use intent.putExtra with file uri or even you can create your own content Provider (Which is my fav).

bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);

http://developer.android.com/training/camera/photobasics.html#TaskPath

takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));




回答3:


Try this:

String filename = "somename.jpg"; // your filename with path to sdcard
File file = new File(filename);
OutputStream outStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream); // your bitmap
outStream.flush();
outStream.close();



回答4:


Using the code you can save image on sd card :

            FileOutputStream outStream = null;
            File f=new File(Environment.getExternalStorageDirectory()+"/My Image/");
            f.mkdir();
            String extStorageDirectory = f.toString();
            File file = new File(extStorageDirectory, "image.jpg");
            pathOfImage = file.getAbsolutePath();
            try {
                outStream = new FileOutputStream(file);
                bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                Toast.makeText(getApplicationContext(), "Saved at "+f.getAbsolutePath(), Toast.LENGTH_LONG).show();
            } catch (FileNotFoundException e) {e.printStackTrace();}
            try {
                outStream.flush();
                outStream.close();
            } catch (IOException e) {e.printStackTrace();}


来源:https://stackoverflow.com/questions/29717038/android-saving-image-to-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!