1. 程式人生 > >【Android】_基於CameraHelper_拍照儲存、簡單相簿(SQLite版)

【Android】_基於CameraHelper_拍照儲存、簡單相簿(SQLite版)

CameraSQLiteDemo 實現拍照、相簿瀏覽功能

一個簡單的CameraDemo

(一)CameraSQLite Demo

介面如圖1,拍攝兩張圖片、點選相簿可以檢視到所以照片:
在這裡插入圖片描述 在這裡插入圖片描述 在這裡插入圖片描述
在這裡插入圖片描述

(二)Android&Camera&sqlite用法

總結構:
在這裡插入圖片描述
拍照:呼叫OnOpenCamera函式
相簿:讀取資料庫中的圖片並順序檢視
在這裡插入圖片描述


CameraHelper函式(獲取攝像頭拍攝返回的二進位制圖片):
在這裡插入圖片描述
Blob函式(資料庫的建立,插入,讀取):
在這裡插入圖片描述
在這裡插入圖片描述

(三)實現介面和程式碼

1、activity_camera.xml佈局
在這裡插入圖片描述 在這裡插入圖片描述

<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" >
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary"> <Button android:id="@+id/btnPaizhao" android:layout_width="100dp"
android:layout_height="wrap_content" android:layout_marginTop="2dp" android:layout_marginLeft="2dp" android:layout_marginRight="2dp" android:layout_marginBottom="2dp" android:layout_weight="1" android:text="拍照" android:textColor="#ffffff" android:textSize="18sp" android:background="@drawable/shape_btn"/>
<Button android:id="@+id/btnReadDB" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_marginTop="2dp" android:layout_marginLeft="2dp" android:layout_marginRight="2dp" android:layout_marginBottom="2dp" android:layout_weight="1" android:text="相簿" android:textColor="#ffffff" android:textSize="18sp" android:background="@drawable/shape_btn"/> </LinearLayout> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="拍照" android:gravity="center" android:textSize="16sp" android:textColor="#FFFFFF" android:background="@color/colorAccent" /> <ImageView android:id="@+id/imageView1" android:layout_width="fill_parent" android:layout_height="150dp"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="我的相簿" android:gravity="center" android:textSize="16sp" android:textColor="#FFFFFF" android:background="@color/colorPrimary" /> <ScrollView android:id="@+id/scrollView1" 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> </ScrollView> </LinearLayout>

2、CameraActivity.java

package com.example.cungu.myapplication4;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.net.Uri;
import android.provider.MediaStore;
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.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
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;

public class CameraActivity extends AppCompatActivity implements View.OnClickListener{

    Button btnPaizhao;
    Button btnReadDB;
    CameraHelper mCameraHelper;
    ImageView imageView1;
    BlobDAL mBlobDAL;//BOLB表示二進位制大物件,這種資料型別通過用來儲存圖片,圖象,視訊等

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        imageView1 = (ImageView) findViewById(R.id.imageView1);
        btnPaizhao = (Button) findViewById(R.id.btnPaizhao);
        btnReadDB=(Button) findViewById(R.id.btnReadDB);
        btnPaizhao.setOnClickListener(this);
        btnReadDB.setOnClickListener(this);

        mBlobDAL = new BlobDAL(this);
        mCameraHelper = new CameraHelper(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent=new Intent();
        switch (v.getId()){
            case R.id.btnPaizhao:
                mCameraHelper.OnOpenCamera();
                break;
            case R.id.btnReadDB :
                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(CameraActivity.this);
                    Bitmap bp = bpArr.get(i);
                    if (bp != null) {
                        iv.setImageBitmap(bp);
                    } else {
                        iv.setImageBitmap(null);
                    }
                    gp.addView(iv);
                }
                break;
        }
    }

    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。
            ContentValues values = new ContentValues();
            //在完成拍照後,新的照片會以此處的photoUri命名. 其實就是指定了個檔名
            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, null, null, null, null);
                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

        }

    }
}