使用意图与Glide库共享图像 - 图像始终为空

问题描述:

我有一个自定义的listview工作良好,现在我想分享图像和文本从列表中。我发现了一个如何从SO完成的步骤,但当点击“共享”按钮时,图像始终为空。使用意图与Glide库共享图像 - 图像始终为空

使用Glide的imageview加载图像。

if (!Patterns.WEB_URL.matcher(Limage).matches()) { 
viewholder.iview.setVisibility(View.GONE); 
} else { 
Glide.with(convertView.getContext()).load(Limage).centerCrop() 
.diskCacheStrategy(DiskCacheStrategy.ALL).listener(new RequestListener<String, GlideDrawable>() { 
          @Override 
          public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) { 
           return false; 
          } 

          @Override 
          public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) { 

          // viewholder.progress.setVisibility(View.GONE); 
           return false; 
          } 
         }).into(viewholder.iview); 
      viewholder.iview.setVisibility(View.VISIBLE); 
     } 

我已经创建了一个共享按钮,并在里面onclick我传递下面的代码。

viewholder.share.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Uri bmpUri = getLocalBitmapUri(viewholder.iview); 
       if (bmpUri != null) { 
        // Construct a ShareIntent with link to image 
        Intent shareIntent = new Intent(); 
        shareIntent.setAction(Intent.ACTION_SEND); 
        shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri); 
        shareIntent.setType("image/*"); 
        // Launch sharing dialog for image 
        listdisplay.startActivity(Intent.createChooser(shareIntent, "Share Image")); 

       } else { 
        // ...sharing failed, handle error 
       } 

      } 
     }); 

要从Imageview中获取图像,我使用下面的代码。

private Uri getLocalBitmapUri(ImageView iview) { 
     Drawable drawable = iview.getDrawable(); 
     Bitmap bmp = null; 
     if (drawable instanceof BitmapDrawable){ 

      bmp = ((BitmapDrawable) iview.getDrawable()).getBitmap(); 

       Log.e("Shiva","Came inside drawable"); 
     } else { 
      Log.e("Shiva","drawable is null"+drawable); 
      return null; 

     } 

     Uri bmpUri = null; 

     File file = new File(listdisplay.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png"); 
     FileOutputStream out = null; 
     try { 
      out = new FileOutputStream(file); 
      bmp.compress(Bitmap.CompressFormat.PNG, 90, out); 
      out.close(); 
      bmpUri = Uri.fromFile(file); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     // **Warning:** This will fail for API >= 24, use a FileProvider as shown below instead. 

    return bmpUri; 

    } 

因此,现在发生的事情是在if步骤中检查“drawable instanceof BitmapDrawable”总是返回null。这里有什么不对? 注意:以上代码位于适配器内部。

使用Glide时,iview.getDrawable()将返回null。 您可以设置:

public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) { 
       viewholder.iview.setDrawable(resource); 
       return true; 
      } 

然后iview.getDrawable()将返回绘制

+0

没有工作。我得到空drawable是null。我记录了我在Andriod中监视[email protected]d2的drawable。 – user2269164

+1

尝试添加.load(Limage).asBitmap() – John

+1

或使用此((GlideBitmapDrawable)view.getDrawable()。getCurrent())。getBitmap() – John

// Pass the Activity Context, ImageView, Image path which is located inside sdcard,And default Image you want to display to 
loadImageWithGlide Method. 

loadImageWithGlide(this,imageView,imagePath,R.drawable.damaged_image,R.drawable.damaged_image); 


// Method to Load Image from Sdcard to ImageView With Using Glide Library 
public static void loadImageWithGlide(final Context context, ImageView theImageViewToLoadImage, 
              String theLoadImagePath, int theDefaultImagePath, int tehErrorImagePath) { 
     if (context == null) return; 

     Glide.with(context) //passing context 
       .load(theLoadImagePath) //passing your url to load image. 
       .placeholder(theDefaultImagePath) //this would be your default image (like default profile or logo etc). it would be loaded at initial time and it will replace with your loaded image once glide successfully load image using url. 
       .error(tehErrorImagePath)//in case of any glide exception or not able to download then this image will be appear . if you won't mention this error() then nothing to worry placeHolder image would be remain as it is. 
       .diskCacheStrategy(DiskCacheStrategy.ALL) //using to load into cache then second time it will load fast. 
       //.animate(R.anim.fade_in) // when image (url) will be loaded by glide then this face in animation help to replace url image in the place of placeHolder (default) image. 
       .fitCenter()//this method help to fit image into center of your ImageView 
       .into(theImageViewToLoadImage); //pass imageView reference to appear the image. 

    } 


// Bellow is Code to share Image 
// Note: The image needed to located inside Sdcard. Pass that path inside Share Method. 

public static void share(Context theCtx, String theImagePath, String theText) { 
     File myImageFile = new File(theImagePath); 
     String shareBody = theText; //"Here is the share content body " ; 
     Intent sharingIntent = new Intent(Intent.ACTION_SEND); 
     if (myImageFile.exists()) { 
      sharingIntent.setType("image/jpeg"); 
      sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + myImageFile.getAbsolutePath())); 
     } else if (!theText.isEmpty()) { 
      sharingIntent.setType("text/*"); 
     } 
     sharingIntent.putExtra(Intent.EXTRA_SUBJECT, ""); //"Subject here" 
     sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody); 
     sharingIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); 
     theCtx.startActivity(Intent.createChooser(sharingIntent, "Share via")); 
    } 

