Android開發(fā)(15) 調(diào)用攝像頭拍照,保存在照片到數(shù)據(jù)庫

概述

有時(shí)候我們需要操作攝像頭進(jìn)行拍照,并保存照片。


拍照

  1. 啟動(dòng)攝像頭
         //向  MediaStore.Images.Media.EXTERNAL_CONTENT_URI 插入一個(gè)數(shù)據(jù),那么返回標(biāo)識ID。
        //在完成拍照后,新的照片會(huì)以此處的photoUri命名. 其實(shí)就是指定了個(gè)文件名
        ContentValues values = new ContentValues();
        photoUri = getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        //準(zhǔn)備intent,并 指定 新 照片 的文件名(photoUri)
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
        //啟動(dòng)拍照的窗體。并注冊 回調(diào)處理。
        startActivityForResult(intent, REQUEST_CODE_camera);
  1. 處理 回調(diào)。就是當(dāng)拍照完成后,我們?nèi)绾翁幚硭N覀儽仨氃赼ctivity的onActivityResult(要重載此方法)方法里處理它。

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

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

                    //寫入到數(shù)據(jù)庫
                    mBlobDAL.InsertImg(bp);
                }
                cursor.close();
            }
            photoUri = null;
        }
  1. 我們在這里需要處理圖片的縮放。以為圖片太大了,直接放入ImageView是無法顯示的。
    /* 獲得圖片,并進(jìn)行適當(dāng)?shù)?縮放。 圖片太大的話,是無法展示的。 */
     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;
    }

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

存儲

  1. 建表
       @Override  
         publicvoid onCreate(SQLiteDatabase db) {

        String str = "CREATE TABLE [IMGS] ( [IDPK] integer PRIMARY KEY autoincrement,IMG_DATA blob )";
        db.execSQL(str);
    }
  1. 插入數(shù)據(jù)庫。

      /** 插入圖
      * */
     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);
    
     }
    
  2. 讀取圖片列表

     //讀取
     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 插入一個(gè)數(shù)據(jù),那么返回標(biāo)識ID。
            //在完成拍照后,新的照片會(huì)以此處的photoUri命名. 其實(shí)就是指定了個(gè)文件名
            ContentValues values = new ContentValues();
            photoUri = getContentResolver().insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            //準(zhǔn)備intent,并 指定 新 照片 的文件名(photoUri)
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
            //啟動(dòng)拍照的窗體。并注冊 回調(diào)處理。
            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;
                //按 剛剛指定 的那個(gè)文件名,查詢數(shù)據(jù)庫,獲得更多的 照片信息,比如 圖片的物理絕對路徑
                Cursor cursor = cr.query(photoUri, null, null, null, null);
                if (cursor != null) {
                    if (cursor.moveToNext()) {
                        String path = cursor.getString(1);
                        //獲得圖片
                        Bitmap bp = getBitMapFromPath(path);
                        imageView1.setImageBitmap(bp);

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

        /* 獲得圖片,并進(jìn)行適當(dāng)?shù)?縮放。 圖片太大的話,是無法展示的。 */
        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;
        }

    }

    /*
     * 操作數(shù)據(jù)庫
     * */
    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="讀數(shù)據(jù)庫-顯示剛剛拍的" />

    <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="讀取數(shù)據(jù)庫后顯示在下面:"
        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> 

演示代碼下載

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容