700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > android 拍照 Camera类 使用照相机进行拍照 翻译

android 拍照 Camera类 使用照相机进行拍照 翻译

时间:2018-12-10 18:12:43

相关推荐

android 拍照 Camera类 使用照相机进行拍照  翻译

参考网址:/reference/android/hardware/Camera.html

android.hardware.Camera

The Camera class is used to set image capture settings, start/stop preview, snap pictures, and retrieve frames for encoding for video. This class is a client for the Camera service, which manages the actual camera hardware.

权限AndroidManifest.xml:

<uses-sdk ………… />

下面写上:

<uses-permission android:name="android.permission.CAMERA" /><uses-feature android:name="android.hardware.camera" /><uses-feature android:name="android.hardware.camera.autofocus" />

如果涉及到存储,则还应当添加:

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

To take pictures with this class, use the following steps:

获取个Camera实例open(int).获取已经存在(默认)的设置getParameters().如果必要,可以修改返回的Camera.Parameters对象 and 调用setParameters(Camera.Parameters).如果需要,也可以调用setDisplayOrientation(int).重要: 传递一个完全初始化后的SurfaceHoldersetPreviewDisplay(SurfaceHolder). Without a surface, the camera will be unable to start the preview.重要:调用startPreview()更新预览界面,预览必须在你拍照之前启动。 当你想要的时候,调用takePicture(Camera.ShutterCallback, Camera.PictureCallback, Camera.PictureCallback, Camera.PictureCallback)来捕获一张照片.等待 回调函数提供实际的图像数据。 照完之后,预览显示将会停止。如果想照更多的照片,请再次调用startPreview().调用stopPreview()来通知更新预览界面。重要:调用release()来释放相机,让其他应用程序使用. 应用程序应该用onPause()(and re-open()it inonResume())来立即释放相机.

To quickly switch to video recording mode, use these steps:

Obtain and initialize a Camera and start preview as described above. Callunlock()to allow the media process to access the camera.Pass the camera tosetCamera(Camera). SeeMediaRecorderinformation about video recording.When finished recording, callreconnect()to re-acquire and re-lock the camera.If desired, restart preview and take more photos or videos. CallstopPreview()andrelease()as described above.

This class is not thread-safe, and is meant for use from one event thread. Most long-running operations (preview, focus, photo capture, etc) happen asynchronously and invoke callbacks as necessary. Callbacks will be invoked on the event threadopen(int)was called from. This class's methods must never be called from multiple threads at once.

这个类不是线程安全的,并且是供一个事件线程使用。最长时间运行的操作(预览,对焦,照片拍摄等)发生 异步调用的回调是必要的。回调将在事件线程open(int)被调用后被调用。这个类的方法,绝不能从多个线程立即调用。

Caution:Different Android-powered devices may have different hardware specifications, such as megapixel ratings and auto-focus capabilities. In order for your application to be compatible with more devices, you should not make assumptions about the device camera specifications.

注意:不同版本的Android手机可能有不同的硬件规格,如像素的分级和自动对焦功能。为了让您的应用程序能与更多的设备兼容,你不应该做出有关该设备的摄像头规格的假设。

Constants

public static final String ACTION_NEW_PICTURE

Added in API level 14

Broadcast Action: A new picture is taken by the camera, and the entry of the picture has been added to the media store.getData()is URI of the picture.

Constant Value: "android.hardware.action.NEW_PICTURE"

public static final String ACTION_NEW_VIDEO

Added in API level 14

Broadcast Action: A new video is recorded by the camera, and the entry of the video has been added to the media store.getData()is URI of the video.

Constant Value: "android.hardware.action.NEW_VIDEO"

public static final int CAMERA_ERROR_SERVER_DIED

Added in API level 1

Media server died. In this case, the application must release the Camera object and instantiate a new one.

See Also
Camera.ErrorCallbackConstant Value: 100 (0x00000064)

public static final int CAMERA_ERROR_UNKNOWN

Added in API level 1

Unspecified camera error.

See Also
Camera.ErrorCallbackConstant Value: 1 (0x00000001)

Public Methods

public final void addCallbackBuffer (byte[] callbackBuffer)

Added in API level 8

Adds a pre-allocated buffer to the preview callback buffer queue. Applications can add one or more buffers to the queue. When a preview frame arrives and there is still at least one available buffer, the buffer will be used and removed from the queue. Then preview callback is invoked with the buffer. If a frame arrives and there is no buffer left, the frame is discarded. Applications should add buffers back when they finish processing the data in them.

