• Stars
    star
    605
  • Rank 74,072 (Top 2 %)
  • Language
    C#
  • License
    MIT License
  • Created over 6 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A native Unity plugin to take pictures/record videos with device camera on Android & iOS

Unity Native Camera Plugin

Available on Asset Store: https://assetstore.unity.com/packages/tools/integration/native-camera-for-android-ios-117802

Forum Thread: https://forum.unity.com/threads/native-camera-for-android-ios-open-source.529560/

Discord: https://discord.gg/UJJt549AaV

GitHub Sponsors β˜•

This plugin helps you take pictures/record videos natively with your device's camera on Android and iOS. It has built-in support for runtime permissions, as well.

INSTALLATION

There are 5 ways to install this plugin:

  • import NativeCamera.unitypackage via Assets-Import Package
  • clone/download this repository and move the Plugins folder to your Unity project's Assets folder
  • import it from Asset Store
  • (via Package Manager) add the following line to Packages/manifest.json:
    • "com.yasirkula.nativecamera": "https://github.com/yasirkula/UnityNativeCamera.git",
  • (via OpenUPM) after installing openupm-cli, run the following command:
    • openupm add com.yasirkula.nativecamera

Android Setup

NativeCamera no longer requires any manual setup on Android. For reference, the legacy manual setup documentation is available at: https://github.com/yasirkula/UnityNativeCamera/wiki/Manual-Setup-for-Android

iOS Setup

There are two ways to set up the plugin on iOS:

FAQ

  • Audio is muted on iOS after calling NativeCamera.RecordVideo

Please see: https://forum.unity.com/threads/native-camera-for-android-ios-open-source.529560/page-9#post-8207157

  • Can't use the camera, it says "java.lang.ClassNotFoundException: com.yasirkula.unity.NativeCamera" in Logcat

If you are sure that your plugin is up-to-date, then enable Custom Proguard File option from Player Settings and add the following line to that file: -keep class com.yasirkula.unity.* { *; }

  • NativeCamera functions return Permission.Denied even though I've granted the permission"

