【问题标题】:android share image from urlandroid从url分享图片
【发布时间】:2013-04-30 13:20:35
【问题描述】:

我想使用代码分享一张图片:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri imageUri = Uri.parse("http://stacktoheap.com/images/stackoverflow.png");
sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(sharingIntent);

我做了一个按钮来调用上面的代码。共享意图打开,但如果我单击“通过彩信共享”,我得到了:“无法将此图片添加到您的消息中”。如果 Facebook 我只有一个没有我的图片的文本区域。

【问题讨论】:

    标签: android share


    【解决方案1】:

    不需要使用 ImageView 的 @eclass 答案的改编版本:

    使用Picasso 将网址加载到位图中

    public void shareItem(String url) {
        Picasso.with(getApplicationContext()).load(url).into(new Target() {
            @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setType("image/*");
                i.putExtra(Intent.EXTRA_STREAM, getLocalBitmapUri(bitmap));
                startActivity(Intent.createChooser(i, "Share Image"));
            }
            @Override public void onBitmapFailed(Drawable errorDrawable) { }
            @Override public void onPrepareLoad(Drawable placeHolderDrawable) { }
        });
    }
    

    将位图转换为 Uri

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

    【讨论】:

    • 知道了.. getExternalFilesDir 是一个上下文方法,所以如果你想在某个适配器类中使用它,只需从构造函数中的基类获取上下文并像这样使用它_context.getExternalFilesDir().. 谢谢。
    • 2 个小注意事项:您可能希望将 getLocalBitmapUri 放在线程中以防保存更大的图像压缩 png 将忽略 90 的质量级别。
    • 大图需要更多时间。有什么办法可以缩短这个时间吗?
    • 在你的“shareItem”方法中,每个覆盖都会出现以下错误:方法不会从它的超类覆盖
    • bmpUri 应该是FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
    【解决方案2】:

    我使用来自this tutorial的这些代码

            final ImageView imgview= (ImageView)findViewById(R.id.feedImage1);
    
                    Uri bmpUri = getLocalBitmapUri(imgview);
                    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
                        startActivity(Intent.createChooser(shareIntent, "Share Image"));    
                    } else {
                        // ...sharing failed, handle error
                    }
    

    然后将其添加到您的活动中

     public Uri getLocalBitmapUri(ImageView imageView) {
        // Extract Bitmap from ImageView drawable
        Drawable drawable = imageView.getDrawable();
        Bitmap bmp = null;
        if (drawable instanceof BitmapDrawable){
           bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
        } else {
           return null;
        }
        // Store image to default external storage directory
        Uri bmpUri = null;
        try {
            File file =  new File(Environment.getExternalStoragePublicDirectory(  
                Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
            file.getParentFile().mkdirs();
            FileOutputStream out = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.close();
            bmpUri = Uri.fromFile(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bmpUri;
    }
    

    然后添加您的应用程序清单

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    

    【讨论】:

    • 如果您允许写入,是否还需要请求读取权限?
    • @Lion789 不,其中一个就足够了。事实上,如果你使用Context.getExternalFilesDir(),你不需要权限:)
    【解决方案3】:

    您需要使用本地文件。像这样:

          Uri imageUri = Uri.parse("android.resource://your.package/drawable/fileName");
          Intent intent = new Intent(Intent.ACTION_SEND);
          intent.setType("image/png");
    
          intent.putExtra(Intent.EXTRA_STREAM, imageUri);
          startActivity(Intent.createChooser(intent , "Share"));
    

    如果您的图像在远程服务器上,请先将其下载到设备。

    【讨论】:

    • 如何使用下载的文件进行分享?
    • @CoderPhp 你得到了他的 Uri 路径。 here 是一个关于如何做的教程
    【解决方案4】:

    试试这个:

    new OmegaIntentBuilder(context)
                    .share()
                    .filesUrls("http://stacktoheap.com/images/stackoverflow.png")
                    .download(new DownloadCallback() {
                        @Override
                        public void onDownloaded(boolean success, @NotNull ContextIntentHandler contextIntentHandler) {
                            contextIntentHandler.startActivity();
                        }
                    });
    

    https://github.com/Omega-R/OmegaIntentBuilder

    【讨论】:

    • 很棒的库,但是如果你想让所有可用的应用程序显示在选择器意图中,你需要指定: contextIntentHandler.getIntent().type = MimeTypes.IMAGE_JPEG // 或 PNG,基于您的需求
    【解决方案5】:

    经过大量思考,这是我发现为我工作的代码!我认为这是使用毕加索完成给定任务的最简单的代码版本之一。无需创建 ImageView 对象。

                Target target = new Target() {
                @Override
                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                    bmp = bitmap;
                    String path = MediaStore.Images.Media.insertImage(getContentResolver(), bmp, "SomeText", null);
                    Log.d("Path", path);
                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.putExtra(Intent.EXTRA_TEXT, "Hey view/download this image");
                    Uri screenshotUri = Uri.parse(path);
                    intent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
                    intent.setType("image/*");
                    startActivity(Intent.createChooser(intent, "Share image via..."));
                }
    
                @Override
                public void onBitmapFailed(Drawable errorDrawable) {
    
                }
    
                @Override
                public void onPrepareLoad(Drawable placeHolderDrawable) {
    
                }
            };
            String url = "http://efdreams.com/data_images/dreams/face/face-03.jpg";
            Picasso.with(getApplicationContext()).load(url).into(target);
    

    在这里,bmp 是一个类级别的位图变量,而 url 将是用于共享的图像的动态 Internet url。此外,除了将要共享的代码保留在 onBitmapLoaded() 函数中,它还可以保留在另一个处理函数中,然后从 onBitmapLoaded() 函数中调用。希望这会有所帮助!

    【讨论】:

    • 兄弟,你成就了我的一天!感谢它为我所做的工作。
    【解决方案6】:

    首先您需要在滑行中加载图像。然后,您可以将其分享到任何地方。 从 glide 加载图像的代码(图像正在保存到存储中,您可以稍后将其删除)。

    Glide.with(getApplicationContext())
     .load(imagelink)\\ link of your image file(url)
     .asBitmap().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)
    
     .into(new SimpleTarget < Bitmap > (250, 250) {
      @Override
      public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
    
    
       Intent intent = new Intent(Intent.ACTION_SEND);
       intent.putExtra(Intent.EXTRA_TEXT, "Hey view/download this image");
       String path = MediaStore.Images.Media.insertImage(getContentResolver(), resource, "", null);
       Log.i("quoteswahttodo", "is onresoursereddy" + path);
    
       Uri screenshotUri = Uri.parse(path);
    
       Log.i("quoteswahttodo", "is onresoursereddy" + screenshotUri);
    
       intent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
       intent.setType("image/*");
    
       startActivity(Intent.createChooser(intent, "Share image via..."));
      }
    
      @Override
      public void onLoadFailed(Exception e, Drawable errorDrawable) {
       Toast.makeText(getApplicationContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
    
    
       super.onLoadFailed(e, errorDrawable);
      }
    
      @Override
      public void onLoadStarted(Drawable placeholder) {
       Toast.makeText(getApplicationContext(), "Starting", Toast.LENGTH_SHORT).show();
    
       super.onLoadStarted(placeholder);
      }
     });
    

    【讨论】:

      【解决方案7】:
         share.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
      
                  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                      int permissionCheck = ContextCompat.checkSelfPermission(SingleProduct.this,
                              Manifest.permission.READ_EXTERNAL_STORAGE);
      
                      if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                          Log.e("MainActivity ", "P granted");
      
                          bmpUri = getLocalBitmapUri(imageView);
      
                      } else {
                          ActivityCompat.requestPermissions(SingleProduct.this,
                                  new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                      }
                  } else {
                      Log.e("MainActivity", "Lower Than MarshMallow");
                      bmpUri = getLocalBitmapUri(imageView);
                  }
      
                  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.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                      shareIntent.setType("image/*");
                      startActivity(Intent.createChooser(shareIntent, "Share Image"));
                  } else {
                      Toast.makeText(SingleProduct.this, "Sharing Failed !!", Toast.LENGTH_SHORT).show();
                  }
              }
          });
      

       public Uri getLocalBitmapUri(ImageView imageView) {
          Drawable drawable = imageView.getDrawable();
          Bitmap bmp = null;
          if (drawable instanceof BitmapDrawable) {
              bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
          } else {
              return null;
          }
          Uri bmpUri = null;
          try {
              File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png");
              FileOutputStream out = new FileOutputStream(file);
              bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
              out.close();
      
             bmpUri = Uri.fromFile(file);
      
      
          } catch (IOException e) {
              e.printStackTrace();
          }
          return bmpUri;
      }
      

      //for oreo add below code in manifest under application tag
      
       <provider
              android:name=".utility.GenericFileProvider"
              android:authorities="${applicationId}.your package 
           name.utility.GenericFileProvider"
              android:exported="false"
              android:grantUriPermissions="true">
              <meta-data
                  android:name="android.support.FILE_PROVIDER_PATHS"
                  android:resource="@xml/provider_paths" />
          </provider>
      

      create class that extends FileProvider
      
      public class MyFileProvider extends FileProvider {
      
      }
      

      for oreo add this code
      
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                  bmpUri = FileProvider.getUriForFile(this, 
            this.getApplicationContext().getPackageName() + 
          ".your package name.GenericFileProvider", file);
              } else {
                  bmpUri = Uri.fromFile(file);
              }
      

      finally add provider_paths.xml in res/xml 
      
         <paths xmlns:android="http://schemas.android.com/apk/res/android">
         <external-path name="external_files" path="."/>
         </paths>
      

      就是这样

      【讨论】:

      • 嗨,我试过了,但出现错误:无法找到包含 /file:/storage/emulated/0/Pictures/Screenshots/MyScreenshot.jpg 的已配置根目录主意?已经坚持了几个小时了:(
      【解决方案8】:

      在这里,我使用 asyncTask 将 url 转换为 imageView 并将其存储到位图中。 不要忘记在清单中添加互联网权限。

      public class MainActivity extends AppCompatActivity  {
      
          @SuppressLint("WrongThread")
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              Button iv1 = findViewById(R.id.shreimage);
              final ImageView imgview= (ImageView)findViewById(R.id.content_image);
              new DownloadImageTask(imgview).execute("https://sample-videos.com/img/Sample-jpg-image-50kb.jpg");
              iv1.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View view) {
                      Drawable myDrawable = imgview.getDrawable();
                      Bitmap bitmap = ((BitmapDrawable)myDrawable).getBitmap();
                      try{
                          File file = new File(MainActivity.this.getExternalCacheDir(),"myImage.jpeg");
                          FileOutputStream fout = new FileOutputStream(file);
                          bitmap.compress(Bitmap.CompressFormat.JPEG,80,fout);
                          fout.flush();
                          fout.close();
                          file.setReadable(true,false);
                          Intent intent = new Intent(Intent.ACTION_SEND);
                          intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                          intent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(file));
                          intent.setType("image/*");
                          startActivity(Intent.createChooser(intent,"Share Image Via"));
                      }catch (FileNotFoundException e){
                          e.printStackTrace();
                          Toast.makeText(MainActivity.this,"File Nott Found",Toast.LENGTH_SHORT).show();
                      }catch (IOException e){
                          e.printStackTrace();
                      }catch (Exception e){
                          e.printStackTrace();
                      }
                  }
              });
      
           }
      
      
          private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
              ImageView bmImage;
      
              public DownloadImageTask(ImageView bmImage) {
                  this.bmImage = bmImage;
              }
      
              protected Bitmap doInBackground(String... urls) {
                  String urldisplay = urls[0];
                  Bitmap mIcon11 = null;
                  try {
                      InputStream in = new java.net.URL(urldisplay).openStream();
                      mIcon11 = BitmapFactory.decodeStream(in);
                  } catch (Exception e) {
                      Log.e("Error", e.getMessage());
                      e.printStackTrace();
                  }
                  return mIcon11;
              }
      
              protected void onPostExecute(Bitmap result) {
                  bmImage.setImageBitmap(result);
              }
          }
      }
      

      【讨论】:

        【解决方案9】:
        Picasso.with(applicationContext).load(url).into(object : Target {
                    override fun onBitmapLoaded(bitmap: Bitmap, from: Picasso.LoadedFrom?) {
                        val bitmapPath: String =
                            MediaStore.Images.Media.insertImage(contentResolver, bitmap, "ayurved", null)
                        val bitmapUri = Uri.parse(bitmapPath)
                        val shareIntent = Intent(Intent.ACTION_SEND)
                        shareIntent.type = "image/jpeg";
                        shareIntent.putExtra(Intent.EXTRA_STREAM, bitmapUri);
                        startActivity(Intent.createChooser(shareIntent, "ayurved"))
                    }
                    override fun onBitmapFailed(errorDrawable: Drawable?) {}
                    override fun onPrepareLoad(placeHolderDrawable: Drawable?) {}
                })
        

        【讨论】:

        • 虽然这可能会回答问题,但提供有关原因和方式的信息会更有用。
        【解决方案10】:

        通过使用 createchooser 你可以做到这一点,

        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        Uri screenshotUri = Uri.parse(path);
        
        sharingIntent.setType("image/png");
        sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
        startActivity(Intent.createChooser(sharingIntent, "Share image using"));
        

        注册 Intent

        如果您希望在调用此 Intent 时列出您的应用,则必须在 manifest.xml 文件中添加一个 Intent 过滤器

         <intent-filter>
         <action android:name="android.intent.action.SEND" />
         <category android:name="android.intent.category.DEFAULT" />
         <data android:mimeType="image/*" />
         </intent-filter>
        

        【讨论】:

        • 在您的主要活动中
        • 主要活动有动作和类别,我的问题不是那个,我的问题是图片没有附加到分享活动
        • 文件图片 = new File(Uri.parse("android.resource://" + C.PROJECT_PATH + "/drawable/" + R.drawable.icon_to_share).toString()); sharedIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(image));
        猜你喜欢
        • 1970-01-01
        • 2016-12-23
        • 1970-01-01
        • 2023-03-27
        • 2021-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多