For formats besides YV12, the size of the buffer is determined by multiplying the preview image width, height, and bytes per pixel. The width and height can be read fromgetPreviewSize(). Bytes per pixel can be computed fromgetBitsPerPixel(int)/ 8, using the image format fromgetPreviewFormat().

If using theYV12format, the size can be calculated using the equations listed insetPreviewFormat(int).

This method is only necessary whensetPreviewCallbackWithBuffer(PreviewCallback)is used. WhensetPreviewCallback(PreviewCallback)orsetOneShotPreviewCallback(PreviewCallback)are used, buffers are automatically allocated. When a supplied buffer is too small to hold the preview frame data, preview callback will return null and the buffer will be removed from the buffer queue.

Parameters
See Also
setPreviewCallbackWithBuffer(PreviewCallback)

public final void autoFocus (Camera.AutoFocusCallback cb)

Added in API level 1

Starts camera auto-focus and registers a callback function to run when the camera is focused. This method is only valid when preview is active (betweenstartPreview()and beforestopPreview()).

Callers should checkgetFocusMode()to determine if this method should be called. If the camera does not support auto-focus, it is a no-op andonAutoFocus(boolean, Camera)callback will be called immediately.

If your application should not be installed on devices without auto-focus, you must declare that your application uses auto-focus with the <uses-feature> manifest element.

If the current flash mode is notFLASH_MODE_OFF, flash may be fired during auto-focus, depending on the driver and camera hardware.

Auto-exposure lockgetAutoExposureLock()and auto-white balance locksgetAutoWhiteBalanceLock()do not change during and after autofocus. But auto-focus routine may stop auto-exposure and auto-white balance transiently during focusing.

Stopping preview withstopPreview(), or triggering still image capture withtakePicture(Camera.ShutterCallback, Camera.PictureCallback, Camera.PictureCallback), will not change the the focus position. Applications must call cancelAutoFocus to reset the focus.

If autofocus is successful, consider usingMediaActionSoundto properly play back an autofocus success sound to the user.

Parameters
See Also
cancelAutoFocus()setAutoExposureLock(boolean)setAutoWhiteBalanceLock(boolean)MediaActionSound

public final void cancelAutoFocus ()

Added in API level 5

Cancels any auto-focus function in progress. Whether or not auto-focus is currently in progress, this function will return the focus position to the default. If the camera does not support auto-focus, this is a no-op.

See Also
autoFocus(Camera.AutoFocusCallback)

public final boolean enableShutterSound (boolean enabled)

Added in API level 17

Enable or disable the default shutter sound when taking a picture.

By default, the camera plays the system-defined camera shutter sound whentakePicture(Camera.ShutterCallback, Camera.PictureCallback, Camera.PictureCallback)is called. Using this method, the shutter sound can be disabled. It is strongly recommended that an alternative shutter sound is played in theCamera.ShutterCallbackwhen the system shutter sound is disabled.

Note that devices may not always allow disabling the camera shutter sound. If the shutter sound state cannot be set to the desired value, this method will return false.canDisableShutterSoundcan be used to determine whether the device will allow the shutter sound to be disabled.

Parameters
Returns
trueif the shutter sound state was successfully changed.falseif the shutter sound state could not be changed.trueis also returned if shutter sound playback is already set to the requested state.
See Also
takePicture(Camera.ShutterCallback, Camera.PictureCallback, Camera.PictureCallback)canDisableShutterSoundCamera.ShutterCallback

public static void getCameraInfo (int cameraId, Camera.CameraInfo cameraInfo)

Added in API level 9

Returns the information about a particular camera. IfgetNumberOfCameras()returns N, the valid id is 0 to N-1.

public static int getNumberOfCameras ()

Added in API level 9

Returns the number of physical cameras available on this device.

public Camera.Parameters getParameters ()

Added in API level 1

Returns the current settings for this Camera service. If modifications are made to the returned Parameters, they must be passed tosetParameters(Camera.Parameters)to take effect.

See Also
setParameters(Camera.Parameters)

public final void lock ()

Added in API level 5

Re-locks the camera to prevent other processes from accessing it. Camera objects are locked by default unlessunlock()is called. Normallyreconnect()is used instead.

Since API level 14, camera is automatically locked for applications instart(). Applications can use the camera (ex: zoom) after recording starts. There is no need to call this after recording starts or stops.

If you are not recording video, you probably do not need this method.

Throws

public static Camera open (int cameraId)

Added in API level 9

Creates a new Camera object to access a particular hardware camera. If the same camera is opened by other applications, this will throw a RuntimeException.

