Java 在Android中的指定文件夹中保存图片

Java 在Android中的指定文件夹中保存图片,java,android,camera,Java,Android,Camera,这是我在Stackoverflow的第一篇帖子,我祈祷你能帮助我 我最近开始学习Android,并决定一个简单的应用程序,它可以拍摄照片,然后在应用程序中向用户显示照片,这将是一个很好的开始 然而,在Android开发者网站()上阅读了指南之后,我似乎无法显示图像 我收到错误消息: 无法解码流:java.io.FileNotFoundException:file:/storage/simulated/0/Pictures/JPEG_20160101_163802_1697759335.jpg:o

这是我在Stackoverflow的第一篇帖子,我祈祷你能帮助我

我最近开始学习Android,并决定一个简单的应用程序,它可以拍摄照片,然后在应用程序中向用户显示照片,这将是一个很好的开始

然而,在Android开发者网站()上阅读了指南之后,我似乎无法显示图像

我收到错误消息:

无法解码流:java.io.FileNotFoundException:file:/storage/simulated/0/Pictures/JPEG_20160101_163802_1697759335.jpg:open失败:enoint(无此类文件或目录)

我可以看到照片已保存在默认的相机文件夹中,而不是我指定的路径(从开发人员教程复制/粘贴的路径)

如果有人能帮我找出如何将照片保存在指定的文件中,或者从相机应用程序中获取保存的位置,我将不胜感激

    package uk.co.c2digital.futurefoto;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * The following code is based on the following article: http://developer.android.com/training/camera/photobasics.html
 */

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.v("MainActivity", "App Started");
    }





    /**
     * This block of code launches the default camera application
     */

    static final int REQUEST_TAKE_PHOTO = 1;

    public void dispatchTakePictureIntent(View view) {

        Log.v("MainActivity", "dispatchTakePictureIntent() function started");

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {

            // Out success result to log
            Log.v("MainActivity", "Camera app found");

            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
                Log.v("MainActivity","Image will be saved to: " + photoFile);
            } catch (IOException ex) {
                // Error occurred while creating the File
                Toast.makeText(this, "Unable to save image", Toast.LENGTH_SHORT).show();
                Log.v("MainActivity", "Error while attempting to run createImageFile()");
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Log.v("MainActivity","File created");
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(photoFile));
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);




            }
        } else {
            Toast.makeText(this, "Unable to launch camera app", Toast.LENGTH_SHORT).show();
            Log.v("MainActivity","Unable to find camera app");
        }
    }

    /**
     * End of camera launch code
     */


    /**
     * This block of code creates a unique file name for captured photos to prevent naming collisions
     */


    String mCurrentPhotoPath;

    public File createImageFile() throws IOException {

        Log.v("MainActivity","createImageFile() functions started");

        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = "file:" + image.getAbsolutePath();


        return image;
    }


    /**
     * End of unique file name code
     */


    /**
     * This block of code decodes and scales the photo and displays in photoView
     */



    public void setPic() {

        Log.v("MainActivity","setPic() function started");

        ImageView mImageView = (ImageView) findViewById(R.id.imageViewer);

        // Get the dimensions of the View
        int targetW = mImageView.getWidth();
        int targetH = mImageView.getHeight();

        // Get the dimensions of the bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determine how much to scale down the image
        int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

        // Decode the image file into a Bitmap sized to fill the View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;

        Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        mImageView.setImageBitmap(bitmap);
    }

    /**
     * End of photo scaling code
     */


    /**
     * THis block of code allows the created photo to be made available to the photo gallery
     */


    private void galleryAddPic() {

        Log.v("MainActivity", "galleryAddPic() function started");

        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(mCurrentPhotoPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }


    /**
     * End of gallery code
     */


    /**
     * This block of code handles the responce from the cameras intent
     */

    public void onActivityResult(int RequestCode, int ResultCode, Intent data) {

        Log.v("MainActivity","onActivityResult() function started");

        if (RequestCode == REQUEST_TAKE_PHOTO) {

            Log.v("MainActivity","RequestCode matched REQUEST_TAKE_PHOTO");

            if (ResultCode == RESULT_OK) {

                Log.v("MainActivity","ResultCode was OK");

                 // galleryAddPic();
                  setPic();

            } else {

                Log.v("MainActivity","ResultCode was not OK");
                Log.v("MainActivity","ResultCode was: " + ResultCode);
            }


        } else {

            Log.v("MainActivity","RequestCode did not equal REQUEST_TAKE_PHOTO");
            Log.v("MainActivity","Request Code was: " + RequestCode);
        }


    }
}

这是我使用的方法:

Uri newPhotoUri;
public void takePhoto() {
    // create Intent to take a picture and return control to the calling application
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    newPhotoUri = Uri.fromFile(new File(filename)); // create a file to save the image
    intent.putExtra(MediaStore.EXTRA_OUTPUT, newPhotoUri); // set the image file name

    // start the image capture Intent
    startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
然后:

/**
 * Called when returning from the camera request.
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        Log.d(TAG, "Received camera activity result");
        if (resultCode == RESULT_OK) {
            String resultPath = "";
            if (data == null) {
                if (this.newPhotoUri != null) {
                    Log.d(TAG, "Intent data is null, trying with uri " + this.newPhotoUri.getPath());
                    resultPath = this.newPhotoUri.getPath();
                } else {
                    Log.d(TAG, "Intent data and photo Uri are null, exiting");
                    return;
                }
            } else {
                // Image captured and saved to fileUri specified in the Intent
                Log.d(TAG, "Image saved to: " + data.getData());
                resultPath = data.getData().toString();
            }
            // process resultPath
        } else if (resultCode == RESULT_CANCELED) {
            // User cancelled the image capture
            Log.d(TAG, "User cancelled");
        } else {
            // Image capture failed
        }
    }
}

对于某些设备,无法保证使用媒体存储位置,因此这是一种更实用的方法。

这里有一个指南——请查看。这将对您有所帮助。@helldawg-感谢您的链接,但旁白是希腊文的,不幸的是,我不会说。@jihonora-谢谢,我花了一点时间来学习在文件名中输入什么内容(目前正在使用:“Environment.getExternalStorageDirectory(),“image1.jpeg”)。