如何在Sqlite中将图像存储为blob以及如何检索它?

我想存储一个图像(从URL)到一个SQLite数据库。

为此我使用:

db = new DataBase(getApplicationContext()); URL url = new URL("http://sree.cc/wp-content/uploads/schogini_team.png"); URLConnection ucon = url.openConnection(); InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is,128); ByteArrayBuffer barb= new ByteArrayBuffer(128); int current = 0; while ((current = bis.read()) != -1) { barb.append((byte) current); } ContentValues filedata= new ContentValues(); filedata.put(DataBase.IMG_SRC,barb.toByteArray()); db.insert(DataBase.Table_Img, null, filedata); 

Insert()

 public void insert(String tableImg, Object object, ContentValues dataToInsert) { // TODO Auto-generated method stub String sql = "INSERT INTO "+tableImg+" ("+ID+","+IMG_SRC+") " + "VALUES ('"+1+"','"+dataToInsert+"')"; db.execSQL(sql); } 

为了检索图像:

 Cursor cursor = db.selectDataToShow(DataBase.Table_Img, DataBase.IMG_SRC); byte[] imageByteArray=cursor.getBlob(cursor.getColumnIndex(DataBase.IMG_SRC)); cursor.close(); ByteArrayInputStream imageStream = new ByteArrayInputStream(imageByteArray); Bitmap theImage = BitmapFactory.decodeStream(imageStream); System.out.println(">>>>>>>>>>>>>>>>>>>>>> "+theImage); 

所以在这里我得到了null

在我的数据库中,图像的值存储为: Image=[B@43e5ac48]

这里是我用于我的应用程序的代码

这段代码将从url中获取图片,并将其转换为字节数组

 byte[] logoImage = getLogoImage(IMAGEURL); private byte[] getLogoImage(String url){ try { URL imageUrl = new URL(url); URLConnection ucon = imageUrl.openConnection(); InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(500); 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 null; } 

要保存图像到数据库我使用这个代码。

  public void insertUser(){ SQLiteDatabase db = dbHelper.getWritableDatabase(); String delSql = "DELETE FROM ACCOUNTS"; SQLiteStatement delStmt = db.compileStatement(delSql); delStmt.execute(); String sql = "INSERT INTO ACCOUNTS (account_id,account_name,account_image) VALUES(?,?,?)"; SQLiteStatement insertStmt = db.compileStatement(sql); insertStmt.clearBindings(); insertStmt.bindString(1, Integer.toString(this.accId)); insertStmt.bindString(2,this.accName); insertStmt.bindBlob(3, this.accImage); insertStmt.executeInsert(); db.close(); } 

要检索图像,这是我使用的代码。

 public Account getCurrentAccount() { SQLiteDatabase db = dbHelper.getWritableDatabase(); String sql = "SELECT * FROM ACCOUNTS"; Cursor cursor = db.rawQuery(sql, new String[] {}); if(cursor.moveToFirst()){ this.accId = cursor.getInt(0); this.accName = cursor.getString(1); this.accImage = cursor.getBlob(2); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } db.close(); if(cursor.getCount() == 0){ return null; } else { return this; } } 

最后把这个图像加载到一个imageview

 logoImage.setImageBitmap(BitmapFactory.decodeByteArray( currentAccount.accImage, 0,currentAccount.accImage.length)); 

在DBAdaper即数据库帮助类中声明这样的表

  private static final String USERDETAILS= "create table userdetails(usersno integer primary key autoincrement,userid text not null ,username text not null,password text not null,photo BLOB,visibility text not null);"; 

像这样插入值,

首先将图像转换为字节[]

 ByteArrayOutputStream baos = new ByteArrayOutputStream(); Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.common)).getBitmap(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); byte[] photo = baos.toByteArray(); db.insertUserDetails(value1,value2, value3, photo,value2); 

在DEAdaper类中

  public long insertUserDetails(String uname,String userid, String pass, byte[] photo,String visibility) { ContentValues initialValues = new ContentValues(); initialValues.put("username", uname); initialValues.put("userid",userid); initialValues.put("password", pass); initialValues.put("photo",photo); initialValues.put("visibility",visibility); return db.insert("userdetails", null, initialValues); } 

检索图像如下

 Cursor cur=your query; while(cur.moveToNext()) { byte[] photo=cur.getBlob(index of blob cloumn); } 

将字节[]转换为图像

 ByteArrayInputStream imageStream = new ByteArrayInputStream(photo); Bitmap theImage= BitmapFactory.decodeStream(imageStream); 

我认为这个内容可能会解决你的问题

在insert()

 public void insert(String tableImg, Object object, ContentValues dataToInsert) { db.insert(tablename, null, dataToInsert); } 

希望它可以帮助你。

你也可能想要对base64进行编码和解码

  function uncompress(str:String):ByteArray { import mx.utils.Base64Decoder; var dec:Base64Decoder = new Base64Decoder(); dec.decode(str); var newByteArr:ByteArray=dec.toByteArray(); return newByteArr; } // Compress a ByteArray into a Base64 String. function compress(bytes:ByteArray):String { import mx.utils.Base64Decoder; //Transform String in a ByteArray. import mx.utils.Base64Encoder; //Transform ByteArray in a readable string. var enc:Base64Encoder = new Base64Encoder(); enc.encodeBytes(bytes); return enc.drain().split("\n").join(""); } 

为一个离子项目


     var imgURI =“”;
     var imgBBDD =“”;  // sqllite保存

    函数takepicture(){
                 var options = {
                    质量:75,
                     destinationType:Camera.DestinationType.DATA_URL,
                     sourceType:Camera.PictureSourceType.CAMERA,
                     allowEdit:true,
                     encodingType:Camera.EncodingType.JPEG,
                     targetWidth:300,
                     targetHeight:300,
                     popoverOptions:CameraPopoverOptions,
                     saveToPhotoAlbum:false
                 };

                 $ cordovaCamera.getPicture(options).then(function(imageData){
                     imgURI =“data:image / jpeg; base64,”+ imageData;
                     imgBBDD = imageData;
                 },函数(err){
                     // 发生错误。 向用户显示一条消息
                 });
             }

现在我们把imgBBDD放到SqlLite中


     函数saveImage = function(theId,themage){
       var insertQuery =“INSERT INTO images(id,image)VALUES(”+ theId +“,'”+ theimage +“');”
      的console.log( '>>>>>>>');
       DDBB.SelectQuery(insertQuery)
                     .then(function(result){
                         console.log(“保存图片”);
                     })
                     .catch(function(err) 
                      {
                         deferred.resolve(ERR);
                        返回cb(err);
                     });
     }

服务器端(PHP)


         $ request = file_get_contents(“php:// input”);  //获取原始数据
         $ dades = json_decode($ request,true);  // true返回数组


    如果($ dades == “”){
             $ array = array();
             $ array ['error'] = -1;
             $ array ['descError'] =“获取文件时出错”;
             $ array ['logError'] ='';
            回声json_encode($数组);
            出口;
         }
         //将图像再次发送到客户端
        标题('Content-Type:image / jpeg');
        回声“;

 byte[] byteArray = rs.getBytes("columnname"); Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0 ,byteArray.length);