You must callrelease()when you are done using the camera, otherwise it will remain locked and be unavailable to other applications.

Your application should only have one Camera object active at a time for a particular hardware camera.

Callbacks from other methods are delivered to the event loop of the thread which called open(). If this thread has no event loop, then callbacks are delivered to the main application event loop. If there is no main application event loop, callbacks are not delivered.

Caution:On some devices, this method may take a long time to complete. It is best to call this method from a worker thread (possibly usingAsyncTask) to avoid blocking the main application UI thread.

Parameters
Returns
a new Camera object, connected, locked and ready for use.
Throws
See Also
getCameraDisabled(ponentName)

public static Camera open ()

Added in API level 1

Creates a new Camera object to access the first back-facing camera on the device. If the device does not have a back-facing camera, this returns null.

See Also
open(int)

public final void reconnect ()

Added in API level 8

Reconnects to the camera service after another process used it. Afterunlock()is called, another process may use the camera; when the process is done, you must reconnect to the camera, which will re-acquire the lock and allow you to continue using the camera.

Since API level 14, camera is automatically locked for applications instart(). Applications can use the camera (ex: zoom) after recording starts. There is no need to call this after recording starts or stops.

If you are not recording video, you probably do not need this method.

Throws

public final void release ()

Added in API level 1

Disconnects and releases the Camera object resources.

You must call this as soon as you're done with the Camera object.

public void setAutoFocusMoveCallback (Camera.AutoFocusMoveCallback cb)

Added in API level 16

Sets camera auto-focus move callback.

Parameters

public final void setDisplayOrientation (int degrees)

Added in API level 8

Set the clockwise rotation of preview display in degrees. This affects the preview frames and the picture displayed after snapshot. This method is useful for portrait mode applications. Note that preview display of front-facing cameras is flipped horizontally before the rotation, that is, the image is reflected along the central vertical axis of the camera sensor. So the users can see themselves as looking into a mirror.

This does not affect the order of byte array passed inonPreviewFrame(byte[], Camera), JPEG pictures, or recorded videos. This method is not allowed to be called during preview.

If you want to make the camera image show in the same orientation as the display, you can use the following code.

