我是Android开发的初学者,我必须继续由前同事开始的项目。 在这个应用程序中,我们有客户文件,包含个人信息,还有一个按钮,允许我们拍照。 但问题是:这在HTC Desire和其他Android手机上运行良好,但不适用于Galaxy S和Galaxy S II。
使用的算法是基本的:当我们触摸屏幕或中心垫时,我们使用“camera”类中的autoFocus方法。然后,我们显示刚拍摄的照片,当我们按下菜单按钮或“后退”按钮时,会显示一个对话框,询问我们是否要保存图片。
这是“CameraView.java”代码:
public class CameraView extends Activity implements Callback, AutoFocusCallback
{
private Camera camera;
private FrameLayout layout;
private SurfaceView surface;
private String idPatient;
private boolean start;
private int click;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setBackgroundDrawable(null);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
layout = new FrameLayout(this);
surface = new SurfaceView(this);
surface.getHolder().addCallback(this);
surface.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
layout.addView(surface);
setContentView(layout);
idPatient = (String) this.getIntent().getStringExtra("lePatient");
start = false;
click = 0;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER )
{
click++;
if((!start)&&(click==1))
{
camera.autoFocus(this);
return true;
}
}
if (keyCode == KeyEvent.KEYCODE_BACK )
{
finish();
}
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
click++;
if((!start)&&(click==1))
{
camera.autoFocus(this);
return true;
}
}
return false;
}
public void onAutoFocus(boolean success, Camera camera)
{
start = true;
PictureCallback picture = new PictureCallback()
{
@Override
public void onPictureTaken(byte[] data, Camera camera)
{
Intent intentPhoto = new Intent(CameraView.this, PhotoView.class);
intentPhoto.putExtra("lePatient", idPatient);
intentPhoto.putExtra("laPhoto", data);
CameraView.this.startActivityForResult(intentPhoto, 101);
camera.startPreview();
start = false;
click = 0;
}
};
camera.takePicture(null, null, picture);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
Camera.Parameters params = camera.getParameters();
params.setPictureFormat(PixelFormat.JPEG);
params.setPreviewSize(width, height);
camera.setParameters(params);
camera.startPreview();
}
@Override
public void surfaceCreated(SurfaceHolder holder)
{
try
{
camera = Camera.open();
camera.setPreviewDisplay(holder);
}
catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
}
/**
* Fermeture de l'activity
*/
protected void onDestroy()
{
super.onDestroy();
}
}
“photoView.java”类:
public class PhotoView extends Activity
{
private static final int DIALOG_ENREGISTRER = 10;
private ImageView photo;
private byte[] data;
private String idPatient;
private DBAdapter db;
/**
* Creation de l'activity
*/
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setBackgroundDrawable(null);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.photoview);
db = new DBAdapter(this);
db.open();
idPatient = (String) this.getIntent().getStringExtra("lePatient");
data = (byte[]) this.getIntent().getByteArrayExtra("laPhoto");
photo = (ImageView) this.findViewById(R.id.photo);
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
int w = bmp.getWidth();
int h = bmp.getHeight();
Matrix mtx = new Matrix();
mtx.postRotate(90);
Bitmap rotatedBMP = Bitmap.createBitmap(bmp, 0, 0, w, h, mtx, true);
WindowManager manager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
int height= display.getHeight();
int width= display.getWidth();
Bitmap bmpFullScreen = Bitmap.createScaledBitmap(rotatedBMP, width, height, true);
photo.setImageBitmap(bmpFullScreen);
}
/**
* Permet de récuperer un évènement de click de touche
*/
public boolean onKeyUp(int keyCode, KeyEvent event) {
if((keyCode==KeyEvent.KEYCODE_BACK) ||(keyCode==KeyEvent.KEYCODE_MENU))// zoom in
{
showDialog(DIALOG_ENREGISTRER);
}
//return super.onKeyUp(keyCode, event);
return false;
}
/**
* Permet de créer des boites de dialog
*/
protected Dialog onCreateDialog(int id)
{
switch (id)
{
case DIALOG_ENREGISTRER:
return new AlertDialog.Builder(PhotoView.this)
.setIcon(android.R.drawable.ic_menu_info_details)
.setTitle("Enregistrer ?")
.setPositiveButton("OUI", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
String title = PhotoView.this.savePhotoDB();
PhotoView.this.savePhotoFS(title);
finish();
}
})
.setNegativeButton("NON", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
finish();
}
})
.create();
}
return null;
}
/**
* Permet de sauvegarder une photo dans la base de données
* @param title
*/
private String savePhotoDB()
{
Log.i("","idPatient : " +idPatient);
String comment = "Note : ";
Log.i("","comment : " + comment);
Date maintenant = new Date(System.currentTimeMillis());
SimpleDateFormat formatDateJour = new SimpleDateFormat("yyyyddMM");
String date = formatDateJour.format(maintenant);
Log.i("","Date formatée : " + date);
SimpleDateFormat formatHeure = new SimpleDateFormat("mmss");
String heure = formatHeure.format(maintenant);
Log.i("","Heure formatée : " + heure);
String fileName = "photo"+date+heure+".jpeg";
Log.i("","fileName : " + fileName);
String title = "photo"+date+heure+".jpeg";
Log.i("","title : " + title);
String userDefined = "1";
Log.i("","userDefined : " + userDefined);
db.insererPhoto(idPatient, comment, date, fileName, title, userDefined);
return title;
}
/**
* Permet de sauvegarder une photo sur le file system
* @param title
*/
private void savePhotoFS(String title) {
try
{
File fs = new File(PhotoView.this.getFilesDir()+"/"+title);
FileOutputStream fos = new FileOutputStream(fs);
fos.write(data);
fos.flush();
fos.close();
//Toast.makeText(PhotoView.this, ""+fs.getAbsolutePath(), Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Fermeture de l'activity
*/
protected void onDestroy()
{
db.close();
super.onDestroy();
}
}
有人能帮帮我吗?
感谢您阅读:)
答案 0 :(得分:3)
谢谢你的回答。
问题解决了! 以下是遇到同样问题的人的答案:
在这些方面:
Intent intentPhoto = new Intent(CameraView.this, PhotoView.class);
intentPhoto.putExtra("lePatient", idPatient);
intentPhoto.putExtra("laPhoto", data);
startActivityForResult(intentPhoto, 101);
“ intentPhoto.putExtra(”laPhoto“,data)”方法无法执行,因为“数据”大小太大。 “数据”包含拍摄的照片,而在Galaxy SII上,图像分辨率非常大,因此这种方法无法发送数据(因为它的大小有限)。
所以我只是在 surfaceChanged 方法上使用 setPictureSize(width,height)方法( Camera.Parameters )来定义我自己的分辨率( 1024x768),现在它的工作正常!
小心:在定义自己的分辨率之前,您必须使用 getSupportedPictureSizes()方法验证设备是否已接受该分辨率
希望这可以帮助某人
答案 1 :(得分:1)
以下是我用来做同样事情的代码。它会创建一个SurfaceView并启动相机预览。点击屏幕上的任何位置时,它会拍照,显示并显示两个按钮 - 保存和重试(请参阅onPictureTaken方法)。用户可以单击“保存”,然后将数据返回给应用程序,或者重试(从我可以告诉我没有完成重试功能 - 它只是调用finish())。希望这会有所帮助。
public class SnapShot extends Activity implements OnClickListener,
SurfaceHolder.Callback, Camera.PictureCallback {
SurfaceView cameraView;
SurfaceHolder surfaceHolder;
Camera camera;
LayoutInflater inflater;
Uri imageFileUri;
Button save;
Button retry;
View viewControl;
LayoutParams layoutParamsControl;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_camera);
cameraView = (SurfaceView) this.findViewById(R.id.CameraView);
surfaceHolder = cameraView.getHolder();
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceHolder.addCallback(this);
cameraView.setFocusable(true);
cameraView.setFocusableInTouchMode(true);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
inflater = LayoutInflater.from(getBaseContext());
viewControl = inflater.inflate(R.layout.camera_control, null);
save = (Button) viewControl.findViewById(R.id.vc_btn_keep);
retry = (Button)viewControl.findViewById(R.id.vc_btn_discard);
layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
camera.startPreview();
}
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
try {
Camera.Parameters parameters = camera.getParameters();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
// This is an undocumented although widely known feature
parameters.set("orientation", "portrait");
// For Android 2.2 and above
camera.setDisplayOrientation(90);
// Uncomment for Android 2.0 and above
// parameters.setRotation(90);
} else {
// This is an undocumented although widely known feature
parameters.set("orientation", "landscape");
// For Android 2.2 and above
camera.setDisplayOrientation(0);
// Uncomment for Android 2.0 and above
// parameters.setRotation(0);
}
camera.setParameters(parameters);
camera.setPreviewDisplay(holder);
} catch (IOException exception) {
camera.release();
Log.v("surfaceCreated", exception.getMessage());
}
camera.startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
}
@Override
public void onPictureTaken(final byte[] data, Camera camera) {
this.addContentView(viewControl, layoutParamsControl);
save.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
insertImage(data);
Intent i = new Intent();
i.putExtra("data", imageFileUri.toString());
setResult(-1, i);
finish();
}});
retry.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}});
}
public void insertImage(byte[] data)
{
Bitmap b = null;
try {
b = GeneralUtils.decodeFile(data, this);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 80, bos);
//b = null;
Bitmap bitmap = BitmapFactory.decodeByteArray(bos.toByteArray(), 0, bos.size());
Matrix m = new Matrix();
if (b.getWidth() > b.getHeight())
{
m.postRotate(90);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
}
String result = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "", "");
b.recycle();
data = null;
b = null;
m = null;
imageFileUri = Uri.parse(result);
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(null, null, null, this);
}
}