2017-03-27 68 views
2

我有一個自定義的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。這裏有什麼不對? 注意:以上代碼位於適配器內部。

回答

0

使用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

0
// 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")); 
    } 
0

您需要創建與你的形象不是你可以提取它的內存高速緩存,否則爲空,可被銷燬。

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

請解釋爲什麼這會起作用,以便其他人可以從你的貢獻中學習。謝謝。 –

+0

它工作嗎? @ user465139 –

+0

很好,謝謝你的編輯。 –

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; 
} 
相關問題