如何在Android中捕获图像时创建我们自己的相机应用程序以减少图像像素

时间:2013-12-31 05:09:52

标签: android android-camera

我是android新手, 我的应用程序在较少(相机)分辨率的手机中工作正常,但如果我的应用程序用于高(相机)像素移动,它挂起,如果我使用它几次(4到5)。我的问题是我们可以创建相机代码,以便我表现得像分辨率较低的相机?

我用于相机的代码。
        //摄像头代码

public void openCamera() {

    if (Helper.checkCameraHardware(this)) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateFileName = sdf.format(new Date());

            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
            String curentDateandTime = sdf1.format(new Date());

            File sdImageMainDirectory = new File(Environment
                    .getExternalStorageDirectory().getPath()
                    + "/"
                    + Helper.IMG_FOLDER + "/" + dateFileName);
            if (!sdImageMainDirectory.exists()) {
                sdImageMainDirectory.mkdirs();
            }

            String PATH = Environment.getExternalStorageDirectory()
                    .getPath()
                    + "/"
                    + Helper.IMG_FOLDER
                    + "/"
                    + dateFileName + "/";
            // PATH = PATH OF DIRECTORY,image_PATH = full path of IMAGE

            image_PATH = PATH + curentDateandTime + ".jpg";

            System.out.println("image_PATH In open camera" + image_PATH);
            Log.d("Camera", "File exist at in OC" + image_PATH + "  <<");

            File file = new File(PATH, curentDateandTime + ".jpg");

            Uri outputFileUri = Uri.fromFile(file);

            Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
            i.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            startActivityForResult(i, 1234);

        } catch (Exception e) {
            Helper.AlertBox(this,
                    "Error No: 001\nPlease contact Bluefrog technical person.\n"
                            + e.toString());
        }
    } else {
        // Helper.AlertBox(this, "Camera Not Found.!");
        Helper.AlertBox(this, "Image Not Captured !");
        image_PATH = "";
        SENDING_IMAGE_PATH = "";
    }
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // image_PATH = "";
    image_str = "";

    // super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 1234) {
        if (resultCode == RESULT_OK) {
            // restorePreferences();

            Log.e("image_PATH in OnActivityResultSet", "File exist at "
                    + image_PATH);

            Log.d("Camera", "File exist at " + image_PATH + "  <<");

            File file = new File(image_PATH);
            if (file.exists()) {

                Log.e("File exist condition :", "File exist at "
                        + image_PATH);

                try {

                    iv_MEPhoto.setImageBitmap(Helper.getImage(file
                            .getPath()));

                    iv_MEPhoto.setVisibility(View.VISIBLE);
                    photoTaken = true;
                    SENDING_IMAGE_PATH = image_PATH;

                    Log.e("File exist condition :", "File exist at "
                            + image_PATH);

                } catch (Exception e) {
                    Helper.AlertBox(this,
                            "Error No: 004\nPlease contact Bluefrog technical person.\n"
                                    + e.toString());
                    Log.e("Error reading file", e.toString());
                }

            } else {
                image_PATH = "";
                SENDING_IMAGE_PATH = "";

                Helper.AlertBox(this,
                        "Error No: 005\nPlease contact Bluefrog technical person.");
            }
        } else {
            Helper.AlertBox(this, "Image Not Captured.");
            image_PATH = "";
            SENDING_IMAGE_PATH = "";
        }
    }

}

// camera code end
//  in HELPER cLASS reqWidth = 320 ,reqHeight =240
public static Bitmap getImage(String filePath) {

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, options);

    options.inSampleSize = calculateInSampleSize(options, reqWidth,
            reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
    bmp = Bitmap.createScaledBitmap(bmp, reqWidth, reqHeight, true);

    return bmp;
}

public static String getImageString(String filePath) {

    String imageString = "";

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, options);

    options.inSampleSize = calculateInSampleSize(options, reqWidth,
            reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    Bitmap bmp = BitmapFactory.decodeFile(filePath, options);

    bmp = Bitmap.createScaledBitmap(bmp, reqWidth, reqHeight, true);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 70, baos); // bm is the bitmap
    // object
    byte[] byte_arr = baos.toByteArray();
    imageString = Base64.encodeBytes(byte_arr);
    return imageString;

}
public static int calculateInSampleSize(BitmapFactory.Options options,
        int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        // Calculate ratios of height and width to requested height and
        // width
        final int heightRatio = Math.round((float) height
                / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will
        // guarantee
        // a final image with both dimensions larger than or equal to the
        // requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }

    return inSampleSize;
}

1 个答案:

答案 0 :(得分:0)

为了让你拥有自己的Android应用程序,你需要这些权限

 <uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

在你的活动应该包括

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Toast;


public class GeoCamera extends Activity implements SurfaceHolder.Callback,
    OnClickListener {

static final int FOTO_MODE = 0;

private SurfaceView surefaceView;
private SurfaceHolder surefaceHolder;
private Camera camera;

private boolean previewRunning = false;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFormat(PixelFormat.TRANSLUCENT);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    // load the layout
    setContentView(R.layout.main);
    surefaceView = (SurfaceView) findViewById(R.id.surface_camera);
    surefaceView.setOnClickListener(this);
    surefaceHolder = surefaceView.getHolder();
    surefaceHolder.addCallback(this);
    surefaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

/*
 * initiate auto focus
 */
AutoFocusCallback myAutoFocusCallback = new AutoFocusCallback() {

    @Override
    public void onAutoFocus(boolean arg0, Camera arg1) {
        // TODO Auto-generated method stub
        Toast.makeText(getApplicationContext(),
                "'It is ready to take the photograph !!!",
                Toast.LENGTH_SHORT).show();
    }
};



Camera.PictureCallback pictureCallBack = new Camera.PictureCallback() {

    /*
     * (non-Javadoc)
     * 
     * @see android.hardware.Camera.PictureCallback#onPictureTaken(byte[],
     * android.hardware.Camera) create new intent and store the image
     */
    public void onPictureTaken(byte[] data, Camera camera) {
        // TODO Auto-generated method stub

        if (data != null) {
            Intent imgIntent = new Intent();
            storeByteImage(data);
            camera.startPreview();
            setResult(FOTO_MODE, imgIntent);
        }

    }
};

/*
 * called when image is stored
 */
public boolean storeByteImage(byte[] data) {
    // Create the <timestamp>.jpg file and modify the exif data
    String filename = "/sdcard"
            + String.format("/%d.jpg", System.currentTimeMillis());
    try {
        FileOutputStream fileOutputStream = new FileOutputStream(filename);
        try {
            fileOutputStream.write(data);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        fileOutputStream.flush();
        fileOutputStream.close();
        return true;

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}




/*
 * (non-Javadoc)
 * 
 * @see android.view.View.OnClickListener#onClick(android.view.View) called
 * when clicked on the surface
 */
public void onClick(View v) {
    // TODO Auto-generated method stub
    camera.takePicture(null, pictureCallBack, pictureCallBack);
}

/*
 * (non-Javadoc)
 * 
 * @see
 * android.view.SurfaceHolder.Callback#surfaceChanged(android.view.SurfaceHolder
 * , int, int, int)
 */
public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {
    // TODO Auto-generated method stub
    if (previewRunning) {
        cam.stopPreview();
    }
    Camera.Parameters parameters = cam.getParameters();
    List<Camera.Size> sizes = parameters.getSupportedPictureSizes();
    height = sizes.get(0).height;
    width = sizes.get(0).width;
    parameters.setPictureSize(width, height);
    Display display = ((WindowManager) getSystemService(WINDOW_SERVICE))
            .getDefaultDisplay();

    if (display.getRotation() == Surface.ROTATION_0) {
        parameters.setPreviewSize(width, height);
        cam.setDisplayOrientation(90);
    }

    cam.setParameters(parameters);
    try {
        cam.setPreviewDisplay(holder);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    cam.startPreview();
    previewRunning = true;
}

/*
 * (non-Javadoc)
 * 
 * @see
 * android.view.SurfaceHolder.Callback#surfaceCreated(android.view.SurfaceHolder
 * )
 */
public void surfaceCreated(SurfaceHolder holder) {
    // TODO Auto-generated method stub
    camera = Camera.open();

}

/*
 * (non-Javadoc)
 * 
 * @see android.view.SurfaceHolder.Callback#surfaceDestroyed(android.view.
 * SurfaceHolder) Called when it release the camera resource
 */
public void surfaceDestroyed(SurfaceHolder holder) {
    // TODO Auto-generated method stub
    camera.stopPreview();
    previewRunning = false;
    camera.release();
}



}

布局应包括

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<SurfaceView android:id="@+id/surface_camera"
    android:layout_width="fill_parent" android:layout_height="10dip"
    android:layout_weight="1">      
</SurfaceView>

您可以设置您选择的相机参数以获取更多详细信息:http://developer.android.com/reference/android/hardware/Camera.Parameters.html