即使退出应用程序,也可以将捕获的图像保留为按钮背景

时间:2015-01-29 10:32:24

标签: android

我有一个Android应用程序,我在其中访问设备的相机并捕获图像,而图像又自动设置为图像按钮背景。 问题是每当我退出应用程序并再次打开它时,我的图像按钮的背景消失了,我必须捕获一个新的。我需要一个代码来保存捕获的图像作为图像按钮背景。 注意:我没有使用数据库,图像保存在设备的库中。

private File createImageFile() throws IOException{ 
Date now = new Date(); 
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(now); 
String imageFileName = "JPEG_" + timeStamp +"_"; 
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); 
File image = File.createTempFile(imageFileName, ".jpg", storageDir); 
mCurrentPhotoPath = image.getAbsolutePath(); return image; }

public void newphoto(View v){ 
    Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    File photofile = null; 
    try { 
        photofile = createImageFile(); 
    } catch (IOException ex)
    {} 
    if (photofile!=null){ 
        i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photofile)); 
        startActivityForResult(i,reqCode); 
    }
}

ImageButton myImage = (ImageButton) findViewById(R.id.B1);
Bitmap myBitmap = BitmapFactory.decodeFile(mCurrentPhotoPath); 
int nh=(int)(myBitmap.getHeight()*(212.0/myBitmap.getWidth())); 
Bitmap s =Bitmap.createScaledBitmap(myBitmap, 212, nh, true); 
myImage.setImageBitmap(s);

2 个答案:

答案 0 :(得分:1)

假设您正在保存您在图库中捕获的图片。以下代码将帮助您将其检索回来。

Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
yourImageButton.setImageBitmap(bitmap);

答案 1 :(得分:0)

存储图片后,请立即修改共享首选项。

prefs.putString("lastTakenPicture", your_path_string);

当您的应用启动时,获取该path_string并将其转换为Bitmap,然后将其添加到ImageButton

修改 SharedPreference的全局变量

 private SharedPreferences sharedPreferences;

并在您的onCreate()方法

sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String lastTakenImagePath= sharedPreferences.getString("lastTakenImagePath",null);
if(lastTakenImagePath!=null){
 /*
*Here Convert pathstring to file, file to bitmap 
*and assign bitmap to   imagebutton.
*/
}

将图片存储在文件存储中后,执行此操作

 SharedPreferences.Editor editor = sharedPreferences.edit();
 editor.putInt("lastTakenImagePath", your_image_file_path.toString());
 editor.commit();