您需要创建与你的形象不是你可以提取它的内存高速缓存,否则为空,可被销毁。

imageView.setDrawingCacheEnabled(true); 
imageView.buildDrawingCache(); 
Bitmap bitmap = imageView.getDrawingCache(); 
+2

请解释为什么这会起作用,以便其他人可以从你的贡献中学习。谢谢。 –

+0

它工作吗? @ user465139 –

+0

很好,谢谢你的编辑。 –

您可以使用此加载图像:

Glide.with(this) 
      .load("https://cdn-images-1.medium.com/max/1200/1*hcfIq_37pabmAOnw3rhvGA.png") 
      .asBitmap() 
      .diskCacheStrategy(DiskCacheStrategy.SOURCE) 
      .into(new SimpleTarget<Bitmap>() { 
       @Override 
       public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { 
        Log.d("Size ", "width :"+resource.getWidth() + " height :"+resource.getHeight()); 
        imageView.setImageBitmap(resource); 
        storeImage(resource); 
       } 
      }); 

和存储位图到外部存储设备,然后分享它。

private void storeImage(Bitmap image) { 
     File pictureFile = getOutputMediaFile(); 
     if (pictureFile == null) { 
      Log.d(TAG, 
        "Error creating media file, check storage permissions: ");// e.getMessage()); 
      return; 
     } 
     try { 
      FileOutputStream fos = new FileOutputStream(pictureFile); 
      image.compress(Bitmap.CompressFormat.PNG, 90, fos); 
      fos.close(); 
      Log.d(TAG, "img dir: " + pictureFile); 
     } catch (FileNotFoundException e) { 
      Log.d(TAG, "File not found: " + e.getMessage()); 
     } catch (IOException e) { 
      Log.d(TAG, "Error accessing file: " + e.getMessage()); 
     } 
    } 


private File getOutputMediaFile(){ 
    // To be safe, you should check that the SDCard is mounted 
    // using Environment.getExternalStorageState() before doing this. 
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory() 
      + "/Android/data/" 
      + getApplicationContext().getPackageName() 
      + "/Files"); 

    if (! mediaStorageDir.exists()){ 
     if (! mediaStorageDir.mkdirs()){ 
      return null; 
     } 
    } 

    File mediaFile; 
    Random generator = new Random(); 
    int n = 1000; 
    n = generator.nextInt(n); 
    String mImageName = "Image-"+ n +".jpg"; 

    mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName); 
    return mediaFile; 
}