Declare WRITE_EXTERNAL_STORAGE permission manually in your Plugins/Android/AndroidManifest.xml file with the tools:node="replace" attribute as follows: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:node="replace"/> (you'll need to add the xmlns:tools="http://schemas.android.com/tools" attribute to the <manifest ...> element).

HOW TO

A. Accessing Camera

NativeCamera.TakePicture( CameraCallback callback, int maxSize = -1, PreferredCamera preferredCamera = PreferredCamera.Default ): opens the camera and waits for user to take a picture.

  • This operation is asynchronous! After user takes a picture or cancels the operation, the callback is called (on main thread). CameraCallback takes a string parameter which stores the path of the captured image, or null if the operation is canceled
  • maxSize determines the maximum size of the returned image in pixels on iOS. A larger image will be down-scaled for better performance. If untouched, its value will be set to SystemInfo.maxTextureSize. Has no effect on Android
  • saveAsJPEG determines whether the image is saved as JPEG or PNG. Has no effect on Android
  • preferredCamera determines whether the rear camera or the front camera should be opened by default

NativeCamera.RecordVideo( CameraCallback callback, Quality quality = Quality.Default, int maxDuration = 0, long maxSizeBytes = 0L, PreferredCamera preferredCamera = PreferredCamera.Default ): opens the camera and waits for user to record a video.

  • quality determines the quality of the recorded video. Available values are: Default, Low, Medium, High
  • maxDuration determines the maximum duration, in seconds, for the recorded video. If untouched, there will be no limit. Please note that the functionality of this parameter depends on whether the device vendor has added this capability to the camera or not. So, this parameter may not have any effect on some devices
  • maxSizeBytes determines the maximum size, in bytes, for the recorded video. If untouched, there will be no limit. This parameter has no effect on iOS. Please note that the functionality of this parameter depends on whether the device vendor has added this capability to the camera or not. So, this parameter may not have any effect on some devices

NativeCamera.DeviceHasCamera(): returns false if the device doesn't have a camera. In this case, TakePicture and RecordVideo functions will not execute.

NativeCamera.IsCameraBusy(): returns true if the camera is currently open. In that case, another TakePicture or RecordVideo request will simply be ignored.

Note that TakePicture and RecordVideo functions return a NativeCamera.Permission value. More details available below.

B. Runtime Permissions

Beginning with 6.0 Marshmallow, Android apps must request runtime permissions before accessing certain services, similar to iOS. There are two functions to handle permissions with this plugin:

NativeCamera.Permission NativeCamera.CheckPermission( bool isPicturePermission ): checks whether the app has access to camera or not.

  • isPicturePermission determines whether we're checking permission to take a picture or record a video. Has no effect on iOS

NativeCamera.Permission is an enum that can take 3 values:

  • Granted: we have the permission to access the camera
  • ShouldAsk: we don't have permission yet, but we can ask the user for permission via RequestPermission function (see below). On Android, as long as the user doesn't select "Don't ask again" while denying the permission, ShouldAsk is returned
  • Denied: we don't have permission and we can't ask the user for permission. In this case, user has to give the permission from Settings. This happens when user denies the permission on iOS (can't request permission again on iOS), when user selects "Don't ask again" while denying the permission on Android or when user is not allowed to give that permission (parental controls etc.)

NativeCamera.Permission NativeCamera.RequestPermission( bool isPicturePermission ): requests permission to access the camera from the user and returns the result. It is recommended to show a brief explanation before asking the permission so that user understands why the permission is needed and doesn't click Deny or worse, "Don't ask again". Note that TakePicture and RecordVideo functions call RequestPermission internally and execute only if the permission is granted (the result of RequestPermission is then returned).

NativeCamera.OpenSettings(): opens the settings for this app, from where the user can manually grant permission in case current permission state is Permission.Denied (Android requires Storage and, if declared in AndroidManifest, Camera permissions; iOS requires Camera permission).

bool NativeCamera.CanOpenSettings(): on iOS versions prior to 8.0, opening settings from within the app is not possible and in this case, this function returns false. Otherwise, it returns true.

C. Utility Functions

NativeCamera.ImageProperties NativeCamera.GetImageProperties( string imagePath ): returns an ImageProperties instance that holds the width, height, mime type and EXIF orientation information of an image file without creating a Texture2D object. Mime type will be null, if it can't be determined.

NativeCamera.VideoProperties NativeCamera.GetVideoProperties( string videoPath ): returns a VideoProperties instance that holds the width, height, duration (in milliseconds) and rotation information of a video file. To play a video in correct orientation, you should rotate it by rotation degrees clockwise. For a 90-degree or 270-degree rotated video, values of width and height should be swapped to get the display size of the video.

Texture2D NativeCamera.LoadImageAtPath( string imagePath, int maxSize = -1, bool markTextureNonReadable = true, bool generateMipmaps = true, bool linearColorSpace = false ): creates a Texture2D from the specified image file in correct orientation and returns it. Returns null, if something goes wrong.

  • maxSize determines the maximum size of the returned Texture2D in pixels. Larger textures will be down-scaled. If untouched, its value will be set to SystemInfo.maxTextureSize. It is recommended to set a proper maxSize for better performance
  • markTextureNonReadable marks the generated texture as non-readable for better memory usage. If you plan to modify the texture later (e.g. GetPixels/SetPixels), set its value to false
  • generateMipmaps determines whether texture should have mipmaps or not
  • linearColorSpace determines whether texture should be in linear color space or sRGB color space

async Task<Texture2D> NativeCamera.LoadImageAtPathAsync( string imagePath, int maxSize = -1, bool markTextureNonReadable = true, bool generateMipmaps = true, bool linearColorSpace = false ): asynchronous variant of LoadImageAtPath (requires Unity 2018.4 or later). Works best when linearColorSpace is false. It's also slightly faster when generateMipmaps is false. Note that it isn't possible to load multiple images simultaneously using this function.

Texture2D NativeCamera.GetVideoThumbnail( string videoPath, int maxSize = -1, double captureTimeInSeconds = -1.0, bool markTextureNonReadable = true, bool generateMipmaps = true, bool linearColorSpace = false ): creates a Texture2D thumbnail from a video file and returns it. Returns null, if something goes wrong.

  • maxSize determines the maximum size of the returned Texture2D in pixels. Larger thumbnails will be down-scaled. If untouched, its value will be set to SystemInfo.maxTextureSize. It is recommended to set a proper maxSize for better performance
  • captureTimeInSeconds determines the frame of the video that the thumbnail is captured from. If untouched, OS will decide this value
  • markTextureNonReadable (see LoadImageAtPath)

async Task<Texture2D> NativeCamera.GetVideoThumbnailAsync( string videoPath, int maxSize = -1, double captureTimeInSeconds = -1.0, bool markTextureNonReadable = true, bool generateMipmaps = true, bool linearColorSpace = false ): asynchronous variant of GetVideoThumbnail (requires Unity 2018.4 or later). Works best when linearColorSpace is false. It's also slightly faster when generateMipmaps is false. Note that it isn't possible to generate multiple video thumbnails simultaneously using this function.

EXAMPLE CODE

The following code has two functions:

  • if you click left half of the screen, the camera is opened and after a picture is taken, it is displayed on a temporary quad that is placed in front of the camera
  • if you click right half of the screen, the camera is opened and after a video is recorded, it is played using the Handheld.PlayFullScreenMovie function
void Update()
{
	if( Input.GetMouseButtonDown( 0 ) )
	{
		// Don't attempt to use the camera if it is already open
		if( NativeCamera.IsCameraBusy() )
			return;
			
		if( Input.mousePosition.x < Screen.width / 2 )
		{
			// Take a picture with the camera
			// If the captured image's width and/or height is greater than 512px, down-scale it
			TakePicture( 512 );
		}
		else
		{
			// Record a video with the camera
			RecordVideo();
		}
	}
}

private void TakePicture( int maxSize )
{
	NativeCamera.Permission permission = NativeCamera.TakePicture( ( path ) =>
	{
		Debug.Log( "Image path: " + path );
		if( path != null )
		{
			// Create a Texture2D from the captured image
			Texture2D texture = NativeCamera.LoadImageAtPath( path, maxSize );
			if( texture == null )
			{
				Debug.Log( "Couldn't load texture from " + path );
				return;
			}

			// Assign texture to a temporary quad and destroy it after 5 seconds
			GameObject quad = GameObject.CreatePrimitive( PrimitiveType.Quad );
			quad.transform.position = Camera.main.transform.position + Camera.main.transform.forward * 2.5f;
			quad.transform.forward = Camera.main.transform.forward;
			quad.transform.localScale = new Vector3( 1f, texture.height / (float) texture.width, 1f );
			
			Material material = quad.GetComponent<Renderer>().material;
			if( !material.shader.isSupported ) // happens when Standard shader is not included in the build
				material.shader = Shader.Find( "Legacy Shaders/Diffuse" );

			material.mainTexture = texture;
				
			Destroy( quad, 5f );

			// If a procedural texture is not destroyed manually, 
			// it will only be freed after a scene change
			Destroy( texture, 5f );
		}
	}, maxSize );

	Debug.Log( "Permission result: " + permission );
}

private void RecordVideo()
{
	NativeCamera.Permission permission = NativeCamera.RecordVideo( ( path ) =>
	{
		Debug.Log( "Video path: " + path );
		if( path != null )
		{
			// Play the recorded video
			Handheld.PlayFullScreenMovie( "file://" + path );
		}
	} );

	Debug.Log( "Permission result: " + permission );
}

More Repositories

1

UnityIngameDebugConsole

A uGUI based console to see debug messages and execute commands during gameplay in Unity
C#
2,117
star
2

UnityAssetUsageDetector

Find usages of the selected asset(s) and/or Object(s) in your Unity project, i.e. list the objects that refer to them
C#
1,693
star
3

UnityRuntimeInspector

Runtime Inspector and Hierarchy solution for Unity for debugging and runtime editing purposes
C#
1,676
star
4

UnityNativeGallery

A native Unity plugin to interact with Gallery/Photos on Android & iOS (save and/or load images/videos)
Objective-C++
1,396
star
5

UnityBezierSolution

A bezier spline solution for Unity 3D with some utility functions (like travelling the spline with constant speed/time)
C#
1,153
star
6

UnityNativeShare

A Unity plugin to natively share files (images, videos, documents, etc.) and/or plain text on Android & iOS
C#
905
star
7

UnitySimpleFileBrowser

A uGUI based runtime file browser for Unity 3D (draggable and resizable)
C#
844
star
8

UnityDynamicPanels

Draggable, resizable, dockable and stackable UI panel solution for Unity 3D
C#
735
star
9

UnityRuntimePreviewGenerator

Generate preview textures (thumbnails) for your GameObject's or materials on the fly in Unity
C#
304
star
10

UnityNativeFilePicker

A native Unity plugin to import/export files from/to various document providers on Android & iOS
C#
277
star
11

UnityInspectPlus

Speeding up your Inspector workflow in Unity 3D
C#
254
star
12

UnityImageCropper

A uGUI based image cropping solution for Unity 3D
C#
207
star
13

UnityAndroidRuntimePermissions

A native Unity plugin to handle runtime permissions on Android M+
C#
194
star
14

UnityRuntimeSceneGizmo

Interactable runtime scene gizmo for uGUI
C#
175
star
15

UnitySimplePatchTool

Unity port of SimplePatchTool library to add patching support to standalone Unity applications
C#
163
star
16

UnitySimpleInput

An improvement over Unity's legacy Input system that allows you to use custom input providers like on-screen joysticks, UI buttons and d-pads
C#
157
star
17

UnityAdjustPivot

Adjust pivot point of an object in Unity without creating an empty parent object
C#
149
star
18

Unity360ScreenshotCapture

A simple script to capture 360Β° screenshots in-game with Unity
C#
142
star
19

SimplePatchTool

C# library for patching standalone applications with binary diff and self patching support
C#
132
star
20

UnityTextToTextMeshProUpgradeTool

Upgrade Text, InputField, Dropdown and TextMesh objects to their TextMesh Pro variants in Unity
C#
113
star
21

DownloadLinkGeneratorForGoogleDrive

Create list of files and their download links in a Google Driveβ„’ folder
HTML
109
star
22

UnityIonicIntegration

A guide to integrating Unity 3D content into an Ionic app and sending messages between them (for Android & iOS)(tested with Vuforia plugin)
Objective-C++
104
star
23

UnityMobileLocalizedAppTitle

Localize your Unity app's name and/or icon on Android & iOS
C#
102
star
24

UnityGridFramework

Open source Grid Framework for creating grid-based levels easily in Unity 3D
C#
94
star
25

UnitySimpleGDPRConsent

A Unity plugin to present GDPR consent dialogs to the users
C#
93
star
26

UnityTextureOps

A basic image processing plugin for Unity
C#
87
star
27

UnityChoiceOfGamesSaveManager

Save manager for 'Choice of Games' on Steam - Created with Unity 3D
C#
76
star
28

UnitySpeechToText

A native Unity plugin to convert speech to text on Android & iOS
C#
70
star
29

UnityRuntimeTexture

An abstraction layer on top of Texture2D.LoadImage to create Texture2D objects at runtime from raw PNG/JPEG data in Unity
C#
62
star
30

UnityDashedSpriteShape

Creating dashed (dotted) 2D Sprite Shapes in Unity
ShaderLab
62
star
31

UnityMobileRemoteControl

Control your Windows device from your phone
C#
59
star
32

UnityEditorGoogleDriveIntegration

Access your Google Driveβ„’ files from within Unity editor
C#
48
star
33

UnityHexicGame

Hexic puzzle game made with Unity 3D
ShaderLab
36
star
34

UnityGenericPool

A simple generic pooling script for Unity3D with a helper class
C#
36
star
35

UnitySpinningLoadingBars

3 different spinning loading bar prefabs for Unity's UI system
28
star
36

UnityFlatColorPalettes

A number of flat color palettes for Unity 3D
26
star
37

UnityEveryplaySaveToLocal

A helper script to save captured Everyplay videos to local file system on Android & iOS
Objective-C++
15
star
38

UnityOrderedUpdate

Receive Update callback(s) from anywhere and in any order in Unity!
C#
15
star
39

UnityAndroidStreamingAssets

A helper script to extract StreamingAssets to local file system on Unity Android
C#
10
star
40

DownloadLinkGeneratorForDropbox

Create list of files and their download links in a Dropbox folder
HTML
6
star
41

SecondHand

Global Game Jam entry
C#
5
star
42

GeometricSketchpadProject

Bilkent CS102 Course Project
Java
4
star
43

GreenHellMods

A number of mods created via ModAPI for Green Hell game
C#
4
star
44

.github

Default GitHub community health files for all my repositories
2
star
45

BubblesProject

Bilkent CS319 Course Project
Java
2
star