1、把图片转换为字节
private byte[]img(Bitmap bitmap){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}2、把图片存储到数据库
假设获取的图片为bitmap,数据库有一张User表,存储的属性为byte[]headshot
public class User extends DataSupport {
private byte[] headshot;//头像
public User(){
super();
}
public User(byte[]headshot){
super();
this.headshot=headshot;
}
public byte[] getHeadshot() {
return headshot;
}
public void setHeadshot(byte[] headshot) {
this.headshot = headshot;
}
}对图片进行保存
//获取到图片 Bitmap headShot=BitmapFactory.decodeFile(imagePath); //把图片转换字节流 byte[]images=img(headShot); //找到用户 User users=DataSupport.findFirst(User.class); //保存 users.setHeadshot(images); users.save();
4、获取图片
User mUser=DataSupport.findFrist(User.class); byte[]images=mUser.getHeadshot(); Bitmap bitmap=BitmapFactory.decodeByteArray(images,0,images.length);