第58章、拍照功能实现(从零开始学Android)

第58章、拍照功能实现(从零开始学Android)Android有两种拍照方法,一种是直接调用系统的照相Intent,使用onActivityResult获取图片资源或者指定图片路径,拍照返回成功后去指定路径读取图片;一种是用SurfaceView自定义界面,添加业务个性化功能。一、第一种方法1、设计界面  (1)、布局文件  打开activity_main.xml文件。  输入以下代码: 

大家好,又见面了,我是你们的朋友全栈君。

  Android有两种拍照方法,一种是直接调用系统的照相Intent,使用 onActivityResult获取图片资源或者指定图片路径,拍照返回成功后去指定路径读取图片;一种是用SurfaceView自定义界面,添加业务个性化功能。

一、第一种方法

1、设计界面

  (1)、布局文件

  打开activity_main.xml文件。

  输入以下代码:

 

<?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">

    <Button
        android:id="@+id/bysystem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="调用系统相机不返回结果" />

    <Button
        android:id="@+id/byself"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="调用系统相机并返回结果" />

    <ImageView
        android:id="@+id/photo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

2、程序文件

  打开“src/com.genwoxue.camera/MainActivity.java”文件。

  然后输入以下代码:

package com.genwoxue.camera;


import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	private Button btnSystem=null;
	private Button btnSelf=null;
	private File file=null;	
	private static final String FILENAME="photo.jpg";
	
	private static String path="";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		btnSystem=(Button)super.findViewById(R.id.bysystem);
		btnSelf=(Button)super.findViewById(R.id.byself);
		
		//调用系统照相机,不返回结果
		btnSystem.setOnClickListener(new OnClickListener(){
        	public void onClick(View v)
        	{ 
        		Intent intent = new Intent();  
        		intent.setAction("android.media.action.STILL_IMAGE_CAMERA"); 
        		startActivity(intent); 
        	}
		});
		
		//调用系统照相机,返回结果
		btnSelf.setOnClickListener(new OnClickListener(){
        	public void onClick(View v)
        	{  
        		//判断外部存储卡是否存在
        		if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
        			Toast.makeText(getApplicationContext(), "读取失败,SD存储卡不存在!", Toast.LENGTH_LONG).show();  
        			return;
        		}
        		
        		//判断文件是否存在
        		path=Environment.getExternalStorageDirectory().toString()+File.separator+"genwoxue"+File.separator+FILENAME;
        		file=new File(path);
        		if(!file.exists()){
        			File vDirPath = file.getParentFile(); 
        			vDirPath.mkdirs(); 
        			Toast.makeText(getApplicationContext(), "photo.jpg文件不存在!", Toast.LENGTH_LONG).show();  
        			return;
        		}
        		
        		Uri uri = Uri.fromFile(file); 
        		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
        		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        		startActivityForResult(intent, 1); 
        		
        	}
		});
		
	}
	
}

 3、运行结果

  第58章、拍照功能实现(从零开始学Android) 

  第58章、拍照功能实现(从零开始学Android)

 

二、第二种方法。

1、设计界面

  (1)、布局文件

  打开activity_main.xml文件。

  输入以下代码:

<?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">


    <Button
        android:id="@+id/byself"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="拍照(自定义相机)" />
    
    <SurfaceView
        android:id="@+id/photo"
        android:layout_width="300dip"
        android:layout_height="400dip" />

</LinearLayout>

2、程序文件

  打开“src/com.genwoxue.cameradiy/MainActivity.java”文件。

  然后输入以下代码:

package com.genwoxue.cameradiy;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	private Button btnSelf=null;
	private Camera camera=null;
	private static final String TAG="PhotoDIY";
	private String path="";
	private boolean previewRuning=true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		//初始化SurfaceView
		SurfaceView mpreview = (SurfaceView) this.findViewById(R.id.photo); 
		SurfaceHolder mSurfaceHolder = mpreview.getHolder(); 
		mSurfaceHolder.addCallback(new SurfaceViewCallback()); 
		mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 

		
		btnSelf=(Button)super.findViewById(R.id.byself);
		
		//拍照(自定义相机)
		btnSelf.setOnClickListener(new OnClickListener(){
        	public void onClick(View v)
        	{  
        		if(camera!=null){
        			camera.autoFocus(new AutoFocusCallbackimpl());
        		}
        	}
		});
		
	}
	
	public class SurfaceViewCallback implements SurfaceHolder.Callback{
		
		@Override
		public void surfaceChanged(SurfaceHolder holder,int format,int width,int heith){

		}
		
		@Override
		public void surfaceCreated(SurfaceHolder holder){
			//现在智能机可能会有多个镜头:一般前置为1;后置为0
			MainActivity.this.camera=Camera.open(0);
			//设置参数
			Parameters param=camera.getParameters();
			param.setPictureFormat(PixelFormat.JPEG);
			param.set("jpeg-quality",85);
			param.setPreviewFrameRate(5);
			camera.setParameters(param);
			
			try {
				camera.setPreviewDisplay(holder);	//成像在SurfaceView
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			//开始预览
			camera.startPreview();
			previewRuning=true;
		}
		
		@Override
		public void surfaceDestroyed(SurfaceHolder holder){
			if(camera!=null){
				if(previewRuning){
					camera.stopPreview();
					previewRuning=false;
				}
				camera.release();
			}
		}
	}
	
	//调用takePicture()方法时,自动执行pictureCallback回调方法
	public PictureCallback picture=new PictureCallback(){
		@Override
		public void onPictureTaken(byte[] data,Camera camera){		
			Bitmap bmp=BitmapFactory.decodeByteArray(data, 0, data.length);
			//判断外部存储卡是否存在
    		if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
    			Toast.makeText(getApplicationContext(), "读取失败,SD存储卡不存在!", Toast.LENGTH_LONG).show();  
    			return;
    		}
    		
    		//判断文件是否存在
    		path=Environment.getExternalStorageDirectory().toString()
    				+File.separator
    				+"genwoxue"
    				+File.separator
    				+System.currentTimeMillis()
    				+".jpg";
    		
    		File file=new File(path);
    		if(!file.exists()){
    			File vDirPath = file.getParentFile(); 
    			vDirPath.mkdirs(); 
    			Toast.makeText(getApplicationContext(), "photo.jpg文件不存在!", Toast.LENGTH_LONG).show();  
    			return;
    		}
    		
    		try {
				BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(file));
				bmp.compress(Bitmap.CompressFormat.JPEG, 80, bos);
				try {
					bos.flush();
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
    		
    		camera.stopPreview();
    		camera.startPreview();
    		
		}
	};

	//对焦回回调
	public class AutoFocusCallbackimpl implements AutoFocusCallback{
		public void onAutoFocus(boolean success,Camera camera){
			
			if(success){
				camera.takePicture(shutter, null, picture);
				camera.stopPreview();
			}
		}
	}
	
	//快门回调
	public ShutterCallback shutter=new ShutterCallback(){
		public void onShutter(){
			
		}
	};
}

3、运行结果

  第58章、拍照功能实现(从零开始学Android)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/150351.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 大数据采集技术概述「建议收藏」

    大数据采集技术概述「建议收藏」大数据采集是指从传感器和智能设备、企业在线系统、企业离线系统、社交网络和互联网平台等获取数据的过程。数据包括RFID数据、传感器数据、用户行为数据、社交网络交互数据及移动互联网数据等各种类型的结构化、半结构化及非结构化的海量数据。不但数据源的种类多,数据的类型繁杂,数据量大,并且产生的速度快,传统的数据采集方法完全无法胜任。所以,大数据采集技术面临着许多技术挑战,一方面需要保证数据…

    2022年6月24日
    44
  • Vue响应式实现原理[通俗易懂]

    Vue响应式实现原理[通俗易懂]Vue响应式原理Vue是数据驱动视图实现双向绑定的一种前端框架,采用的是非入侵性的响应式系统,不需要采用新的语法(扩展语法或者新的数据结构)实现对象(model)和视图(view)的自动更新,数据层(Model)仅仅是普通的Javascript对象,当Modle更新后view层自动完成更新,同理view层修改会导致model层数据更新。双向绑定实现机制Vue的双向绑定实现机制核心:依赖于Object.defineProperty()实现数据劫持订阅模式Object.defineProper

    2022年5月18日
    41
  • HttpServletResponse设置ContentType失效

    HttpServletResponse设置ContentType失效现象:使用postman测试响应ContentType没有值这是我的部分代码:@Overridepublicvoiddownload(LongbuildingId,HttpServletResponseresponse)throwsIOException{ ……IoUtil.write(response.getOutputStream(),true,bytes);response.setContentType(imag

    2022年7月19日
    49
  • LINUX安全设置

    LINUX安全设置

    2021年8月31日
    52
  • 移动硬盘格式导致无法copy大文件

    移动硬盘格式导致无法copy大文件

    2022年3月8日
    40
  • pycharm有什么好用的插件_pycharm插件推荐

    pycharm有什么好用的插件_pycharm插件推荐目录一、安装二、导入及设置三、使用一、安装在全局环境中(不要在虚拟环境中安装pipinstallautopep8二、导入及设置在PyCharm导入这个工具,具体设置如下图:Name:AutoPep8Description:autopep8yourcodeProgram:autopep8Arguments:–in-place–aggressive–aggressive$FilePath$Workingdirectory:$ProjectFileDir$

    2022年8月29日
    1

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号