繁体   English   中英

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

[英]Sharing image using intent with Glide library- Image is null always

我有一个自定义列表视图工作正常,现在我想分享列表中的图像和文本。 我已经从SO中找到了一个步骤,但是当我点击“共享”按钮时,图像始终为空。

使用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);
        }

我创建了一个Share按钮,在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.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;
} 

使用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()将返回drawable

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

你需要在内存中使用你的图像创建缓存,而不是提取它,否则为null,可能会被破坏。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM