如何创建我们自己的相机应用程序,在Android中拍摄图像时减少图像像素
我是android新手, 我的应用程序在分辨率较低(摄像头)的手机上运行良好,但如果我的应用程序在高(摄像头)像素手机上使用,如果我使用它几次(4到5次),它就会挂起。我的问题是,我们能否创建摄像头代码,使我的行为像分辨率较低的摄像头 我用于照相机的代码。如何创建我们自己的相机应用程序,在Android中拍摄图像时减少图像像素,android,android-camera,Android,Android Camera,我是android新手, 我的应用程序在分辨率较低(摄像头)的手机上运行良好,但如果我的应用程序在高(摄像头)像素手机上使用,如果我使用它几次(4到5次),它就会挂起。我的问题是,我们能否创建摄像头代码,使我的行为像分辨率较低的摄像头 我用于照相机的代码。 //摄像机代码 public void openCamera() { if (Helper.checkCameraHardware(this)) { try { SimpleDateForma
//摄像机代码
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;
}
public void openCamera(){
if(助手.检查摄像头硬件(此)){
试一试{
SimpleDataFormat sdf=新SimpleDataFormat(“yyyy-MM-dd”);
字符串dateFileName=sdf.format(new Date());
SimpleDataFormat sdf1=新的SimpleDataFormat(“yyyyMMddHHmmss”);
字符串curentDateandTime=sdf1.format(new Date());
File sdImageMainDirectory=新文件(环境)
.getExternalStorageDirectory().getPath()
+ "/"
+Helper.IMG_文件夹+“/”+日期文件名);
如果(!sdImageMainDirectory.exists()){
sdImageMainDirectory.mkdirs();
}
String PATH=Environment.getExternalStorageDirectory()
.getPath()
+ "/"
+Helper.IMG_文件夹
+ "/"
+日期文件名+“/”;
//路径=目录的路径,映像\路径=映像的完整路径
image_PATH=PATH+curentDateandTime+“.jpg”;
System.out.println(“开放式摄像机中的图像路径”+图像路径);
Log.d(“摄像头”,“文件存在于OC”+image_PATH+”中要创建自己的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>
import java.io.FileNotFoundException;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.util.Date;
导入android.content.Context;
导入android.content.Intent;
导入android.graphics.PixelFormat;
导入android.hardware.Camera;
导入android.hardware.Camera.AutoFocusCallback;
导入android.os.Bundle;
导入android.telephony.TelephonyManager;
导入android.view.Menu;
导入android.view.MenuInflater;
导入android.view.MenuItem;
导入android.view.SurfaceHolder;
导入android.view.SurfaceView;
导入android.view.view;
导入android.view.Window;
导入android.view.WindowManager;
导入android.view.view.OnClickListener;
导入android.widget.Toast;
公共类GeoCamera扩展活动实现SurfaceHolder.Callback,
onclick侦听器{
静态最终int FOTO_模式=0;
私人SurfaceView surefaceView;
私人担保持有人;
私人摄像机;
私有布尔预览运行=false;
/**在首次创建活动时调用*/
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
getWindow().setFormat(像素格式.半透明);
requestWindowFeature(窗口。功能\u无\u标题);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_全屏,
WindowManager.LayoutParams.FLAG(全屏);
//加载布局
setContentView(R.layout.main);
surefaceView=(SurfaceView)findViewById(R.id.surface\U摄像头);
surefaceView.setOnClickListener(此);
surefaceHolder=surefaceView.getHolder();
surefaceHolder.addCallback(此);
surefaceHolder.setType(SurfaceHolder.SURFACE类型推送缓冲区);
}
/*
*启动自动对焦
*/
AutoFocusCallback myAutoFocusCallback=新的AutoFocusCallback(){
@凌驾
自动对焦上的公共空白(布尔值arg0,相机arg1){
//TODO自动生成的方法存根
Toast.makeText(getApplicationContext(),
“‘已经准备好拍照了!!!”,
吐司。长度(短)。show();
}
};
Camera.PictureCallback PictureCallback=新建Camera.PictureCallback(){
/*
*(非Javadoc)
*
*@请参阅android.hardware.Camera.PictureCallback#onPictureTaken(字节[],
*android.hardware.Camera)创建新的意图并存储图像
*/
公共void onPictureTaken(字节[]数据,摄像头){
//TODO自动生成的方法存根
如果(数据!=null){
Intent imgIntent=新Intent();
storeByteImage(数据);
camera.startPreview();
设置结果(FOTO_模式,imgIntent);
}
}
};
/*
*在存储图像时调用
*/
公共布尔存储字节图像(字节[]数据){
//创建.jpg文件并修改exif数据
字符串filename=“/sdcard”
+格式(“/%d.jpg”,System.currentTimeMillis());
试一试{
FileOutputStream FileOutputStream=新的FileOutputStream(文件名);
试一试{
fileOutputStream.write(数据);
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
fileOutputStream.flush();
fileOutputStream.close();
返回true;
}catch(filenotfounde异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
返回false;
}
/*
*(非Javadoc)
*
*@see android.view.view.OnClickListener#onClick(android.view.view)调用
*在曲面上单击时
*/
公共void onClick(视图v){
//TODO自动生成的方法存根
拍照(空,pictureCallBack,pictureCallBack);
}
/*
*(非Javadoc)
*
*@见
*android.view.SurfaceHolder.Callback#surfaceChanged(android.view.SurfaceHolder
*,int,int,int)
*/
公共无效表面更改(表面文件夹持有者,整型格式,整型宽度,
整数高度){
//TODO自动生成的方法存根
如果(预览运行){
cam.stopPreview();
}
Camera.Parameters=cam.getParameters();
列表大小=参数。getSupportedPictureSizes();
高度=大小。获取(0)。高度;
宽度=大小。获取(0)。宽度;
parameters.setPictureSi