如何使用java在mongoDB中插入图像? [英] How to insert images in mongoDB using java?
本文介绍了如何使用java在mongoDB中插入图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将图像文档存储在mongoDB中。
我正在使用java。
I want to store image documents in mongoDB.
I am using java.
任何链接或建议都将受到赞赏。
Any links or suggestions would be appreciated.
推荐答案
为了存储像图像这样的二进制数据,你可以使用 GridFS 或实现自己的实现;下载驱动程序并查看 src / test / com / mongodb /gridfs/GridFSTest.java
;)
For storing binary data like images you can use GridFS or implement your own realization; Download the driver and look at src/test/com/mongodb/gridfs/GridFSTest.java
;)
编辑:你今天很幸运!我为你做了完整的代码;)享受!
you are lucky today! I made complete code for you;) Enjoy!
package mongodb.testing.java;
import com.mongodb.*;
import com.mongodb.gridfs.*;
import java.io.*;
public class Main {
public static byte[] LoadImage(String filePath) throws Exception {
File file = new File(filePath);
int size = (int)file.length();
byte[] buffer = new byte[size];
FileInputStream in = new FileInputStream(file);
in.read(buffer);
in.close();
return buffer;
}
public static void main(String[] args) throws Exception {
//Load our image
byte[] imageBytes = LoadImage("C:/Temp/bear.bmp");
//Connect to database
Mongo mongo = new Mongo( "127.0.0.1" );
String dbName = "GridFSTestJava";
DB db = mongo.getDB( dbName );
//Create GridFS object
GridFS fs = new GridFS( db );
//Save image into database
GridFSInputFile in = fs.createFile( imageBytes );
in.save();
//Find saved image
GridFSDBFile out = fs.findOne( new BasicDBObject( "_id" , in.getId() ) );
//Save loaded image from database into new image file
FileOutputStream outputImage = new FileOutputStream("C:/Temp/bearCopy.bmp");
out.writeTo( outputImage );
outputImage.close();
}
}
这篇关于如何使用java在mongoDB中插入图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文