android開發(15) 調用攝像頭拍照,保存在照片到數據庫。


好吧。我們做手機開發的,總是避免不了操作攝像頭的問題。我在這里也糾結了一天。只好不停的再搜索引擎里搜來搜去。最后做了一個完整示例。期間遇到很多問題,把自己折磨的不行。那么弄個完整的示例,給自己,也給后來學習者。那么,開始說代碼吧。

 

1。啟動攝像頭

 

              // 向  MediaStore.Images.Media.EXTERNAL_CONTENT_URI 插入一個數據,那么返回標識ID。
            
// 在完成拍照后,新的照片會以此處的photoUri命名. 其實就是指定了個文件名
            ContentValues values =  new ContentValues();
            photoUri = getContentResolver().insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
             // 准備intent,並 指定 新 照片 的文件名(photoUri)
            Intent intent =  new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
             // 啟動拍照的窗體。並注冊 回調處理。
            startActivityForResult(intent, REQUEST_CODE_camera);

 

2. 處理 回調。就是當拍照完成后,我們如何處理它。我們必須在activity的onActivityResult(要重載此方法)方法里處理它。

public  void HandleonActivityResult( int requestCode,  int resultCode,
                Intent data) {
             if (requestCode == CameraHelper.REQUEST_CODE_camera) {

                ContentResolver cr = mContext.getContentResolver();
                 if (photoUri ==  null)
                     return;
                 // 按 剛剛指定 的那個文件名,查詢數據庫,獲得更多的 照片信息,比如 圖片的物理絕對路徑
                Cursor cursor = cr.query(photoUri,  nullnullnullnull);
                 if (cursor !=  null) {
                     if (cursor.moveToNext()) {
                        String path = cursor.getString( 1);
                         // 獲得圖片
                        Bitmap bp = getBitMapFromPath(path);
                        imageView1.setImageBitmap(bp);

                         // 寫入到數據庫
                        mBlobDAL.InsertImg(bp);
                    }
                    cursor.close();
                }
                photoUri =  null;
            }
        

 3.我們在這里需要處理圖片的縮放。以為圖片太大了,直接放入ImageView是無法顯示的。

 

         /*  獲得圖片,並進行適當的 縮放。 圖片太大的話,是無法展示的。  */

       private Bitmap getBitMapFromPath(String imageFilePath) {

            Display currentDisplay = getWindowManager().getDefaultDisplay();
             int dw = currentDisplay.getWidth();
             int dh = currentDisplay.getHeight();
             //  Load up the image's dimensions not the image itself
            BitmapFactory.Options bmpFactoryOptions =  new BitmapFactory.Options();
            bmpFactoryOptions.inJustDecodeBounds =  true;
            Bitmap bmp = BitmapFactory.decodeFile(imageFilePath,
                    bmpFactoryOptions);
             int heightRatio = ( int) Math.ceil(bmpFactoryOptions.outHeight
                    / ( float) dh);
             int widthRatio = ( int) Math.ceil(bmpFactoryOptions.outWidth
                    / ( float) dw);

             //  If both of the ratios are greater than 1,
            
//  one of the sides of the image is greater than the screen
             if (heightRatio >  1 && widthRatio >  1) {
                 if (heightRatio > widthRatio) {
                     //  Height ratio is larger, scale according to it
                    bmpFactoryOptions.inSampleSize = heightRatio;
                }  else {
                     //  Width ratio is larger, scale according to it
                    bmpFactoryOptions.inSampleSize = widthRatio;
                }
            }
             //  Decode it for real
            bmpFactoryOptions.inJustDecodeBounds =  false;
            bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
             return bmp;
        }

 好了。處理攝像頭拍照是完了。下面我們要把圖片存放在數據里。

4.建表

         

        @Override  

         publicvoid onCreate(SQLiteDatabase db) {

            String str = "CREATE TABLE [IMGS] ( [IDPK] integer PRIMARY KEY autoincrement,IMG_DATA blob )";
            db.execSQL(str);
        }

5.插入數據庫。   

          /* * 插入圖
         *  */
         public  void InsertImg(Bitmap bmp) {
            SQLiteDatabase db = getWritableDatabase();
            ContentValues cv =  new ContentValues();

            ByteArrayOutputStream os =  new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.PNG, 100, os);

            cv.put("IMG_DATA", os.toByteArray());
            db.insert("IMGS",  null, cv);

        }

 6.讀取圖片列表

         // 讀取
         public List<Bitmap> ReadImg() {
            SQLiteDatabase db = getReadableDatabase();
            Cursor cr = db.rawQuery("select * from IMGS ",  null);
            List<Bitmap> lst =  new ArrayList<Bitmap>();
             while (cr.moveToNext()) {
                 byte[] in = cr.getBlob(cr.getColumnIndex("IMG_DATA"));
                lst.add(BitmapFactory.decodeByteArray(in, 0, in.length));
            }
             return lst;  } 

 

