简体   繁体   English

保存到内部内存android

[英]Saving to internal memory android

I'm having trouble getting an image to save to internal memory on my device. 我无法将图像保存到设备的内存中。 I've looked at other topics and implemented them, but nothing has worked for me. 我查看了其他主题并将其实现,但是没有任何效果对我有用。 If anyone can point me in the right direction it would be appreciated. 如果有人能指出我正确的方向,将不胜感激。 I also can't save the image to an sd card as my tablet does not have one. 我也无法将图像保存到SD卡,因为我的平板电脑没有图像。 Here's my code 这是我的代码

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

EDIT: Looks like this code was working for me. 编辑:看起来这段代码为我工作。 The pictures don't show up on my device unless I'd restart it then they would appear in my photos application. 除非重新启动图片,否则它们不会显示在设备上,否则它们将出现在我的照片应用程序中。

Saving: 保存:

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();

Give manifest permissions and also, Go to Device Settings>Device>Applications>Application Manager>"your app">Permissions>Enable Storage permission! 授予清单权限,然后转到“设备设置”>“设备”>“应用程序”>“应用程序管理器”>“您的应用程序”>“权限”>“启用存储”权限!

In your save method, try doing this: 在您的保存方法中,尝试执行以下操作:

String FILENAME = "hello_file";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();

See the developer docs for more information. 有关更多信息,请参见开发人员文档。 http://developer.android.com/guide/topics/data/data-storage.html#filesInternal http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

Another note for why your current code might not be working - in your getOutputMediaFile method, you're creating a new file using the external storage directory: 关于为什么当前代码可能无法正常工作的另一条注释-在getOutputMediaFile方法中,您正在使用外部存储目录创建新文件:

Environment.getExternalStoragePublicDirectory

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

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