【Android】_基于CameraHelper_拍照保存、简单相册(SQLite版)

CameraSQLiteDemo 实现拍照、相册浏览功能

(一)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

        }

    }
}

猜你喜欢

转载自blog.csdn.net/cungudafa/article/details/85221981
今日推荐