如何在imageview中保存图像?

时间:2017-01-09 14:03:41

标签: android

我的应用程序允许您从图库中选择图像并在图像视图中显示它,但当您关闭活动并再次打开它时,图像就不再存在了。

  private final static int RESULT_LOAD_IMAGE = 1;

public void getpic(View view) {
    Intent i = new Intent(
            Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    startActivityForResult(i, RESULT_LOAD_IMAGE);
}




@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String selectedimage = cursor.getString(columnIndex);
        cursor.close();

        ImageView imageView = (ImageView) findViewById(R.id.imageButton3);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setImageBitmap(BitmapFactory.decodeFile(selectedimage));

    }


}

如何保存所选图像?

2 个答案:

答案 0 :(得分:0)

您可以从Bitmap获取ImageView来保存它:

imageview.buildDrawingCache();
Bitmap bm=imageview.getDrawingCache();

OutputStream fOut = null;
Uri outputFileUri;
try {
    File root = new File(Environment.getExternalStorageDirectory()
        + File.separator + "folder_name" + File.separator);
    root.mkdirs();
    File sdImageMainDirectory = new File(root, "myPicName.jpg");
    outputFileUri = Uri.fromFile(sdImageMainDirectory);
    fOut = new FileOutputStream(sdImageMainDirectory);
} catch (Exception e) {
    Toast.makeText(this, "Error occured. Please try again later.",
    Toast.LENGTH_SHORT).show();
}
try {
    bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
    fOut.flush();
    fOut.close();
} catch (Exception e) {
}

答案 1 :(得分:0)

使用Glide加载图片

在build.gradle(app)中添加以下依赖项

compile 'com.github.bumptech.glide:glide:4.2.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.2.0'

在onActivityResult

中添加以下代码
  Glide
  .with(mContext)
  .load(selectedimage)
  .centerCrop()
  .placeholder(R.color.black)
  .crossFade()
  .into(imageView);

有关详细信息,请参阅 https://github.com/bumptech/glide

http://en.proft.me/2016/09/12/load-process-and-cache-image-android-using-glide/

Glide load local image by Uri.

相关问题