본문 바로가기

안드로이드

blob 이미지 insert, select 방법

반응형

blob 이미지 insert, update , select 방법


- 이미지를 blob로 변환해서 db에 저장하면 보안상 도움이 됩니다.

- 단 db용량이 커지기 때문에 이미지는 blob보다는 sd카드나 웹에서 다운받아서 파일로 사용하는것이 좋습니다.

- blob select시 db row가 증가하게 되면 table 쿼리 속도가 느려지는 문제가 있는데 table에 index를 적용해서 table         을 만들면 속도가 빨라집니다


- 예제 (db를 만들고 , table 명 MASTER_IMAGE , 칼럼 IMAGE(blob) 로 테이블을 만들어줍니다)

-> sd카드의 이미지를 읽어와서 byte[]로 만든 후  blob 칼럼에 업데이트 해주고 있습니다


ImageView blobImg;


 @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        blobImg= (ImageView)findViewById(R.id.b_img);

        insertBlob("blob0000"); 

       showImg();

}


public void  insertBlob (String imageName) {

SQLiteDatabase db=null;

WorldTourSqliteHelper mHelper = new WorldTourSqliteHelper(this);


int count =0;

try {

db = mHelper.getWritableDatabase();

String sql  = "UPDATE MASTER_IMAGE SET IMAGE=? 

   SQLiteStatement insertStmt      =   db.compileStatement(sql);

   insertStmt.clearBindings();

   insertStmt.bindBlob(1, getBlob (imageName));

   insertStmt.execute();

}

monthCursor.close();

Log.d("dddd"  ,"InsertComplete!!!!");

} catch (Exception e) {

Log.e("Thread", "Insert Error", e);

} finally {

mHelper.close();

}

}


private byte[] getBlob(String image){

ByteArrayBuffer baf = new ByteArrayBuffer(500);

    try {

    String FILE_PATH1 = "sdcard/"

    File file = new File(FILE_PATH1, image+".jpg");

    InputStream is = new FileInputStream(file);


            BufferedInputStream bis = new BufferedInputStream(is);

            int current = 0;

            while ((current = bis.read()) != -1) {

                    baf.append((byte) current);

            }

            return baf.toByteArray();

    } catch (Exception e) {

            Log.d("ImageManager", "Error: " + e.toString());

    }

    return baf.toByteArray();

}


private void showImg(){

SQLiteDatabase db=null;

WorldTourSqliteHelper mHelper = new WorldTourSqliteHelper(this);

int count =0;

 

try {

db = mHelper.getWritableDatabase();

String sql1 = "SELECT IMAGE FROM MASTER_IMAGE ";

Cursor monthCursor = db.rawQuery(sql1, null);

while (monthCursor.moveToNext()) {

byte[] image = monthCursor.getBlob(0);

        Bitmap bm= BitmapFactory.decodeByteArray( Img, 0, Img.length);

                        blobImg .setImageBitmap(bm);

}

 monthCursor.close();

}catch(Exception e){

}

finally{

mHelper.close();

}

}



     


insertStmt.bindBlob(1, getBlob (imageName));

-> getBlob (imageName) 가   IMAGE=? 에  바인딩 됩니다


private byte[] getBlob(String image)

-> sd카드에서 이미지 이름과 일치하는 파일을 찾아서 byte[]로 만들어 줍니다


byte[] image = monthCursor.getBlob(0);

Bitmap bm= BitmapFactory.decodeByteArray(   Img,  0,      Img.length);

-> 커서에 getBlob이미지를 사용하면 byte[] 을 리턴하는데 이것을 이용하여 이미지를 보여줍니다


반응형