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



Clound SSD Virtual Server

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

Android Taking Photo and Save Photo to Storage (SD Card) ในตอนที่สองของ Camera Taking Photo จะเป็นการนำ Result ที่ได้จากการถ่ายรูปจาก Camera มาจัดเก็บเป็นไฟล์ลงใน Storage (SD Card) ซึ่งวิธีการนั้นคือแทนที่จะนำ Result ภาพที่ได้มาแสดงผลจะใช้การนำมาสร้างเป็นรูปภาพ Image โดยความชัดที่ได้นั้นจะขึ้นอยู่กับคุณภาพของกล้องของโทรศัพท์ในแต่ล่ะรุ่น และหลังจากที่ได้ไฟล์จากการถ่ายรูปลงใน SD Card แล้ว เราสามารถนำ Path ที่ได้มาแสดงผลบน ImageView หรือจะนำไปใช้งาในด้านอื่น ๆ ก็ได้เช่นเดียวกัน





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



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

หลังจากถ่ายภาพเสร็จแล้วจะใช้การสร้างรูปภาพและจัดเก็บลงใน Storage SD Card
	private File createImageFile() throws IOException {
	    // Create an image file name
	    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
	    String imageFileName = "JPEG_" + timeStamp + "_";
	    File storageDir = new File(strSDCardPathName);
	    File image = File.createTempFile(
	        imageFileName,  /* prefix */
	        ".jpg",         /* suffix */
	        storageDir      /* directory */
	    );

	    // Save a file: path for use with ACTION_VIEW intents
	    mCurrentPhotoPath = image.getAbsolutePath();
	    return image;
	} 

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


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

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


Example ตัวอย่างการเขียน Android เพื่อเปิดกล้องถ่ายรูปและ Capture รูปภาพ และบันทึกลงใน Storage (SD Card)

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

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

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

activity_main.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tableLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
 
   	<TableRow
      android:id="@+id/tableRow1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" >
     
     <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Camera Take Photo "
        android:layout_span="1"
        android:textAppearance="?android:attr/textAppearanceLarge" />
  	        
 	</TableRow>

	<View
		android:layout_height="1dip"
		android:background="#CCCCCC" />
 
  <TableLayout
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="0.1"
      android:orientation="horizontal" >


      <ImageView
          android:id="@+id/imgView"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_weight="0.75"
          android:src="@drawable/ic_launcher" />

      <Button
          android:id="@+id/btnTakePhoto"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Take Photo" />
  </TableLayout>

	<View
		android:layout_height="1dip"
		android:background="#CCCCCC" />
   		  
   	<LinearLayout
      android:id="@+id/LinearLayout1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:padding="5dip" >

   		<TextView
   		    android:id="@+id/textView2"
   		    android:layout_width="wrap_content"
   		    android:layout_height="wrap_content"
   		    android:text="By.. ThaiCreate.Com" />

	</LinearLayout>
	
</TableLayout>









ไฟล์ Java

MainActivity.java
package com.myapp;