public static void setCameraDisplayOrientation(Activity activity,int cameraId, android.hardware.Camera camera) {android.hardware.Camera.CameraInfo info =new android.hardware.Camera.CameraInfo();android.hardware.Camera.getCameraInfo(cameraId, info);int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();int degrees = 0;switch (rotation) {case Surface.ROTATION_0: degrees = 0; break;case Surface.ROTATION_90: degrees = 90; break;case Surface.ROTATION_180: degrees = 180; break;case Surface.ROTATION_270: degrees = 270; break;}int result;if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {result = (info.orientation + degrees) % 360;result = (360 - result) % 360; // compensate the mirror} else {// back-facingresult = (info.orientation - degrees + 360) % 360;}camera.setDisplayOrientation(result);}

Starting from API level 14, this method can be called when preview is active.

Parameters
See Also
setPreviewDisplay(SurfaceHolder)

public final void setErrorCallback (Camera.ErrorCallback cb)

Added in API level 1

Registers a callback to be invoked when an error occurs.

Parameters

public final void setFaceDetectionListener (Camera.FaceDetectionListener listener)

Added in API level 14

Registers a listener to be notified about the faces detected in the preview frame.

Parameters
See Also
startFaceDetection()

public final void setOneShotPreviewCallback (Camera.PreviewCallback cb)

Added in API level 3

Installs a callback to be invoked for the next preview frame in addition to displaying it on the screen. After one invocation, the callback is cleared. This method can be called any time, even when preview is live. Any other preview callbacks are overridden.

If you are using the preview data to create video or still images, strongly consider usingMediaActionSoundto properly indicate image capture or recording start/stop to the user.

Parameters
See Also
MediaActionSound

public void setParameters (Camera.Parameters params)

Added in API level 1

Changes the settings for this Camera service.

Parameters
Throws
See Also
getParameters()

public final void setPreviewCallback (Camera.PreviewCallback cb)

Added in API level 1

Installs a callback to be invoked for every preview frame in addition to displaying them on the screen. The callback will be repeatedly called for as long as preview is active. This method can be called at any time, even while preview is live. Any other preview callbacks are overridden.

If you are using the preview data to create video or still images, strongly consider usingMediaActionSoundto properly indicate image capture or recording start/stop to the user.

Parameters
See Also
MediaActionSound

public final void setPreviewCallbackWithBuffer (Camera.PreviewCallback cb)

Added in API level 8

Installs a callback to be invoked for every preview frame, using buffers supplied withaddCallbackBuffer(byte[]), in addition to displaying them on the screen. The callback will be repeatedly called for as long as preview is active and buffers are available. Any other preview callbacks are overridden.

The purpose of this method is to improve preview efficiency and frame rate by allowing preview frame memory reuse. You must calladdCallbackBuffer(byte[])at some point -- before or after calling this method -- or no callbacks will received.

The buffer queue will be cleared if this method is called with a null callback,setPreviewCallback(Camera.PreviewCallback)is called, orsetOneShotPreviewCallback(Camera.PreviewCallback)is called.

If you are using the preview data to create video or still images, strongly consider usingMediaActionSoundto properly indicate image capture or recording start/stop to the user.

Parameters
See Also
addCallbackBuffer(byte[])MediaActionSound

public final void setPreviewDisplay (SurfaceHolder holder)

Added in API level 1

Sets theSurfaceto be used for live preview. Either a surface or surface texture is necessary for preview, and preview is necessary to take pictures. The same surface can be re-set without harm. Setting a preview surface will un-set any preview surface texture that was set viasetPreviewTexture(SurfaceTexture).

TheSurfaceHoldermust already contain a surface when this method is called. If you are usingSurfaceView, you will need to register aSurfaceHolder.CallbackwithaddCallback(SurfaceHolder.Callback)and wait forsurfaceCreated(SurfaceHolder)before calling setPreviewDisplay() or starting preview.

This method must be called beforestartPreview(). The one exception is that if the preview surface is not set (or set to null) before startPreview() is called, then this method may be called once with a non-null parameter to set the preview surface. (This allows camera setup and surface creation to happen in parallel, saving time.) The preview surface may not otherwise change while preview is running.

Parameters
Throws

public final void setPreviewTexture (SurfaceTexture surfaceTexture)

Added in API level 11

Sets theSurfaceTextureto be used for live preview. Either a surface or surface texture is necessary for preview, and preview is necessary to take pictures. The same surface texture can be re-set without harm. Setting a preview surface texture will un-set any preview surface that was set viasetPreviewDisplay(SurfaceHolder).

This method must be called beforestartPreview(). The one exception is that if the preview surface texture is not set (or set to null) before startPreview() is called, then this method may be called once with a non-null parameter to set the preview surface. (This allows camera setup and surface creation to happen in parallel, saving time.) The preview surface texture may not otherwise change while preview is running.

The timestamps provided bygetTimestamp()for a SurfaceTexture set as the preview texture have an unspecified zero point, and cannot be directly compared between different cameras or different instances of the same camera, or across multiple runs of the same program.

If you are using the preview data to create video or still images, strongly consider usingMediaActionSoundto properly indicate image capture or recording start/stop to the user.

Parameters
Throws
See Also
MediaActionSoundSurfaceTextureTextureView

public final void setZoomChangeListener (Camera.OnZoomChangeListener listener)

Added in API level 8

Registers a listener to be notified when the zoom value is updated by the camera driver during smooth zoom.

Parameters
See Also
startSmoothZoom(int)

public final void startFaceDetection ()

Added in API level 14

Starts the face detection. This should be called after preview is started. The camera will notifyCamera.FaceDetectionListenerof the detected faces in the preview frame. The detected faces may be the same as the previous ones. Applications should callstopFaceDetection()to stop the face detection. This method is supported ifgetMaxNumDetectedFaces()returns a number larger than 0. If the face detection has started, apps should not call this again.

When the face detection is running,setWhiteBalance(String),setFocusAreas(List), andsetMeteringAreas(List)have no effect. The camera uses the detected faces to do auto-white balance, auto exposure, and autofocus.

If the apps callautoFocus(AutoFocusCallback), the camera will stop sending face callbacks. The last face callback indicates the areas used to do autofocus. After focus completes, face detection will resume sending face callbacks. If the apps callcancelAutoFocus(), the face callbacks will also resume.

After callingtakePicture(Camera.ShutterCallback, Camera.PictureCallback, Camera.PictureCallback)orstopPreview(), and then resuming preview withstartPreview(), the apps should call this method again to resume face detection.

Throws
See Also
Camera.FaceDetectionListenerstopFaceDetection()getMaxNumDetectedFaces()

public final void startPreview ()

Added in API level 1

Starts capturing and drawing preview frames to the screen. Preview will not actually start until a surface is supplied withsetPreviewDisplay(SurfaceHolder)orsetPreviewTexture(SurfaceTexture).

IfsetPreviewCallback(Camera.PreviewCallback),setOneShotPreviewCallback(Camera.PreviewCallback), orsetPreviewCallbackWithBuffer(Camera.PreviewCallback)were called,onPreviewFrame(byte[], Camera)will be called when preview data becomes available.

public final void startSmoothZoom (int value)

Added in API level 8

Zooms to the requested value smoothly. The driver will notifyCamera.OnZoomChangeListenerof the zoom value and whether zoom is stopped at the time. For example, suppose the current zoom is 0 and startSmoothZoom is called with value 3. TheonZoomChange(int, boolean, Camera)method will be called three times with zoom values 1, 2, and 3. Applications can callstopSmoothZoom()to stop the zoom earlier. Applications should not call startSmoothZoom again or change the zoom value before zoom stops. If the supplied zoom value equals to the current zoom value, no zoom callback will be generated. This method is supported ifisSmoothZoomSupported()returns true.

Parameters
Throws
See Also
setZoomChangeListener(OnZoomChangeListener)

public final void stopFaceDetection ()

Added in API level 14

Stops the face detection.

See Also
startFaceDetection()

public final void stopPreview ()

Added in API level 1

Stops capturing and drawing preview frames to the surface, and resets the camera for a future call tostartPreview().

public final void stopSmoothZoom ()

Added in API level 8

Stops the smooth zoom. Applications should wait for theCamera.OnZoomChangeListenerto know when the zoom is actually stopped. This method is supported ifisSmoothZoomSupported()is true.

Throws

public final void takePicture (Camera.ShutterCallback shutter, Camera.PictureCallback raw, Camera.PictureCallback jpeg)

Added in API level 1

Equivalent to takePicture(shutter, raw, null, jpeg).

See Also
takePicture(ShutterCallback, PictureCallback, PictureCallback, PictureCallback)

public final void takePicture (Camera.ShutterCallback shutter, Camera.PictureCallback raw, Camera.PictureCallback postview, Camera.PictureCallback jpeg)

Added in API level 5

Triggers an asynchronous image capture. The camera service will initiate a series of callbacks to the application as the image capture progresses. The shutter callback occurs after the image is captured. This can be used to trigger a sound to let the user know that image has been captured. The raw callback occurs when the raw image data is available (NOTE: the data will be null if there is no raw image callback buffer available or the raw image callback buffer is not large enough to hold the raw image). The postview callback occurs when a scaled, fully processed postview image is available (NOTE: not all hardware supports this). The jpeg callback occurs when the compressed image is available. If the application does not need a particular callback, a null can be passed instead of a callback method.

This method is only valid when preview is active (afterstartPreview()). Preview will be stopped after the image is taken; callers must callstartPreview()again if they want to re-start preview or take more pictures. This should not be called betweenstart()andstop().

After calling this method, you must not callstartPreview()or take another picture until the JPEG callback has returned.

Parameters

public final void unlock ()

Added in API level 5

Unlocks the camera to allow another process to access it. Normally, the camera is locked to the process with an active Camera object untilrelease()is called. To allow rapid handoff between processes, you can call this method to release the camera temporarily for another process to use; once the other process is done you can callreconnect()to reclaim the camera.

This must be done before callingsetCamera(Camera). This cannot be called after recording starts.

If you are not recording video, you probably do not need this method.

Throws

Protected Methods

protected void finalize ()

Added in API level 1

Invoked when the garbage collector has detected that this instance is no longer reachable. The default implementation does nothing, but this method can be overridden to free resources.

Note that objects that overridefinalizeare significantly more expensive than objects that don't. Finalizers may be run a long time after the object is no longer reachable, depending on memory pressure, so it's a bad idea to rely on them for cleanup. Note also that finalizers are run on a single VM-wide finalizer thread, so doing blocking work in a finalizer is a bad idea. A finalizer is usually only necessary for a class that has a native peer and needs to call a native method to destroy that peer. Even then, it's better to provide an explicitclosemethod (and implementCloseable), and insist that callers manually dispose of instances. This works well for something like files, but less well for something like aBigIntegerwhere typical calling code would have to deal with lots of temporaries. Unfortunately, code that creates lots of temporaries is the worst kind of code from the point of view of the single finalizer thread.

If youmustuse finalizers, consider at least providing your ownReferenceQueueand having your own thread process that queue.

Unlike constructors, finalizers are not automatically chained. You are responsible for callingsuper.finalize()yourself.

Uncaught exceptions thrown by finalizers are ignored and do not terminate the finalizer thread. SeeEffective JavaItem 7, "Avoid finalizers" for more.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。