---------------------------

最后貼上完整的代碼:

package demo.cameraDemo;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SlidingDrawer;

public  class MainActivity  extends Activity {
    Button btnPaizhao;
    CameraHelper mCameraHelper;
    ImageView imageView1;
    BlobDAL mBlobDAL;

    @Override
     public  void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mBlobDAL =  new BlobDAL( this);

        imageView1 = (ImageView) findViewById(R.id.imageView1);

        findViewById(R.id.btnReadDB).setOnClickListener( new OnClickListener() {

            @Override
             public  void onClick(View v) {
                List<Bitmap> bpArr = mBlobDAL.ReadImg();
                ViewGroup gp = (ViewGroup) findViewById(R.id.div);
                gp.removeAllViews();
                 for ( int i = 0; i < bpArr.size(); i++) {
                    ImageView iv =  new ImageView(MainActivity. this);
                    Bitmap bp = bpArr.get(i);
                     if (bp !=  null) {
                        iv.setImageBitmap(bp);
                    }  else {
                        iv.setImageBitmap( null);
                    }
                    gp.addView(iv);
                }

            }
        });

        btnPaizhao = (Button) findViewById(R.id.btnPaizhao);
        btnPaizhao.setOnClickListener( new OnClickListener() {

            @Override
             public  void onClick(View arg0) {
                mCameraHelper.OnOpenCamera();
            }

        });

