Aplikasi kamera android :
Sekarang kita akan membuat aplikasi kecil android yang
mempunyai Fungsi :
1.
Dapat mengambil foto dengan kamera
2.
Memperkecil Ukuran foto
3.
Memberi watermark
4.
Menyimpan foto di folder lain
Buatlah Projek baru di android studio : File >New >
New Project
Aplication Name : My Camera
Company Domain : com.www.adyulita.blogspot
Buka file AndroidManifest.xml dan tambahkan koding di
bawah ini :
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.CAMERA" />
Untuk dapat mengakses fitur kamera, menyimpan dan
memindahkan foto ke folder lain di dalam sdcard android.
Buka File Activity_main.xml dan copy koding dibawah ini :
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="blogspot.adyulita.www.com.mycamera.MainActivity"> <LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="vertical" android:layout_centerHorizontal="true" android:weightSum="3" android:layout_alignParentTop="true"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0.4" android:layout_centerHorizontal="true" android:textSize="20dp" android:layout_marginTop="30dp" android:text="Hello Guys!" /> <Button android:id="@+id/buttonCamera" style="?android:attr/buttonStyleSmall" android:layout_width="150dp" android:layout_height="80dp" android:layout_weight="1" android:layout_centerHorizontal="true" android:background="@drawable/camera" /> <ImageView android:id="@+id/imgView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_weight="1" android:src="@drawable/na" /> </LinearLayout> </RelativeLayout>
Tampilan seperti yang di bawah ini
Buka file MainActivity.java dan copy koding di bawah ini :
package blogspot.adyulita.www.com.mycamera; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Calendar; public class MainActivity extends AppCompatActivity { Button btnCamera; ImageView img; private static final int PICK_Camera_IMAGE = 1; Uri imageUri,imageUri1,imageUri2; File dFile; private Bitmap bitmap; String filePath = "NONE"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Definisi komponen yang terdapat di tampilan interface btnCamera = (Button) findViewById(R.id.buttonCamera); // Definisi tombol kamera img = (ImageView)findViewById(R.id.imgView); // Definisi Tampilan gambar btnCamera.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { //Pemberian nama pada file photo String fileName = String.valueOf(System.currentTimeMillis() + ".jpg"); //Folder photo tersimpan di folder DCIM File dir = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); File filetp1 = new File(dir, fileName); imageUri = Uri.fromFile(filetp1); // Untuk membuka fitur kamera Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent, PICK_Camera_IMAGE); } }); } public void onActivityResult(int requestCode, int resultCode, Intent data) { Uri selectedImageUri = null; if (requestCode == PICK_Camera_IMAGE) { if (resultCode == RESULT_OK) { selectedImageUri = imageUri; String filemanagerstring = selectedImageUri.getPath(); File files = new File(filemanagerstring); String namafile = files.getName(); try { //Untuk memindahkan Photo dari DCIM ke Folder My Camera String dest = "/sdcard/My Camera/" + namafile; String src1 = "/sdcard/DCIM/" + namafile; if (!Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { // untuk menghandle jika tidak ada sd card di smartphone } else { dFile = new File(Environment.getExternalStorageDirectory() + File.separator + "My Camera"); if (!dFile.exists()) { dFile.mkdir(); } } String directoryPath = "sdcard/My Camera"; File file = new File(directoryPath, namafile); imageUri1 = Uri.fromFile(file); InputStream in = new FileInputStream(src1); OutputStream out = new FileOutputStream(dest); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); File filea = new File(src1); File filet = new File(dest); imageUri2 = Uri.fromFile(filet); selectedImageUri = imageUri2; filea.delete(); if (filea.exists()) { filea.getCanonicalFile().delete(); if (filea.exists()) { getApplicationContext().deleteFile(filea.getName()); } } } catch (Exception e) { } if (selectedImageUri != null) { if (selectedImageUri != null) { try { // OI FILE Manager String filemanagerstring2 = selectedImageUri .getPath(); // MEDIA GALLERY String selectedImagePath2 = getPath(selectedImageUri); if (selectedImagePath2 != null) { filePath = selectedImagePath2; } else if (filemanagerstring2 != null) { filePath = filemanagerstring2; } else { Toast.makeText(getApplicationContext(), "Unknown path", Toast.LENGTH_LONG) .show(); Log.e("Bitmap", "Unknown path"); } if (filePath != null) { decodeUri(filePath); // Fungsi untuk memperkecil dan memberi watermark pada poto loadImage(namafile); //Fungsi untuk menampilkan Gambar } else { bitmap = null; } } catch (Exception e) { Log.e(e.getClass().getName(), e.getMessage(), e); } } } } } } public String getPath(Uri uri) { String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(uri, projection, null, null, null); if (cursor != null) { int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } else return null; } //Fungsi yang di gunakan untuk mengkompress photo dan memberi watermark pada photo public void decodeUri(String filePath2) throws FileNotFoundException { // Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; Uri uriFromPath = Uri.fromFile(new File(filePath2)); BitmapFactory.decodeStream(getContentResolver().openInputStream( uriFromPath)); final int REQUIRED_SIZE = 65; int width_tmp = o.outWidth, height_tmp = o.outHeight; int scale = 1; while (true) { if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) break; width_tmp /= 2; height_tmp /= 2; scale *= 2; } BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; //Untuk mengambil tanggal final Calendar c = Calendar.getInstance(); int mYear = c.get(Calendar.YEAR); int mMonth = c.get(Calendar.MONTH) + 1; int mDay = c.get(Calendar.DAY_OF_MONTH); int second = c.get(Calendar.SECOND); int minute = c.get(Calendar.MINUTE); int hour = c.get(Calendar.HOUR_OF_DAY); String Date = mDay + "/" + mMonth + "/" + mYear+" "+hour+":"+minute+":"+second; // Format text yang akan muncul di watermark bitmap = BitmapFactory.decodeStream(getContentResolver() .openInputStream(uriFromPath), null, o2); Bitmap drawableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true); Canvas canvas = new Canvas(drawableBitmap); Paint paint = new Paint(); paint.setColor(Color.RED); // warna text watermark : merah paint.setTextSize(46); // ukuran text watermark Rect bounds = new Rect(); paint.getTextBounds(Date, 0,Date.length(), bounds); int x = 180; // untuk posisi watermark int y = bitmap.getHeight() - 60; System.out.println(x + "-" + y); canvas.drawText(Date, x, y, paint); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); drawableBitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes); // untuk mengkompress photo supaya lebih kecil File f = new File(filePath2); try { f.createNewFile(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } FileOutputStream fo = null; try { fo = new FileOutputStream(f); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { fo.write(bytes.toByteArray()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { fo.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //Fungsi untuk menampilkan poto yang sudah di ambil oleh kamera void loadImage(String namafile) throws FileNotFoundException { final int THUMBNAIL_SIZE = 300; //ukuran thumbnail poto yang akan tampil Uri uriFromPath = Uri.fromFile(new File("/sdcard/My Camera/" + namafile)); // alamat poto yang di ambil Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver() .openInputStream(uriFromPath)); Float width = new Float(bitmap.getWidth()); Float height = new Float(bitmap.getHeight()); Float ratio = width / height; // bitmap bitmap = Bitmap.createScaledBitmap(bitmap, (int) (THUMBNAIL_SIZE * ratio), THUMBNAIL_SIZE, false); img.setImageBitmap(bitmap); } }
Projek Aplikasi dapat di download di bawah ini :
http://www.4shared.com/zip/8g4cRqbqce/MyCamera.html
No comments:
Post a Comment