首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在android设备的内部存储中保存图像?

如何在android设备的内部存储中保存图像?
EN

Stack Overflow用户
提问于 2014-01-17 16:12:43
回答 1查看 3.2K关注 0票数 0

我想保存在设备的内部存储图像,因为许多设备没有外部存储或SD卡。

代码语言:javascript
复制
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();
}
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-01-17 16:34:57

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

代码语言:javascript
复制
Boolean haveSd= android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

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

如果您想要保存在内部存储中:

代码语言:javascript
复制
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;
   }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21190573

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档