Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone


Android Taking Photo and Photo to Gallery

Android Taking Photo and Photo to Gallery อีกความสามารถหนึ่งที่น่าสนใจในการเขียน Android ที่เกี่ยวข้องกับการถ่ายรูปด้วย Camera ก็คือ การใช้ Android เรียกกล้องถ่ายรูป และนำ Result รูปที่ได้จัดเก็บลงใน Storage (SD Card) และนำรุปภาพไปเพิ่มลงใน Gallery ของเครื่อง ซึ่งวิธีการนั้นสามารถทำได้ง่ายมากด้วยการ Intent ไปยัง Intent.ACTION_MEDIA_SCANNER_SCAN_FILE จากนั้นแปลงรุปภาพให้อยู่ในรูปแบบของ File Object และ sendBroadcast ไปยัง Gallery



Android Taking Photo and Photo to Gallery


การเปิดกล้อง Camera ถ่ายรูปและ Capture รูปภาพ
01.Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
02.// Ensure that there's a camera activity to handle the intent
03.if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
04.    // Create the File where the photo should go
05.    File photoFile = null;
06.    try {
07.        photoFile = createImageFile();
08.    } catch (IOException ex) {}
09.    // Continue only if the File was successfully created
10.    if (photoFile != null) {
11.        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
12.                Uri.fromFile(photoFile));
13.        startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
14.    }
15.}

หลังจากถ่ายภาพเสร็จแล้วจะใช้การสร้างรูปภาพและจัดเก็บลงใน Storage SD Card
01.private File createImageFile() throws IOException {
02.    // Create an image file name
03.    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
04.    String imageFileName = "JPEG_" + timeStamp + "_";
05.    File storageDir = new File(strSDCardPathName);
06.    File image = File.createTempFile(
07.        imageFileName,  /* prefix */
08.        ".jpg",         /* suffix */
09.        storageDir      /* directory */
10.    );
11. 
12.    // Save a file: path for use with ACTION_VIEW intents
13.    mCurrentPhotoPath = image.getAbsolutePath();
14.    return image;
15.}

สามารถกำหนด Path ได้จาก Environment.getExternalStorageDirectory()
1.static String strSDCardPathName = Environment.getExternalStorageDirectory() + "/temp_picture" + "/";

การ Add รูปภาพลงใน Gallery
1.private void GalleryAddPic() {
2.    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
3.    File f = new File(mCurrentPhotoPath);
4.    Uri contentUri = Uri.fromFile(f);
5.    mediaScanIntent.setData(contentUri);
6.    this.sendBroadcast(mediaScanIntent);
7.}


ในการเรียกใช้งาน Camera และ Save ลงใน Storage (SD Card) จะต้องกำหนด Permission และ Feature ดังนี้

AndroidManifest.xml
1.<uses-permission android:name="android.permission.CAMERA" />
2.<uses-feature android:name="android.hardware.camera" android:required="true" />
3.<uses-feature android:name="android.hardware.camera.autofocus" />
4. 
5.<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />




Example ตัวอย่างการเขียน Android เพื่อเปิดกล้องถ่ายรูปและ Capture รูปภาพ และ การ Add รูปภาพลงใน Gallery

Android Taking Photo and Photo to Gallery

โครงสร้างของไฟล์ในโปรเจคสามารถใช้ได้ทั้งบน Eclipse และ Android Studio

Android Taking Photo and Photo to Gallery

activity_main.xml
01.<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
02.    android:id="@+id/tableLayout1"
03.    android:layout_width="fill_parent"
04.    android:layout_height="fill_parent">
05.  
06.    <TableRow
07.      android:id="@+id/tableRow1"
08.      android:layout_width="wrap_content"
09.      android:layout_height="wrap_content" >
10.      
11.     <TextView
12.        android:id="@+id/textView1"
13.        android:layout_width="wrap_content"
14.        android:layout_height="wrap_content"
15.        android:gravity="center"
16.        android:text="Camera Take Photo "
17.        android:layout_span="1"
18.        android:textAppearance="?android:attr/textAppearanceLarge" />
19.             
20.    </TableRow>
21. 
22.    <View
23.        android:layout_height="1dip"
24.        android:background="#CCCCCC" />
25.  
26.  <TableLayout
27.      android:layout_width="fill_parent"
28.      android:layout_height="wrap_content"
29.      android:layout_weight="0.1"
30.      android:orientation="horizontal" >
31. 
32. 
33.      <ImageView
34.          android:id="@+id/imgView"
35.          android:layout_width="wrap_content"
36.          android:layout_height="wrap_content"
37.          android:layout_weight="0.75"
38.          android:src="@drawable/ic_launcher" />
39. 
40.      <Button
41.          android:id="@+id/btnTakePhoto"
42.          android:layout_width="wrap_content"
43.          android:layout_height="wrap_content"
44.          android:text="Take Photo" />
45.  </TableLayout>
46. 
47.    <View
48.        android:layout_height="1dip"
49.        android:background="#CCCCCC" />
50.           
51.    <LinearLayout
52.      android:id="@+id/LinearLayout1"
53.      android:layout_width="wrap_content"
54.      android:layout_height="wrap_content"
55.      android:padding="5dip" >
56. 
57.        <TextView
58.            android:id="@+id/textView2"
59.            android:layout_width="wrap_content"
60.            android:layout_height="wrap_content"
61.            android:text="By.. ThaiCreate.Com" />
62. 
63.    </LinearLayout>
64.     
65.</TableLayout>




ไฟล์ Java

