android 读取,写入图片到sd卡源码

 
  
/**
     * Save Bitmap to a file.保存图片到SD卡。
     * 
     * @param bitmap
     * @param file
     * @return error message if the saving is failed. null if the saving is
     *         successful.
     * @throws IOException
     */
    public static void saveBitmapToFile(Bitmap bitmap, String _file)
            throws IOException {//_file = getSDPath()+"/xx自定义文件夹/hot.png"
        BufferedOutputStream os = null;
        try {
            File file = new File(_file);
            // String _filePath_file.replace(File.separatorChar +
            // file.getName(), "");
            int end = _file.lastIndexOf(File.separator);
            String _filePath = _file.substring(0, end);
            File filePath = new File(_filePath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            file.createNewFile();
            os = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    Log.e(TAG_ERROR, e.getMessage(), e);
                }
            }
        }
    }

//读取
public class MainAct extends Activity {
        /** Called when the activity is first created. */
        private ImageView img;
        //SD图片路径
        private String filepath = getSDPath()+"/xx自定义文件夹/hot.png"

        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
                img = (ImageView) findViewById(R.id.img);
                File file = new File(filepath);
                if (file.exists()) {
                        Bitmap bm = BitmapFactory.decodeFile(filepath);
                        //将图片显示到ImageView中
                        img.setImageBitmap(bm);
                }
        }
}

/**
	 * 获取SDK路径
	 * @return
	 */
	public static String getSDPath(){ 
	       File sdDir = null; 
	       boolean sdCardExist = Environment.getExternalStorageState()   
	                           .equals(android.os.Environment.MEDIA_MOUNTED);   //判断sd卡是否存在 
	       if   (sdCardExist)   
	       {                               
	         sdDir = Environment.getExternalStorageDirectory();//获取跟目录 
	      }   
	       return sdDir.toString(); 
	       
	}


 
 

你可能感兴趣的:(android)