android室获取blob图片并显示

时间:2018-10-08 11:41:15

标签: android database image blob android-room

我正在使用Room持久性库以Blob格式存储图像。

@Entity(tableName = AppConstants.TABLE_OBSERVATIONS_IMAGE)
public class ImageModel {

    @ColumnInfo(typeAffinity = ColumnInfo.BLOB)
    public byte[] image;

    public ImageModel() {
    }

    @Ignore
    public ImageModel(  byte[] image ) {
         this.image = image;
        }

   public byte[] getImage() {
        return image;
    }

    public void setImage(byte[] image) {
        this.image = image;
    }

}

现在,我想获取它并在图像视图中显示它。但这给了例外。我正在使用以下代码显示图像,其中model.getImage()是我存储的图像。但这会返回空位图,并导致应用崩溃。

ImageModel model = observationModelArrayList.get(position).getImageModels().get(i);
ImageView image = new ImageView(context);
image.setLayoutParams(new android.view.ViewGroup.LayoutParams(100, 100));
image.setMaxHeight(100);
image.setMaxWidth(100);

Bitmap bmp = BitmapFactory.decodeByteArray(model.getImage(), 0, model.getImage().length);
//ImageView image = (ImageView) findViewById(R.id.imageView1);

image.setImageBitmap(Bitmap.createScaledBitmap(bmp, image.getWidth(), image.getHeight(), false));

// Adds the view to the layout
holder.llayImages.addView(image);

请帮助。

1 个答案:

答案 0 :(得分:2)

您可以将图像存储在内部存储器中,因为它不需要存储权限即可加载可以使用的图像

private void loadImage(String path){
  try {
    File file = new File(path, "profile.jpg");
    Bitmap b = BitmapFactory.decodeStream(new FileInputStream(file));
        ImageView img=(ImageView)findViewById(R.id.imgPicker);
    img.setImageBitmap(b); // it will display the image in imageview
    String file_path = saveToInternalStorage(b); // store this file_path in db 
  } catch (FileNotFoundException e) {
    e.printStackTrace();
  }
}

要从服务器加载图像,您可以使用类似的滑动库

GlideApp.with(context)
    .asBitmap()
    .load(url)
    .into(new SimpleTarget<Bitmap>() {
      @Override public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
        String file_path = saveToInternalStorage(resource);  // store the bitmap
        // save this file_path to your db
      }
    });

要保存图像,可以使用此方法

private String saveToInternalStorage(Bitmap bitmapImage){
    ContextWrapper cw = new ContextWrapper(getApplicationContext());
     // path to /data/data/yourapp/app_data/imageDir
    File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
    // Create imageDir
    File mypath=new File(directory,"profile.jpg");

    FileOutputStream fos = null;
    try {           
        fos = new FileOutputStream(mypath);
   // Use the compress method on the BitMap object to write image to the OutputStream
        bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
    } catch (Exception e) {
          e.printStackTrace();
    } finally {
        try {
          fos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
    } 
    return mypath.getAbsolutePath();
}

要加载位图,可以使用glide从glide获取位图,并使用save方法存储位图。将图像文件保存在内部存储中后,将路径保存到数据库中,希望对您有帮助...