To save the image in sdcard [closed]

2019-02-21 05:23发布

问题:

I have Written the code for Editing the Image now I want to save that edited image in the sdcard

image=(ImageView)findViewById(R.id.image);
        Intent intent = getIntent();
        File sdCardDirectory = Environment.getExternalStorageDirectory();
        photo = (Bitmap) intent.getParcelableExtra("photoo");
        image.setImageBitmap(photo);

回答1:

Try this,

 void saveImage() {

    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/saved_images");

    String fname = "Image.jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete (); 
    try {
           FileOutputStream out = new FileOutputStream(file);
           myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
           out.flush();
           out.close();

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


回答2:

Ok first of all you need to give Write Permissions in AndroidManifest.xml as below,

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

Now lets look at the code that actually write your edited image,

// Getting the SDCard Path
File sdcard = Environment.getExternalStorageDirectory();
File editedFile = new File( sdcard, "myphoto.jpeg" );

// if file is already exists then first delete it
if ( editedFile.exists() ) 
{   
    editedFile.delete(); 
}

FileOutputStream fOut = new FileOutputStream( editedFile );
photo.compress( Bitmap.CompressFormat.JPEG, 90, fOut );


回答3:

It is quite simple.

File outpt = new File( sdCardDirectory, "photo.jpeg" );
FileOutputStream outptOs = new FileOutputStream( outpt );
photo.compress( Bitmap.CompressFormat.JPEG, 90, outptOs );