        mCameraHelper =  new CameraHelper( this);
    }

     protected  void onActivityResult( int requestCode,  int resultCode, Intent data) {
        mCameraHelper.HandleonActivityResult(requestCode, resultCode, data);
    }

     public  class CameraHelper {
        Context mContext;

         public CameraHelper(Context ctx) {
            mContext = ctx;
        }

        Uri photoUri;
         public  static  final  int REQUEST_CODE_camera = 2222;

         public  void OnOpenCamera() {
            
             // 向  MediaStore.Images.Media.EXTERNAL_CONTENT_URI 插入一個數據,那么返回標識ID。
            
// 在完成拍照后,新的照片會以此處的photoUri命名. 其實就是指定了個文件名
            ContentValues values =  new ContentValues();
            photoUri = getContentResolver().insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
             // 准備intent,並 指定 新 照片 的文件名(photoUri)
            Intent intent =  new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
             // 啟動拍照的窗體。並注冊 回調處理。
            startActivityForResult(intent, REQUEST_CODE_camera);
        }

         public  void HandleonActivityResult( int requestCode,  int resultCode,
                Intent data) {
             if (requestCode == CameraHelper.REQUEST_CODE_camera) {

                ContentResolver cr = mContext.getContentResolver();
                 if (photoUri ==  null)
                     return;
                 // 按 剛剛指定 的那個文件名,查詢數據庫,獲得更多的 照片信息,比如 圖片的物理絕對路徑
                Cursor cursor = cr.query(photoUri,  nullnullnullnull);
                 if (cursor !=  null) {
                     if (cursor.moveToNext()) {
                        String path = cursor.getString(1);
                         // 獲得圖片
                        Bitmap bp = getBitMapFromPath(path);
                        imageView1.setImageBitmap(bp);

                         // 寫入到數據庫
                        mBlobDAL.InsertImg(bp);
                    }
                    cursor.close();
                }
                photoUri =  null;
            }
        }

         /*  獲得圖片,並進行適當的 縮放。 圖片太大的話,是無法展示的。  */
         private Bitmap getBitMapFromPath(String imageFilePath) {
            Display currentDisplay = getWindowManager().getDefaultDisplay();
             int dw = currentDisplay.getWidth();
             int dh = currentDisplay.getHeight();
             //  Load up the image's dimensions not the image itself
            BitmapFactory.Options bmpFactoryOptions =  new BitmapFactory.Options();
            bmpFactoryOptions.inJustDecodeBounds =  true;
            Bitmap bmp = BitmapFactory.decodeFile(imageFilePath,
                    bmpFactoryOptions);
             int heightRatio = ( int) Math.ceil(bmpFactoryOptions.outHeight
                    / ( float) dh);
             int widthRatio = ( int) Math.ceil(bmpFactoryOptions.outWidth
                    / ( float) dw);

             //  If both of the ratios are greater than 1,
            
//  one of the sides of the image is greater than the screen
             if (heightRatio > 1 && widthRatio > 1) {
                 if (heightRatio > widthRatio) {
                     //  Height ratio is larger, scale according to it
                    bmpFactoryOptions.inSampleSize = heightRatio;
                }  else {
                     //  Width ratio is larger, scale according to it
                    bmpFactoryOptions.inSampleSize = widthRatio;
                }
            }
             //  Decode it for real
            bmpFactoryOptions.inJustDecodeBounds =  false;
            bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
             return bmp;
        }

    }

     /*
     * 操作數據庫
     * 
*/
     class BlobDAL  extends SQLiteOpenHelper {

         public BlobDAL(Context context) {
             super(context, "imgDemo.db",  null, 1);
             //  TODO Auto-generated constructor stub
        }

        @Override
         public  void onCreate(SQLiteDatabase db) {
            String str = "CREATE TABLE [IMGS] ( [IDPK] integer PRIMARY KEY autoincrement,IMG_DATA blob )";
            db.execSQL(str);
        }
        
         /*
         * 插入圖
         * 
*/
         public  void InsertImg(Bitmap bmp) {
            SQLiteDatabase db = getWritableDatabase();
            ContentValues cv =  new ContentValues();

            ByteArrayOutputStream os =  new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.PNG, 100, os);

            cv.put("IMG_DATA", os.toByteArray());
            db.insert("IMGS",  null, cv);

        }

         // 讀取
         public List<Bitmap> ReadImg() {
            SQLiteDatabase db = getReadableDatabase();
            Cursor cr = db.rawQuery("select * from IMGS ",  null);
            List<Bitmap> lst =  new ArrayList<Bitmap>();
             while (cr.moveToNext()) {
                 byte[] in = cr.getBlob(cr.getColumnIndex("IMG_DATA"));
                lst.add(BitmapFactory.decodeByteArray(in, 0, in.length));
            }
             return lst;
        }



        @Override
         public  void onUpgrade(SQLiteDatabase db,  int oldVersion,  int newVersion) {
             //  TODO Auto-generated method stub

        }

    }

    @Override
     public  boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
         return  true;
    }

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnPaizhao"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="拍照" />

    <Button
        android:id="@+id/btnReadDB"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="讀數據庫-顯示剛剛拍的" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="#000000" >
    </View>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="拍照后顯示在下面:"
        android:textSize="16sp"
        android:textColor="#FFFFFF"
        android:background="#000000" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="fill_parent"
        android:layout_height="150dp"
        android:src="@drawable/ic_action_search" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="#000000" >
    </View>
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="讀取數據庫后顯示在下面:"
        android:textSize="16sp"
        android:textColor="#FFFFFF"
        android:background="#000000" />
    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <LinearLayout
                android:id="@+id/div"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >
            </LinearLayout>
        </LinearLayout>
    </ScrollView>

</LinearLayout> 

 ---

提供代碼下載 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM