已经可以看到一张大图前提下,长按弹出 “保存图片”。代码
@Override public boolean onLongClick(View v) { switch (v.getId()) { case R.id.iv_image: AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setItems(new String[]{"保存图片"}, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { iv_image.setDrawingCacheEnabled(true); Bitmap imageBitmap = iv_image.getDrawingCache(); if (imageBitmap != null) { new SaveImageTask().execute(imageBitmap); } } }); builder.show(); } return true; } private class SaveImageTask extends AsyncTask<Bitmap, Void, String> { @Override protected String doInBackground(Bitmap... params) { String result = "保存失败"; try { String sdcard = Environment.getExternalStorageDirectory().toString(); File file = new File(sdcard + "/国字号"); if (!file.exists()) { file.mkdirs(); } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String fileName = sdf.format(new Date()) + ".jpg"; File imageFile = new File(file.getAbsolutePath(), fileName); FileOutputStream outStream = null; outStream = new FileOutputStream(imageFile); Bitmap image = params[0]; image.compress(Bitmap.CompressFormat.JPEG, 100, outStream); outStream.flush(); outStream.close(); result = getResources().getString(R.string.save_picture_success, file.getAbsolutePath()); //关键的代码就这一句,仅仅扫描指定路径的图片将其放入图库。 activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageFile))); } catch (Exception e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(String result) { Toast.makeText(activity, result, Toast.LENGTH_SHORT).show(); iv_image.setDrawingCacheEnabled(false); } }
<string name="save_picture_success">图片成功保存至%s目录</string>
参考http://blog.csdn.net/jiayite/article/details/51434047