节点返回存储在sqlite blob中的图像

时间:2015-07-17 04:04:50

标签: node.js sqlite blob restify

我使用Restify查询API 我的SQLite数据库有一个place表,它具有以下结构(id INTEGER, name TEXT, image BLOB) 我试图将响应结果输出为图像(blob包含jpeg图像),但到目前为止我还没有成功。 在发出请求后的浏览器中我获得了The image 'http://localhost:8080/place/1 cannot be displayed because it contains errors 我在控制台中正确地获得了地名。

这是我的代码:

var restify = require('restify');

function respond(req, res, next) {
  var fs = require("fs");
  var file = "./data.db";
  var exists = fs.existsSync(file);

  var sqlite3 = require('sqlite3').verbose();
  var db = new sqlite3.Database(file);

  db.get("SELECT id, name, image FROM places WHERE id = ?", req.params.uid, function(err, row){
    console.log(row.name);
    res.header('Content-Type', 'image/jpeg');
    res.end(row.image);
    db.close();
  });

  next();
}

var server = restify.createServer();

server.get('/place/:uid', respond);
server.listen(8080, function() {
  console.log('%s listening at %s', server.name, server.url);
});

UPDATE:当我使用相同的node-sqlite3库创建blob时,图像会毫无问题地返回。如果我使用Ruby或Go(我测试过的那些)创建blob,node-sqlite3解码不会按预期工作。

这是怎么回事?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

使用VARCHAR字段并以图像形式存储在图像中,然后检索为字节数组。 请参阅下面的代码,您可以在其中存储图像和检索。不使用blob。 这对你来说很简单。

 Uri selectedImage = data.getData();
         ImageView imageView=(ImageView)this.findViewById(R.id.imageView1);

        getContentResolver().notifyChange(selectedImage, null);

        ContentResolver cr = getContentResolver();
        Bitmap bitmap;
        try {


            bitmap = android.provider.MediaStore.Images.Media
             .getBitmap(cr, selectedImage);
            imageView.setImageBitmap(bitmap);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] b = baos.toByteArray();
            String encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);

            byte[] bytarray = Base64.decode(encodedImageString, Base64.DEFAULT);
            Bitmap bmimage = BitmapFactory.decodeByteArray(bytarray, 0,
                    bytarray.length);

            myDb.execSQL("INSERT INTO imgtbl VALUES('"+encodedImageString+"');");
            Cursor c= myDb.rawQuery("SELECT * FROM imgtbl", null);

           c.moveToFirst();
           String img=c.getString(0);
           byte[] byarray = Base64.decode(img, Base64.DEFAULT);
           Bitmap bmimg = BitmapFactory.decodeByteArray(byarray, 0,
                   byarray.length);

            ImageView iv=(ImageView)findViewById(R.id.img2);
            ImageView iv1=(ImageView)findViewById(R.id.img3);

            iv.setImageBitmap(bmimg);
            iv1.setImageBitmap(bmimg);


        } catch (Exception e) {
            Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                    .show();

            e.printStackTrace();
        }