繁体   English   中英

哪里保存图像-Android

[英]Where to save an Image - android

我正在开发Android应用程序,其中用户从图库中选择图标图像。 我需要保存该图像(位图),以便在应用程序重新启动时可以使用它。

任何简单的例子将不胜感激。

谢谢。

使用下面的代码保存图像:

void saveImage() {

File myDir=new File("/sdcard/saved_images");
myDir.mkdirs();

String fname = "Image.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();
       final AlertDialog alertDialog = new AlertDialog.Builder(this).create();  
            alertDialog.setTitle("Save");  
            alertDialog.setMessage("Your drawing had been saved:)");  
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {  
            public void onClick(DialogInterface dialog, int which) { 
                return;  
            }  
        });  
        alertDialog.show();
} catch (Exception e) {
       e.printStackTrace();
}
}

并从sdcard检索图像:

假设您从Import.java Acitivty中的sdcard检索图像,如下所示:

File file = new File(getExternalFilesDir(null), "MyFile.jpg");

因此,将图像放在File对象中后,只需将其路径放在Intent上,该Intent将用作结果数据,并将其发送回“调用者”活动。 在“被称为”主动性的某点上,您应该这样做:

Intent resultData = new Intent();
resultData.putExtra("imagePath", file.getAbsolutePath());
setResult(RESULT_OK,returnIntent);     
finish();

您的方法onActivityResult:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  super.onActivityResult(requestCode, resultCode, data);

  if(requestCode==RESULT_OK)
  {
    String path = data.getStringExtra("imagePath");           
  }
}

而已! 希望能帮助到你 :)

使用SharedPreferencesBase64字符串表示形式存储图像。

Bitmap imageBitmap = BitmapFactory.decodeStream(stream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream );   
byte[] byte = byteArrayOutputStream.toByteArray(); 
String encodedImage = Base64.encodeToString(byte , Base64.DEFAULT);

SharedPreferences sharedPreferences = getSharedPreferences("SharedPreferencesName", <Mode>);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences .edit();
sharedPreferencesEditor.putString("image_data", encodedImage).commit();

检索时,将Base64表示形式转换回Bitmap

SharedPreferences sharedPreferences = getSharedPreferences("SharedPreferencesName", <Mode>);
String encodedImage = sharedPreferences.getString("image_data", "");

if( !encodedImage.equals("") ){
    byte[] byte = Base64.decode(encodedImage , Base64.DEFAULT);
    Bitmap bitmap = BitmapFactory.decodeByteArray(byte, 0, byte.length);
    imageView.setImageBitmap(bitmap);    
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM