如果要将图像存储在数据库中,则必须先下载图像,然后将其转换为位图,然后再转换为字节数组。从数据库中获取时,必须遵循相同的反向过程。
or
您可以将图像作为 BLOB 存储在数据库中
public static byte[] urlToImageBLOB(String url) throws IOException {
httpclient = new DefaultHttpClient();
entity = null;
httpGet = new HttpGet(url);
response = httpclient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
entity = response.getEntity();
}
return EntityUtils.toByteArray(entity);
}
现在您需要获取图像
public static Bitmap getImageFromBLOB(byte[] mBlob) {
byte[] bb = mBlob;
return BitmapFactory.decodeByteArray(bb, 0, bb.length);
}
设置图像
imageView.setImageBitmap(getImageFromBLOB(cursor.getBlob(object.getColumnIndex("book_thumb"))));
或者
你也可以使用 Handler 来完成任务
protected Drawable Imagehandler(String url) {
try {
url=url.replaceAll(" ", "%20");
InputStream is = (InputStream)this.fetch(url);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e)
{
System.out.println(url);
System.out.println("error at URI"+e);
return null;
}
catch (IOException e)
{
System.out.println("io exception: "+e);
System.out.println("Image NOT FOUND");
return null;
}
}
protected Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
这将在运行时将您的 imageUrl 转换为 Drawble,然后将 Drawble 设置为 Gallery 的 Imageview