在Android设备中保存图像

时间:2014-01-17 16:12:43

标签: android save

我有一个用于在外部存储中保存图像的代码,但我想将图像保存在设备的内部存储中,因为许多设备没有外部存储或sdCard。这些设备无法保存图像。

InputStream y11 = getResources().openRawResource(to);
Bitmap b11 = BitmapFactory.decodeStream(y11);
File direct = new File(Environment.getExternalStorageDirectory()
        .toString() + "/newimages");

direct.mkdirs();

String fName = "Image-" + String.valueOf(System.currentTimeMillis())+ ".jpg";
File file = new File(direct, fName);
if (file.exists())
    file.delete();
try {

FileOutputStream out = new FileOutputStream(file);

b11.compress(Bitmap.CompressFormat.JPEG, 100, out);

out.flush();
// out.close();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"+Environment.getExternalStorageDirectory())));

} catch (Exception e) {
    e.printStackTrace();
}
}

1 个答案:

答案 0 :(得分:2)

您可以使用此代码检查是否存在SD卡:

Boolean haveSd= android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

if(haveSd)
{
  // Work on device-sd
}
else
{
  //Work on device
}

如果你想在内部存储中保存:

public boolean saveImageToInternalStorage(Bitmap image) {

   try {
   // Use the compress method on the Bitmap object to write image to
   // the OutputStream
   FileOutputStream fos = context.openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);

   // Writing the bitmap to the output stream
   image.compress(Bitmap.CompressFormat.PNG, 100, fos);
   fos.close();

   return true;
   } catch (Exception e) {
     Log.e("saveToInternalStorage()", e.getMessage());
     return false;
   }
}