Cara Membuat Aplikasi Kamera Bagian Ketiga - Flash Light - Coding Rakitan
Pada postingan kali ini kita akan melanjutkan postingan sebelumnya Cara Membuat Aplikasi Kamera Bagian Kedua - Capture Image. Postingan sebelumnya kita...
Langkah kedua :
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<FrameLayout
android:id="@+id/fr_kamera"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black">
</FrameLayout>
<ImageView
android:id="@+id/img"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="bottom|center_horizontal"
android:layout_marginBottom="30dp"
android:adjustViewBounds="true"
android:onClick="onClick"
android:tint="@android:color/white"
app:srcCompat="@drawable/camera"
tools:ignore="VectorDrawableCompat" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:orientation="vertical"
android:padding="5dp">
<ImageView
android:id="@+id/flash"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:onClick="onClick"
android:tag="off"
android:tint="@android:color/white"
app:srcCompat="@drawable/flash_off"
tools:ignore="VectorDrawableCompat" />
</LinearLayout>
<LinearLayout
android:id="@+id/ly"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black"
android:orientation="vertical"
android:visibility="gone">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/tampil"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="false"
app:srcCompat="@drawable/ic_launcher_background"
tools:ignore="VectorDrawableCompat" />
<ImageView
android:id="@+id/hapus"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="bottom"
android:layout_margin="20dp"
android:adjustViewBounds="true"
android:onClick="onClick"
android:tint="@android:color/white"
app:srcCompat="@drawable/delete"
tools:ignore="VectorDrawableCompat" />
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:padding="10dp"
android:text="codingrakitan.blogspot.com"
android:textColor="@android:color/white"
android:textSize="12sp" />
</FrameLayout>
</LinearLayout>
</FrameLayout>
Pada class di atas kita menambahkan 3 method yang berfungsi untuk mengatur blitz yaitu flashAktif(), flashAuto(), dan flashMati(). Kode yang berfungsi untuk menyalakan flash light adalah "pr.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);" dimana kode ini menginstruksikan untuk membuat Flash Mode Torch ketika dilakukan tangkapan kamera.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private FrameLayout fr_kamera;
private SurfaceView sv;
private SurfaceHolder sh;
private Camera cm;
private ImageView tampil;
private LinearLayout ly;
private int HOME = 1;
int flash = 1;
String aksi_flash = "mati";
Camera.Parameters pr;
ImageView iv_flash;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
fr_kamera = findViewById(R.id.fr_kamera);
tampil = findViewById(R.id.tampil);
iv_flash = findViewById(R.id.flash);
ly = findViewById(R.id.ly);
kameraAktif();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (HOME==0){
kembaliCamera();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
public void kembaliCamera(){
ly.setVisibility(View.GONE);
HOME=1;
if (aksi_flash=="hidup"){
flashAktif();
}
cm.startPreview();
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.hapus:
kembaliCamera();
break;
case R.id.img:
ambilGambar();
break;
case R.id.flash:
flash++;
if (flash==1){
iv_flash.setImageResource(R.drawable.flash_off);
flashMati();
aksi_flash = "mati";
}else
if (flash==2){
iv_flash.setImageResource(R.drawable.flash_on);
flashAktif();
aksi_flash = "hidup";
}else
if (flash==3){
iv_flash.setImageResource(R.drawable.flash_auto);
flashAuto();
aksi_flash = "auto";
flash = 0;
}
break;
}
}
private void flashAktif() {
pr = cm.getParameters();
pr.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
cm.setParameters(pr);
cm.startPreview();
}
private void flashAuto() {
pr = cm.getParameters();
pr.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
cm.setParameters(pr);
cm.startPreview();
}
private void flashMati() {
pr = cm.getParameters();
pr.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
cm.setParameters(pr);
cm.startPreview();
}
private void kameraAktif() {
sv = new SurfaceView(this);
sh = sv.getHolder();
sh.addCallback(new SurfaceHolderCallback());
fr_kamera.addView(sv);
}
private void ambilGambar() {
if (aksi_flash=="auto"){
flashAuto();
}
cm.takePicture(null, null, jpegCallback);
HOME = 0;
}
Camera.PictureCallback jpegCallback = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap rotateBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight()
, matrix, true);
tampil.setImageBitmap(rotateBitmap);
ly.setVisibility(View.VISIBLE);
}
};
private class SurfaceHolderCallback implements SurfaceHolder.Callback {
@Override
public void surfaceCreated(SurfaceHolder holder) {
cm = Camera.open();
pr = cm.getParameters();
List<Camera.Size> ss = pr.getSupportedPreviewSizes();
Camera.Size pictSize = ss.get(0);
pr.setPictureSize(pictSize.width, pictSize.height);
cm.setParameters(pr);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
try {
cm.setDisplayOrientation(90);
cm.setPreviewDisplay(sv.getHolder());
Camera.Parameters parameters = cm.getParameters();
List<Camera.Size> previewSize = cm.getParameters().getSupportedPreviewSizes();
Camera.Size pre = previewSize.get(0);
parameters.setPreviewSize(pre.width, pre.height);
ViewGroup.LayoutParams lp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
sv.setLayoutParams(lp);
cm.setParameters(parameters);
cm.startPreview();
}catch (Exception e){}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
cm.stopPreview();
cm.release();
}
}
}
Karena dalam hal bertransaksi ke halam web diperlukan akses Internet maka, kita perlu menuliskan kode di bawah kedalam AndroidManifest.xml
dependencies{
...
implementation 'eu.the4thfloor.volley:com.android.volley:2015.05.28'
...
}
Setiap transaksi yang dilakukan baik itu pengiriman data berupa GET atau POST nantinya akan memberikan respon berupa String.
<uses-permission android:name="android.permission.INTERNET"/>
String url = "http://codingrakitan.blogspot.com/";
RequestQueue rq = Volley.newRequestQueue(this);
StringRequest sr = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("respon", "hasil : "+response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("respon", "error : "+error);
}
});
rq.add(sr);
Pada kode di atas di buat untuk mengirimkan data berupa post dengan name "username" dan "password" dengan masing-masing field, valuenya adalah "admin".
String url = "http://codingrakitan.blogspot.com/";
RequestQueue rq = Volley.newRequestQueue(this);
StringRequest sr = new StringRequest(Request.Method.POST, Constants.URL_INSERT, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("respon", "hasil : "+response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("error", "isi = "+error.getMessage());
}
}){
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("username", "admin");
params.put("password", "admin");
return params;
}
};
rq.add(sr);
Langkah 3 : Masukkan gambar percobaan kedalam directory drawable dengan nama gambar.jpg (seuai keinginan anda). Berikut adalah contoh gambar yang akan di tampilkan
dependencies {
...
implementation 'com.github.bumptech.glide:glide:4.2.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.2.0'
}
Langkah 5 : Edit class MainActivity seperti berikut.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/darker_gray"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:id="@+id/gambar"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginTop="20dp" />
</LinearLayout>
</RelativeLayout>
Penjelasan :
public class MainActivity extends AppCompatActivity {
private ImageView gambar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gambar = findViewById(R.id.gambar);
Glide.with(this)
.load(R.drawable.gambar)
.apply(RequestOptions.circleCropTransform())
.into(gambar);
}
}
Kode tersebut menginstruksikan gambar yang terdapada di "R.drawable.gambar" untuk di tampilkan kedalam image view dengan bentuk circle dengan menggunakan method "circleCropTransform()". Selain gambar dari directori anda juga bisa menggunakan gambar online dengan cara menuliskan ".load(URL_GAMBAR)", contohnya :
Glide.with(this)
.load(R.drawable.gambar)
.apply(RequestOptions.circleCropTransform())
.into(gambar);
Glide.with(this)
.load("http://codingrakitan.blogspot.com/")
.apply(RequestOptions.circleCropTransform())
.into(gambar);
Langkah 3 : Edit activity_main.xml dengan kode seperti berikut.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="codingrakitan.blogspot.com.aplikasikamera">
<uses-permission android:name="android.permission.CAMERA"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Langkah 4 : Edit class MainActivity dengan kode seperti berikut.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<FrameLayout
android:id="@+id/fr_kamera"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black">
</FrameLayout>
<ImageView
android:id="@+id/img"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="bottom|center_horizontal"
android:layout_marginBottom="30dp"
android:adjustViewBounds="true"
android:onClick="onClick"
android:tint="@android:color/white"
app:srcCompat="@drawable/camera"
tools:ignore="VectorDrawableCompat" />
<LinearLayout
android:id="@+id/ly"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black"
android:orientation="vertical"
android:visibility="gone">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/tampil"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="false"
app:srcCompat="@drawable/ic_launcher_background"
tools:ignore="VectorDrawableCompat" />
<ImageView
android:id="@+id/hapus"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="bottom"
android:layout_margin="20dp"
android:adjustViewBounds="true"
android:onClick="onClick"
android:tint="@android:color/white"
app:srcCompat="@drawable/delete"
tools:ignore="VectorDrawableCompat" />
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:padding="10dp"
android:text="codingrakitan.blogspot.com"
android:textColor="@android:color/white"
android:textSize="12sp" />
</FrameLayout>
</LinearLayout>
</FrameLayout>
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private FrameLayout fr_kamera;
private SurfaceView sv;
private SurfaceHolder sh;
private Camera cm;
private ImageView tampil;
private LinearLayout ly;
private int HOME = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
fr_kamera = findViewById(R.id.fr_kamera);
tampil = findViewById(R.id.tampil);
ly = findViewById(R.id.ly);
kameraAktif();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (HOME==0){
ly.setVisibility(View.GONE);
HOME=1;
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.hapus:
ly.setVisibility(View.GONE);
break;
case R.id.img:
ambilGambar();
break;
}
}
private void kameraAktif() {
sv = new SurfaceView(this);
sh = sv.getHolder();
sh.addCallback(new SurfaceHolderCallback());
fr_kamera.addView(sv);
}
private void ambilGambar() {
cm.takePicture(null, null, jpegCallback);
HOME = 0;
}
Camera.PictureCallback jpegCallback = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap rotateBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight()
, matrix, true);
tampil.setImageBitmap(rotateBitmap);
ly.setVisibility(View.VISIBLE);
cm.startPreview();
}
};
private class SurfaceHolderCallback implements SurfaceHolder.Callback {
@Override
public void surfaceCreated(SurfaceHolder holder) {
cm = Camera.open();
Camera.Parameters parameters = cm.getParameters();
List<Camera.Size> ss = parameters.getSupportedPreviewSizes();
Camera.Size pictSize = ss.get(0);
parameters.setPictureSize(pictSize.width, pictSize.height);
cm.setParameters(parameters);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
try {
cm.setDisplayOrientation(90);
cm.setPreviewDisplay(sv.getHolder());
Camera.Parameters parameters = cm.getParameters();
List<Camera.Size> previewSize = cm.getParameters().getSupportedPreviewSizes();
Camera.Size pre = previewSize.get(0);
parameters.setPreviewSize(pre.width, pre.height);
ViewGroup.LayoutParams lp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
sv.setLayoutParams(lp);
cm.setParameters(parameters);
cm.startPreview();
}catch (Exception e){}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
cm.stopPreview();
cm.release();
}
}
}
...
<uses-permission android:name="android.permission.CAMERA"/>
...
Langkah 2 : Edit activity_main.xml seperti berikut. Langkah 3 : Edit class MainActivity seperti berikut.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/fr_kamera"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" />
Jika camera anda orientasinya tidak sesuai dengan yang diharapkan silahkan rubah pada bagian cm.setDisplayOrientation(90); anda bisa menggantinya misalnya 0, 90, 180. Pada bagian tersebut jika tidak sesuai bisa jadi hp anda tegakkan ke atas, tetapi gambar yang tampil malah memanjang ke samping.
public class MainActivity extends AppCompatActivity {
private FrameLayout fr_kamera;
private SurfaceView sv;
private SurfaceHolder sh;
private Camera cm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fr_kamera = findViewById(R.id.fr_kamera);
sv = new SurfaceView(this);
sh = sv.getHolder();
sh.addCallback(new SurfaceHolderCallback());
fr_kamera.addView(sv);
}
private class SurfaceHolderCallback implements SurfaceHolder.Callback {
@Override
public void surfaceCreated(SurfaceHolder holder) {
cm = Camera.open();
Camera.Parameters parameters = cm.getParameters();
List<Camera.Size> ss = parameters.getSupportedPreviewSizes();
Camera.Size pictSize = ss.get(0);
parameters.setPictureSize(pictSize.width, pictSize.height);
cm.setParameters(parameters);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
try {
cm.setDisplayOrientation(90);
cm.setPreviewDisplay(sv.getHolder());
Camera.Parameters parameters = cm.getParameters();
List<Camera.Size> previewSize = cm.getParameters().getSupportedPreviewSizes();
Camera.Size pre = previewSize.get(0);
parameters.setPreviewSize(pre.width, pre.height);
ViewGroup.LayoutParams lp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
sv.setLayoutParams(lp);
cm.setParameters(parameters);
cm.startPreview();
}catch (Exception e){}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
cm.stopPreview();
cm.release();
}
}
}