Pertama
Buatlah project baru di android studio kalian... Beri nama project sesuai keinginan kalian... Sebagai contoh saya memberi nama project saya dengan nama "Android Kamera".....
Kedua
Setelah dibuat, tunggu dulu sampa proses gradle project selesai, setelah gradle selesai... Setelah itu, buka AndroidManifests.xml nya, tambahkan fitur untuk kamera nya dan juga tambahkan permission nya
<!-- Accessing camera hardware -->
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Ketiga
Lalu kita lanjut layouting nya di layout activity_main.xml... Jangan lupa, layout nya kita ganti dengan LinearLayout dan orientation vertical.... Dant tambahkan komponen-komponen berkut ini... Kita menambhkan 2 fitur... yaitu untuk camera untuk hasil foto dan juga untuk vidio view....
<LinearLayout
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<!-- Capture picture button -->
<Button
android:id="@+id/btnCapturePicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ambil Foto"
android:layout_marginBottom="10dp"/>
<!-- Record video button -->
<Button
android:id="@+id/btnRecordVideo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rekam Vidio" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Preview"
android:padding="10dp"
android:textSize="15dp"/>
<!-- To display picture taken -->
<ImageView
android:id="@+id/imgPreview"
android:layout_width="match_parent"
android:layout_height="100dp"
android:visibility="gone" />
<!-- To preview video recorded -->
<VideoView
android:id="@+id/videoPreview"
android:layout_width="wrap_content"
android:layout_height="400dp"
android:visibility="gone" />
</LinearLayout>
Inilah hasil penambahan widget pada activity_main.xml
Keempat
A. Setelah itu kita buka MainActivity.java.... Lalu copy code ini di atas methode onCreate...
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
private Uri fileUri; // file url to store image/video
// widget-widget layout activity_main.xml
private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapturePicture, btnRecordVideo;
B. Selanjutnya adalah kenalkan widget-widget yang ada di layout activty_main.xml.....
imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
C. Setelah di kenalkan widget nya, langkah selanjutnya adalah berikan button nya action untuk membuka kamera nya
/**
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
/**
* Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// record video
recordVideo();
}
});
D. Langkah selanjutnya adalah, kita cek dulu apakah kamera tersedia di android nya atau tidak, dan kita periksa apakan si android ini memiliki kamera atau tidak
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
/**
* Checking device has camera hardware or not
*/
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
E. Selanjutnya adalah kode untuk menangkap gambar kamera akan memanfaatkan pengambilan gambar kamera terbaik dan Di sini kita menyimpan file url karena akan null setelah kembali dari aplikasi kamera
/**
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
F. Selanjutnya adalah Bikin method untuk recording vidio...
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
G. Stelah membuat method recordVidio(), langkah selanjut nya adalah menerima method hasil aktivitas akan dipanggil setelah menutup kamera... Berikut adalah code nya
* Receiving activity result method will be called after closing the camera
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
H. Selanjutnya adalah, Kita tampilkan gambar ke dalam image view... Berikut adalah kodingan nya
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
I. Setalah kita menampilkan foto ke image view, selanjutnya adalah kita tinjau rekaman vidio yang di rekam
/**
* Previewing recorded video
*/
private void previewVideo() {
try {
// hide image preview
imgPreview.setVisibility(View.GONE);
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(fileUri.getPath());
// start playing
videoPreview.start();
} catch (Exception e) {
e.printStackTrace();
}
}
J. Selanjutnya adalah, helper method, metode berikut di kelas aktivitas utama Anda. Metode ini membantu dalam membuat dan mendapatkan file dari kartu SD.
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".png");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
Berikut ini adalah kode lengkap pada MainActivity.java.....
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.VideoView;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
private Uri fileUri; // file url to store image/video
private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapturePicture, btnRecordVideo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
/**
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
/**
* Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// record video
recordVideo();
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
/**
* Checking device has camera hardware or not
*/
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/**
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Recording video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
* Receiving activity result method will be called after closing the camera
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* Previewing recorded video
*/
private void previewVideo() {
try {
// hide image preview
imgPreview.setVisibility(View.GONE);
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(fileUri.getPath());
// start playing
videoPreview.start();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".png");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
Ketika semua kode sudah komplit... Maka yang terakhir adalah tinggal run aplikasinya...
Berikut adalah hasil running aplikasinya
a. hasil menambahkan foto
b. Hasil menambahkan vidio....
No comments:
Post a Comment