Android操作SQLite數據庫Blob字段


package com.example.myapplication.db;

import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Environment;
import android.util.Log;
import com.example.myapplication.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MySQLiteOpenHelper extends SQLiteOpenHelper {
    private static final String DBname="uavshop.db"; //像控點數據庫
    private static  final int version=1;
    private String tag="MySQLDBHelper";
    private Context  mycontext;
    String IMAGE = "file_data"; //blob字段名稱
    String TB_NAME = "kzdphoto";//含blob表名

    public MySQLiteOpenHelper(Context context) {
        super(context, DBname, null, version);
        mycontext = context;
        Log.i(tag, "測試");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        Log.i(tag, "uavshop數據庫中kzdphoto創建前");
        String sqlString="create table kzdphoto (id integer primary key autoincrement,file_name nvarchar(255),file_data blob,file_size int,file_type int,xkd_id int,upload_man nvarchar(32),upload_date nvarchar(64),crc int,desc nvarchar(255))";
        db.execSQL(sqlString);
        Log.i(tag, "uavshop數據庫中kzdphoto創建成功");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        Log.i(tag, "更新數據庫,暫時不需要使用");
    }
    //---------------------------------------------------------------------------------------
    public void Test() //測試函數 ,將cw_30.png圖片文件插入數據表中
    {
        try
        {
            //從資源中獲取Bitmap對象
            Resources res = mycontext.getResources();
            Bitmap mybmp = BitmapFactory.decodeResource(res,R.drawable.cw_30);
            //轉換為Byte數組
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            mybmp.compress(Bitmap.CompressFormat.PNG, 100, os);
            byte[] img = os.toByteArray();
           //插入數據庫
           insert(img);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

    }
    //------------------------------------------------------------------------------------------
    public byte[] img(int id)//把圖片轉換成字節
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Bitmap bitmap = ((BitmapDrawable) mycontext.getResources().getDrawable(id,null)).getBitmap();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    //------------------------------------------------------------------------------------------

    //將圖片一字節形式存儲數據庫讀取操作
    public long insert(byte[] img)
    {
        String desc = "文件大小為:"+Integer.toString(img.length)+"字節";
        try
        {
            SQLiteDatabase db = getWritableDatabase();
            ContentValues cv = new ContentValues();
            cv.put("file_name","PG001.jpg");
            cv.put(IMAGE, img);
            cv.put("file_size",img.length);
            cv.put("file_type",1);
            cv.put("xkd_id",0);
            cv.put("upload_man","陳光榮");
            cv.put("upload_date","2021-03-05 15:10:20");
            cv.put("crc",25);
            cv.put("desc",desc);
            long result = db.insert(TB_NAME, null, cv);
            return result;
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            return -1;
        }


    }

    //-----------------------讀取blob字段轉為圖片-----------------------------------
    public Bitmap getBmp(int position)
    {
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.query(TB_NAME,null,null,null,null,null,null);
        cursor.moveToPosition(position);
        byte[] in = cursor.getBlob(cursor.getColumnIndex(IMAGE));
        Bitmap bmpout = BitmapFactory.decodeByteArray(in, 0, in.length);

        return bmpout;
    }
    //------------------將Bitmap對象另存為圖片文件------------------------------------------------------------------------
    public void saveBitmap(String name, Bitmap bm) {
        Log.d("Save Bitmap", "Ready to save picture");
        //指定我們想要存儲文件的地址
        String TargetPath = "";
        File dataFilepath = Environment.getExternalStorageDirectory();
        TargetPath = dataFilepath.getPath()+"/Pictures/";
        Log.d("Save Bitmap", "Save Path=" + TargetPath);
        //判斷指定文件夾的路徑是否存在

        if (!isExist(TargetPath)) {
            Log.d("Save Bitmap", "TargetPath isn't exist");
        } else {
            //如果指定文件夾創建成功,那么我們則需要進行圖片存儲操作
            File saveFile = new File(TargetPath, name);
            try {
                FileOutputStream saveImgOut = new FileOutputStream(saveFile);
                // compress - 壓縮的意思
                bm.compress(Bitmap.CompressFormat.PNG, 80, saveImgOut);
                //存儲完成后需要清除相關的進程
                saveImgOut.flush();
                saveImgOut.close();
                Log.d("Save Bitmap", "The picture is save to your phone!");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

//---------------------------判斷文件夾是否存在------------------------------------------------------
static public  boolean isExist(String path) {
    File file = new File(path);
    return file.exists();
}
// -------------------------------------------------------------------------------------------------
}

  


免責聲明!

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



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