【问题标题】:Android Camera Application: How to display picture after it is saved internally?Android相机应用程序:内部保存后如何显示图片?
【发布时间】:2015-02-24 21:05:46
【问题描述】:

所以我想构建一个使用相机并在内部(在应用程序内)保存图像的 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;
}

}

【问题讨论】:

    标签: java android android-camera storage preview


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      我通常使用毕加索,我对此非常满意。 http://square.github.io/picasso/

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

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

      【讨论】:

        【解决方案3】:

        您需要对文件数据进行解码。为了节省内存,请将位图缩小到适合您的显示的大小 (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 中使用位图

        例如

        mImageView.setImageBitmap(bitmap);
        

        【讨论】:

        • 对不起,我真的很陌生。位图解码器放在第二个活动中,对吗?如何将文件从相机活动传递到将显示它的第二个活动?
        • 当您开始您的新活动时,您可以将“附加”添加到Intent。在那里您可以指定文件名。例如。 intent.putExtra("THE_FILE", filename)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-14
        • 1970-01-01
        • 2018-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多