嘿伙计们我正在开发一个Android项目,我想在我的应用程序中添加一个按钮,当用户点击它时,它会将图像保存到SD卡中并显示一个Toast"图像保存在sdcard" 请帮帮我
答案 0 :(得分:1)
Button bSave = (Button) findViewById(R.id.bSave);
bSave.setOnClickListener(new View.OnClickListener(){
saveImage(true);
Toast.makeText(getApplicationContext(),"Image Saved",0).show();
});
和saveImage();
public void saveImage(boolean isNotifyAfterSave){
Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.ic_launcher);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file = new File(extStorageDirectory, "ic_launcher.PNG");
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
//if isNotifyAfterSave = true, then it will show an NotificationAlert.
if(isNotifyAfterSave){
Uri uriOfFile = Uri.fromFile(file);
showNotification("Image Saved","desc:ic_launcher.png","IMAGE SAVED!",uriOfFile);
}
}
public void showNotification(String title, String text, String ticker,Uri pathToImage) {
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(
context);
Intent intent = new Intent(Intent.ACTION_VIEW, pathToImage);
intent.setDataAndType(pathToImage, "image/*");
PendingIntent pIntent = PendingIntent.getActivity(
context.getApplicationContext(), 0, intent,
PendingIntent.FLAG_ONE_SHOT);
nBuilder.setContentText(text);
nBuilder.setContentTitle(title);
nBuilder.setContentIntent(pIntent);
nBuilder.setTicker(ticker);
nBuilder.setAutoCancel(true);
nBuilder.setDefaults(Notification.DEFAULT_ALL);
nBuilder.setSmallIcon(R.drawable.ic_stat_notify);
nBuilder.setLargeIcon(BitmapFactory.decodeResource(
context.getResources(), R.drawable.ic_launcher));
mNotificationManager.notify(0, nBuilder.build());
}
不要忘记添加android.permission.WRITE_EXTERNAL_STORAGE权限
REF:StackOverflow
答案 1 :(得分:0)
除了Shifar Shifz的回答。如果您想在保存后在图库中查看图像,则应调用以下方法:
private static void addImageToGallery(final Context context, final String filePath) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
否则,它可能仅适用于文件管理器,而不适用于图库应用。