保存到内部存储器android
Posted
技术标签:
【中文标题】保存到内部存储器android【英文标题】:Saving to internal memory android 【发布时间】:2014-02-19 01:34:28 【问题描述】:我无法将图像保存到设备的内存中。我查看了其他主题并实施了它们,但没有任何东西对我有用。如果有人能指出我正确的方向,将不胜感激。我也无法将图像保存到 SD 卡,因为我的平板电脑没有。这是我的代码
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity
// Request codes for Activities
private static final int CAPTURE_IMAGE_REQUEST = 100;
private static final int MEDIA_TYPE_IMAGE = 1;
private static final int LINK_TO_DROPBOX = 150;
// Directory name to store captured images
private static String IMAGE_DIRECTORY_NAME = "Android to Dropbox";
// Uri to store images
private Uri fileUri;
private ImageView imagePreview; // To preview image
private Button captureImage; // To launch camera intent
private Button linkDropbox; // Link users Dropbox account
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imagePreview = (ImageView)findViewById(R.id.imagePrview);
captureImage = (Button)findViewById(R.id.imageCapture);
linkDropbox = (Button)findViewById(R.id.linkToDropbox);
// Go to method to start camera intent to capture image
captureImage.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
captureImage();
);
// Check if user is connected to their Dropbox account
linkDropbox.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
linkToDropbox();
);
// End onCreate
@Override
protected void onSaveInstanceState(Bundle outState)
super.onSaveInstanceState(outState);
outState.putParcelable("file_uri", fileUri);
// End onSavedInstanceState
// Restore fileUri
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
super.onRestoreInstanceState(savedInstanceState);
fileUri = savedInstanceState.getParcelable("file_uri");
// End onRestoreInstanceState
@Override
public boolean onCreateOptionsMenu(Menu menu)
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
// End onCreateOptionsMenu
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
if(requestCode == CAPTURE_IMAGE_REQUEST)
if(resultCode == RESULT_OK) // Successfully captured image
previewCapturedImage();
else if(resultCode == RESULT_CANCELED) // User cancelled image capture
Toast.makeText(getApplicationContext(), "User cancelled image capture", Toast.LENGTH_SHORT).show();
else // Failed to capture image
Toast.makeText(getApplicationContext(), "Failed to capture image", Toast.LENGTH_SHORT).show();
// End onActivityResult
// Method to launch camera within app
private void captureImage()
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAPTURE_IMAGE_REQUEST);
// End captureImage
// Check if user has linked to their Dropbox account
private void linkToDropbox()
// End linkToDropbox
// Preview captured image
private void previewCapturedImage()
try
imagePreview.setVisibility(View.VISIBLE); // Show ImageView
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap image = BitmapFactory.decodeFile(fileUri.getPath(), options);
imagePreview.setImageBitmap(image);
saveToInternalMemory(image); // TRY TO SAVE IMAGE IN INTERNAL MEMORY
catch(NullPointerException e)
e.printStackTrace();
// End previewCapturedImage
// Method to save image to inernal memory
public void saveToInternalMemory(Bitmap image)
boolean ableToSave = true;
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if(pictureFile == null)
Toast.makeText(getApplicationContext(), "Failed to save image", Toast.LENGTH_SHORT).show();
ableToSave = false;
if(ableToSave)
try
FileOutputStream stream = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.close();
catch(FileNotFoundException e)
Toast.makeText(getApplicationContext(), "File not found", Toast.LENGTH_SHORT).show();
catch(IOException e)
Toast.makeText(getApplicationContext(), "Error accessing file", Toast.LENGTH_SHORT).show();
// End saveToInternalMemory
// Create file uri to store image
public Uri getOutputMediaFileUri(int type)
return Uri.fromFile(getOutputMediaFile(type));
// End getOutputMediaFileUri
// Return image
private static File getOutputMediaFile(int type)
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), IMAGE_DIRECTORY_NAME);
File mediaFile;
if(!mediaStorageDir.exists())
if(!mediaStorageDir.mkdirs())
Log.d(IMAGE_DIRECTORY_NAME, "Failed to create " + IMAGE_DIRECTORY_NAME + " directory");
mediaFile = null;
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()); // Image name
if(type == MEDIA_TYPE_IMAGE)
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
else
mediaFile = null;
return mediaFile;
// End getOutputMediaFile
// End MainActivity
编辑:看起来这段代码对我有用。图片不会显示在我的设备上,除非我重新启动它,然后它们才会出现在我的照片应用程序中。
【问题讨论】:
您需要具体说明您所面临的问题。此外,在这里复制所有代码只会使人们难以阅读和理解。请仅包含您遇到问题的部分。 您找到解决方案了吗?我陷入了同样的问题。我可以将图像写入外部存储位而不是内部:( 【参考方案1】:保存:
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/YourFolderName");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
授予清单权限,并转到设备设置>设备>应用程序>应用程序管理器>“您的应用”>权限>启用存储权限!
【讨论】:
【参考方案2】:在你的保存方法中,尝试这样做:
String FILENAME = "hello_file";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
有关详细信息,请参阅开发者文档。 http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
另一个说明为什么您当前的代码可能无法正常工作 - 在您的 getOutputMediaFile
方法中,您正在使用外部存储目录创建一个新文件:
Environment.getExternalStoragePublicDirectory
【讨论】:
以上是关于保存到内部存储器android的主要内容,如果未能解决你的问题,请参考以下文章