Android相机应用程序:如何在内部保存后显示图片?

时间:2015-02-24 21:05:47

标签: java android android-camera storage preview

所以我想构建一个使用相机并在内部(在应用程序内)保存图像的Android应用程序,然后显示刚刚在下一个活动中拍摄的图片......但是我在输出图像时遇到问题。我相信我已经正确保存了图片......但我不确定如何读取数据。我查看了许多教程,但无法找到我应该在下一个活动中放置哪些方法来显示图像。以下是主要活动的代码:

import android.hardware.Camera;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

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


public class MainActivity extends ActionBarActivity {

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

    // Create an instance of Camera
    Camera mCamera = getCameraInstance();

    // Create our Preview view and set it as the content of our activity.
    CameraPreview mPreview = new CameraPreview(this, mCamera);
    FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
    preview.addView(mPreview);

    // Add a listener to the Capture button
    Button captureButton = (Button) findViewById(R.id.button_capture);

    captureButton.setOnClickListener(new View.OnClickListener() {

                                         @Override
                                         public void onClick(View v) {
                                             Camera mCamera = getCameraInstance();
                                             // get an image from the camera
                                             mCamera.takePicture(null, null, mPicture);
                                         }
                                     }
    );





}
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {

        File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
        if (pictureFile == null){
            Log.d("Logtag:", "Error creating media file, check storage permissions: "
                   );
            return;
        }

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.close();
        } catch (FileNotFoundException e) {
            Log.d("Logtag:", "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d("Logtag:", "Error accessing file: " + e.getMessage());
        }
    }
};


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
/** A safe way to get an instance of the Camera object. */
public Camera getCameraInstance(){
    Camera c = null;
    try {
        c = Camera.open(); // attempt to get a Camera instance
    }
    catch (Exception e){
        // Camera is not available (in use or does not exist)
        Toast.makeText(getApplicationContext(), "Camera is not available (in use or does not exist)",
                Toast.LENGTH_LONG).show();
    }
    return c; // returns null if camera is unavailable
}





public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;

/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
    return Uri.fromFile(getOutputMediaFile(type));
}

/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this.

    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), "MyCameraApp");
    // This locat ion works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            Log.d("Logtag", "failed to create directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE){
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                "IMG_"+ timeStamp + ".jpg");
    } else if(type == MEDIA_TYPE_VIDEO) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                "VID_"+ timeStamp + ".mp4");
    } else {
        return null;
    }

    return mediaFile;
}

}

3 个答案:

答案 0 :(得分:0)

将图像文件的路径或uri传递给intent中的其他活动。扩展包括ImageView的布局。使用BitmapFactory解码图像文件。在ImageView上设置生成的位图。

答案 1 :(得分:0)

我知道这可能不是您正在寻找的答案,但您是否考虑过使用图书馆来显示您刚刚拍摄的照片?

我通常使用毕加索,我很高兴。 http://square.github.io/picasso/

如果您有图像路径和视图以显示图像,您基本上可以在一行代码中显示图像,如:

Picasso.with(context).load(pictureFile.getAbsolutePath()).into(view);

答案 2 :(得分:0)

您需要解码文件数据。为了节省内存,请将位图缩小到适合您的显示的位置(maxSize)

public static Bitmap decodeFile(File f, final int maxSize) {

    Bitmap b = null;
    // Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;

    FileInputStream fis = null;
    try {
        fis = new FileInputStream(f);
        BitmapFactory.decodeStream(fis, null, o);
        fis.close();

        int scale = 1;
        if (o.outHeight > maxSize || o.outWidth > maxSize) {
            scale = (int) Math.pow(2, (int) Math.round(Math.log(maxSize / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
        }

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;

        fis = new FileInputStream(f);
        b = BitmapFactory.decodeStream(fis, null, o2);

    } catch (Exception e) {
        Log.e(ImageUtils.TAG, "Error processing bitmap", e);
    } finally {
        FileUtil.closeQuietly(fis);
    }


    return b;
}

然后可以在ImageView中使用位图

e.g

mImageView.setImageBitmap(bitmap);