import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.view.Menu;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {
	
	ImageView imgView;
	static final int REQUEST_TAKE_PHOTO = 1;
	String mCurrentPhotoPath;
	
	static String strSDCardPathName = Environment.getExternalStorageDirectory() + "/temp_picture" + "/";
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //*** Create Folder
        createFolder();
        
        //*** ImageView
        imgView = (ImageView) findViewById(R.id.imgView);
        
        //*** Take Photo
        final Button btnTakePhoto = (Button) findViewById(R.id.btnTakePhoto);
        // Perform action on click
        btnTakePhoto.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
        	     	
        	    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        	    // Ensure that there's a camera activity to handle the intent
        	    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        	        // Create the File where the photo should go
        	        File photoFile = null;
        	        try {
        	            photoFile = createImageFile();
        	        } catch (IOException ex) {}
        	        // Continue only if the File was successfully created
        	        if (photoFile != null) {
        	            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
        	                    Uri.fromFile(photoFile));
        	            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        	        }
        	    }
        	    
            }	
        });
        
    }
    
	 
	private File createImageFile() throws IOException {
	    // Create an image file name
	    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
	    String imageFileName = "JPEG_" + timeStamp + "_";
	    File storageDir = new File(strSDCardPathName);
	    File image = File.createTempFile(
	        imageFileName,  /* prefix */
	        ".jpg",         /* suffix */
	        storageDir      /* directory */
	    );

	    // Save a file: path for use with ACTION_VIEW intents
	    mCurrentPhotoPath = image.getAbsolutePath();
	    return image;
	} 
	 
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if (resultCode == RESULT_OK) {
	    	/*
	        Bundle extras = data.getExtras();
	        Bitmap imageBitmap = (Bitmap) extras.get("data");
	        imgView.setImageBitmap(imageBitmap);
	        */
	    }
	}
	
	 public static void createFolder() 
     {
		File folder = new File(strSDCardPathName);
		try
		{
			// Create folder
			if (!folder.exists()) {
			    folder.mkdir();
			}
		}catch(Exception ex){}
		
     } 
	 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}


Screenshot

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

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








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

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

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

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

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

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

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

ภาพถ่ายจัดเก็บอยู่ใน Storage (SD Card)

ในกรณีที่ต้องการเรียกภาพที่ถูกจัดเก็บมาใช้งานเช่นแสดงผลบน ImageView สามารถเขียนได้เพิ่มเติมในส่วนของ onActivityResult

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if (resultCode == RESULT_OK) {
	    	
	        // Get the dimensions of the View
	        //int targetW = 300;
	        //int targetH = 300;	
	        int targetW = imgView.getWidth();
	        int targetH = imgView.getHeight();
	        
	        // Get the dimensions of the bitmap
	        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
	        bmOptions.inJustDecodeBounds = true;
	        BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
	        int photoW = bmOptions.outWidth;
	        int photoH = bmOptions.outHeight;

	        // Determine how much to scale down the image
	        int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

	        // Decode the image file into a Bitmap sized to fill the View
	        bmOptions.inJustDecodeBounds = false;
	        bmOptions.inSampleSize = scaleFactor;
	        bmOptions.inPurgeable = true;

	        Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
	        imgView.setImageBitmap(bitmap);
	        
	    }
	}

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

แสดงผลบน ImageView



ในกรณีที่ต้องการเปลี่ยนชื่อไฟล์ Rename ก็สามารถเพิ่มได้ที่ onActivityResult เช่นเดียวกัน

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if (resultCode == RESULT_OK) {
	    	
	    	//*** Rename File
	    	String strNewName = "MyPicture.jpg";
	    	String NewPath = strSDCardPathName + strNewName;	 
	    	
	    	File CurrPath = new File(mCurrentPhotoPath);
	    	CurrPath.renameTo(new File(NewPath));
	    	
	    			// Get the dimensions of the View
	        //int targetW = 300;
	        //int targetH = 300;	
	        int targetW = imgView.getWidth();
	        int targetH = imgView.getHeight();
	        
	        // Get the dimensions of the bitmap
	        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
	        bmOptions.inJustDecodeBounds = true;
	        BitmapFactory.decodeFile(NewPath, bmOptions);
	        int photoW = bmOptions.outWidth;
	        int photoH = bmOptions.outHeight;

	        // Determine how much to scale down the image
	        int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

	        // Decode the image file into a Bitmap sized to fill the View
	        bmOptions.inJustDecodeBounds = false;
	        bmOptions.inSampleSize = scaleFactor;
	        bmOptions.inPurgeable = true;

	        Bitmap bitmap = BitmapFactory.decodeFile(NewPath, bmOptions);
	        imgView.setImageBitmap(bitmap);
	        
	    }
	}

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

ใช้วิธีการ Rename เปลี่ยนชื่อไฟล์

   
Share


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


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


   


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

 
Android Taking Photo Capture Screenshots (Camera)
Rating :

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

 
Android Taking Photo and Photo to Gallery
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
   







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