MainActivity.java
001.package com.myapp;
002. 
003.import android.os.Bundle;
004.import android.os.Environment;
005.import android.provider.MediaStore;
006. 
007.import java.io.File;
008.import java.io.IOException;
009.import java.text.SimpleDateFormat;
010.import java.util.Date;
011. 
012.import android.app.Activity;
013.import android.content.Intent;
014.import android.graphics.Bitmap;
015.import android.graphics.BitmapFactory;
016.import android.net.Uri;
017.import android.view.View;
018.import android.view.Menu;
019.import android.widget.Button;
020.import android.widget.ImageView;
021. 
022.public class MainActivity extends Activity {
023.     
024.    ImageView imgView;
025.    static final int REQUEST_TAKE_PHOTO = 1;
026.    String mCurrentPhotoPath;
027.     
028.    static String strSDCardPathName = Environment.getExternalStorageDirectory() + "/temp_picture" + "/";
029.     
030.    @Override
031.    public void onCreate(Bundle savedInstanceState) {
032.        super.onCreate(savedInstanceState);
033.        setContentView(R.layout.activity_main);
034.         
035.        //*** Create Folder
036.        createFolder();
037.         
038.        //*** ImageView
039.        imgView = (ImageView) findViewById(R.id.imgView);
040.                 
041.        //*** Take Photo
042.        final Button btnTakePhoto = (Button) findViewById(R.id.btnTakePhoto);
043.        // Perform action on click
044.        btnTakePhoto.setOnClickListener(new View.OnClickListener() {
045.            public void onClick(View v) {
046.                     
047.                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
048.                // Ensure that there's a camera activity to handle the intent
049.                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
050.                    // Create the File where the photo should go
051.                    File photoFile = null;
052.                    try {
053.                        photoFile = createImageFile();
054.                    } catch (IOException ex) {}
055.                    // Continue only if the File was successfully created
056.                    if (photoFile != null) {
057.                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
058.                                Uri.fromFile(photoFile));
059.                        startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
060.                    }
061.                }
062.                 
063.            }  
064.        });
065.         
066.    }
067.     
068.     
069.      
070.    private File createImageFile() throws IOException {
071.        // Create an image file name
072.        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
073.        String imageFileName = "JPEG_" + timeStamp + "_";
074.        File storageDir = new File(strSDCardPathName);
075.        File image = File.createTempFile(
076.            imageFileName,  /* prefix */
077.            ".jpg",         /* suffix */
078.            storageDir      /* directory */
079.        );
080. 
081.        // Save a file: path for use with ACTION_VIEW intents
082.        mCurrentPhotoPath = image.getAbsolutePath();
083.        return image;
084.    }
085.      
086.     
087.    @Override
088.    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
089.        if (resultCode == RESULT_OK) {                 
090.            Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
091.            imgView.setImageBitmap(bitmap);
092.             
093.            //*** Add to Gallery
094.            GalleryAddPic();
095.        }
096.    }
097.     
098.    private void GalleryAddPic() {
099.        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
100.        File f = new File(mCurrentPhotoPath);
101.        Uri contentUri = Uri.fromFile(f);
102.        mediaScanIntent.setData(contentUri);
103.        this.sendBroadcast(mediaScanIntent);
104.    }
105.     
106.     public static void createFolder()
107.     {
108.        File folder = new File(strSDCardPathName);
109.        try
110.        {
111.            // Create folder
112.            if (!folder.exists()) {
113.                folder.mkdir();
114.            }
115.        }catch(Exception ex){}
116.         
117.     }
118.      
119.    @Override
120.    public boolean onCreateOptionsMenu(Menu menu) {
121.        getMenuInflater().inflate(R.menu.main, menu);
122.        return true;
123.    }
124.     
125.}


Screenshot

Android Taking Photo and Photo to Gallery

หน้าแรกของ App ให้คลิกที่ Take Photo



Android Taking Photo and Photo to Gallery

โปรแกรมจะ Intent ไปยัง App ที่ทำหน้าที่ถ่ายรูป และเปิด Camera

Android Taking Photo and Photo to Gallery

หลังจากที่ถ่ายรูปเสร็จแล้วโปรแกรมจะถามว่าต้องการ Save รูปนี้หรือไม่

Android Taking Photo and Photo to Gallery

เมื่อกด Save ภาพถ่ายจะถูกจัดเก็บลงใน Storage ตามโฟเดอร์ที่กำหนด และแสดงผลบน ImageView

Android Taking Photo and Photo to Gallery

เปิด Gallery บน Android

Android Taking Photo and Photo to Gallery

รุปที่ถูกถ่ายจะถูกเพิ่มลงใน Gallery


.

   
Hate it
Don't like it
It's ok
Like it
Love it
Share


ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท


ลองใช้ค้นหาข้อมูล


   


Bookmark.   
       
  By : ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)
  Score Rating :  
  Create/Update Date : 2015-11-16 15:56:02 / 2017-03-26 21:08:57
  Download : No files
 Sponsored Links / Related

 
Android Taking Photo Capture Screenshots (Camera)
Rating :

 
Android Taking Photo and Save Photo to Storage (SD Card)
Rating :

 
Android Taking Photo and Resize Images (Quality, Size, Width, Height)
Rating :

 
Android Taking Photo and Upload file to Server (PHP/Upload)
Rating :

 
Android Taking Photo and Multiple Upload to Server (PHP/Upload/ProgressDialog)
Rating :


ThaiCreate.Com Forum
Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   





ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2025 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่