Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

image - Android saving Bitmap to SD card

I have a button, and I want when I click on it the image gets saved into the sd card ( or the internal storage, as in htc one x we don't have an external storage like an sd card )

this is my code:

            sd.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                MpClick.start();
                File myDir=new File("/sdcard/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);
                       bitMapToShare.compress(Bitmap.CompressFormat.JPEG, 600, out);
                       out.flush();
                       out.close();

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

and how do I make a message appears in it it's written "Your image was saved." like an alert but for 2seconds and then disappears

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try this

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

and add this in manifest

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

Look at this answer Android saving file to external storage

EDIT : By using this line you can able to see saved images in the gallery view.

sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
        Uri.parse("file://" + Environment.getExternalStorageDirectory())));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...