如何将图像保存到数据库 [英] How to save images into Database
本文介绍了如何将图像保存到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有一种方法可以将图片(.gif类型)保存到sqllite数据库。如果是,我的 DatabaseAdapter
应该如何。
同样是性能问题吗?
解决方案
您应该在数据库中使用 BLOB
:
检查本教程 ...
但我认为你应该下载和存储图像在HashMap,这将使它更简单。
代码:
Stroring
Map< String,byte []> hh = new HashMap< String,byte []>();
String hi =http://i.stack.imgur.com/TLjuP.jpg;
byte [] logoImagedata = getLogoImage(hi);
hh.put(img,logoImagedata);
检索
byte [] imageByteArray = hh.get(img);
ByteArrayInputStream imageStream = new ByteArrayInputStream(imageByteArray);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
getLogoImage()
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;
}
}
希望它能帮助你。 p>
I'd like to know if there's a way to save Images (of the type .gif) to the sqllite-database. If yes how should my DatabaseAdapter
look like.
Also is there a performance issue?
解决方案
You should use BLOB
in your database:
Check this tutorial...
But I think you should download and store image in HashMap, which will make it simpler.
Code:
Stroring
Map<String, byte[]> hh = new HashMap<String, byte[]>();
String hi = "http://i.stack.imgur.com/TLjuP.jpg";
byte[] logoImagedata = getLogoImage(hi);
hh.put("img",logoImagedata);
Retrieving
byte[] imageByteArray = hh.get("img");
ByteArrayInputStream imageStream = new ByteArrayInputStream(imageByteArray);
Bitmap theImage= BitmapFactory.decodeStream(imageStream);
getLogoImage()
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;
}
}
Hope it helps you.
这篇关于如何将图像保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文