android - 如何在 Android 中的 ImageView 上设置的 whatsapp 上共享图像

标签 android image imageview

我在代码中的 ImageView 上设置了图像(通过互联网下载)。我正在通过 json 获取此图像。

我想在 whats app 上分享这张图片,但我不知道文件名或它的路径。

我试过这段代码

Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("image/*");
    share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(root.getAbsolutePath() + "/DCIM/Camera/image.jpg"));
    startActivity(Intent.createChooser(share,"Share via"));

但是如您所见,它传递的是文件路径,我不知道文件路径和文件名。

有没有可能我可以从 ImageView 获取图像并通过 share.putExtra.... 共享它?

因为我可以通过 whats app 轻松分享文本。

我特别指出从 ImageView 方法获取图像,因为它满足我的要求,而不是通过文件路径名获取图像。

我的jsonfetcher

公共(public)类 DownloadJSON 扩展 AsyncTask { //private final ProgressDialog progressDialog;

@Override

protected void onPreExecute() {
    super.onPreExecute();
    pd = new ProgressDialog(CanadaJson.this);
    pd.setTitle("Getting the dishes from our Server Cookers");
    pd.setMessage("The waiter is getting the menu...");
    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

    pd.setIndeterminate(true);
    pd.setCancelable(false);
    pd.show();
}
@Override
protected Void doInBackground(Void... params) {

    // Create an array
    arraylist = new ArrayList<HashMap<String, String>>();
    // Retrieve JSON Objects from the given URL

        jsonobject = JSONfunctions.getJSONfromURL("https://lit-hamlet-6856.herokuapp.com/eventsList/TECHNICAL");
    Log.d("Json Code",jsonobject.toString());


    try {
        // Locate the array name in JSON
        jsonarray = jsonobject.getJSONArray("events");

        for (int i = 0; i < jsonarray.length(); i++) {
            HashMap<String, String> map = new HashMap<String, String>();
            jsonobject = jsonarray.getJSONObject(i);
            // Retrive JSON Objects
            map.put("Name", jsonobject.getString("Name"));
            map.put("Time", jsonobject.getString("Time"));
            map.put("Serves", jsonobject.getString("Serves"));
            map.put("ingredients", jsonobject.getString("ingredients"));
            map.put("Description",jsonobject.getString("Description"));
            // Set the JSON Objects into the array
            arraylist.add(map);
        }

    } catch (JSONException e) {
        Log.e("Error", e.getMessage());

        e.printStackTrace();
    }
    return null;

}
@Override
protected void onPostExecute(Void args) {
    // Locate the listview in listview_main.xml
    //setContentView(R.layout.listview_main);
    listview = (ListView) findViewById(R.id.listview);
    // Pass the results into ListViewAdapter.java
    adapter = new ListViewAdapter(CanadaJson.this, arraylist);
    // Set the adapter to the ListView
    listview.setAdapter(adapter);
    // Close the progressdialog
    pd.dismiss();

 //   textView.setVisibility(View.VISIBLE);

   // mProgressDialog.dismiss();
    super.onPostExecute(args);


}

那么我就是这样设置的。

imageLoader.DisplayImage(resultp.get(FirstActivity.ingredients), flag);

ImageLoader 类(下载图片的方法)

public class ImageLoader {

    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService;
    // Handler to display images in UI thread
    Handler handler = new Handler();

    public ImageLoader(Context context) {
        fileCache = new FileCache(context);
        executorService = Executors.newFixedThreadPool(5);
    }

    final int stub_id = R.drawable.icon;

    public void DisplayImage(String url, ImageView imageView) {
        imageViews.put(imageView, url);
        Bitmap bitmap = memoryCache.get(url);
        if (bitmap != null)
            imageView.setImageBitmap(bitmap);
        else {
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id);
        }
    }

    private void queuePhoto(String url, ImageView imageView) {
        PhotoToLoad p = new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }

    private Bitmap getBitmap(String url) {
        File f = fileCache.getFile(url);

        Bitmap b = decodeFile(f);
        if (b != null)
            return b;

        // Download Images from the Internet
        try {
            Bitmap bitmap = null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is = conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            conn.disconnect();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Throwable ex) {
            ex.printStackTrace();
            if (ex instanceof OutOfMemoryError)
                memoryCache.clear();
            return null;
        }
    }

    // Decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f) {
        try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            FileInputStream stream1 = new FileInputStream(f);
            BitmapFactory.decodeStream(stream1, null, o);
            stream1.close();

            // Find the correct scale value. It should be the power of 2.
            // Recommended Size 512
            final int REQUIRED_SIZE = 256;//control quality of images
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE
                        || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            FileInputStream stream2 = new FileInputStream(f);
            Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
            stream2.close();
            return bitmap;
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // Task for the queue
    private class PhotoToLoad {
        public String url;
        public ImageView imageView;

        public PhotoToLoad(String u, ImageView i) {
            url = u;
            imageView = i;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;

        PhotosLoader(PhotoToLoad photoToLoad) {
            this.photoToLoad = photoToLoad;
        }

        @Override
        public void run() {
            try {
                if (imageViewReused(photoToLoad))
                    return;
                Bitmap bmp = getBitmap(photoToLoad.url);
                memoryCache.put(photoToLoad.url, bmp);
                if (imageViewReused(photoToLoad))
                    return;
                BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
                handler.post(bd);
            } catch (Throwable th) {
                th.printStackTrace();
            }
        }
    }

    boolean imageViewReused(PhotoToLoad photoToLoad) {
        String tag = imageViews.get(photoToLoad.imageView);
        if (tag == null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }

    // Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;

        public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
            bitmap = b;
            photoToLoad = p;
        }

        public void run() {
            if (imageViewReused(photoToLoad))
                return;
            if (bitmap != null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }

}

最佳答案

好吧,经过大量的尝试和谷歌搜索,我找到了一个解决方案,事实证明我无论如何都必须保存图像,这是最好的程序,但我的这个答案会消除命名的麻烦,您只需要提供一个默认名称即可。

   fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageView imgflag = (ImageView) findViewById(R.id.flag);
                imgflag.buildDrawingCache();
                Bitmap bm=imgflag.getDrawingCache();

                OutputStream fOut = null;
                Uri outputFileUri;

                try {
                    File root = new File(Environment.getExternalStorageDirectory()
                            + File.separator + "FoodMana" + File.separator);
                    root.mkdirs();
                    File sdImageMainDirectory = new File(root, "myPicName.jpg");
                    outputFileUri = Uri.fromFile(sdImageMainDirectory);
                    fOut = new FileOutputStream(sdImageMainDirectory);
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "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) {
                }


                    PackageManager pm=getPackageManager();
                    try {

                        Toast.makeText(getApplicationContext(), "Sharing Via Whats app !", Toast.LENGTH_LONG).show();
                        Intent waIntent = new Intent(Intent.ACTION_SEND);
                        waIntent.setType("image/*");
                        waIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        PackageInfo info=pm.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA);
                        //Check if package exists or not. If not then code
                        //in catch block will be called
                        waIntent.setPackage("com.whatsapp");
                        waIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory()
                                + File.separator + "FoodMana" + File.separator+"myPicName.jpg"));
                        waIntent.putExtra(Intent.EXTRA_TEXT, txtrank.getText().toString() + "\n" + txtcountry.getText()+"\n"+
                                txtpopulation.getText()+"\n"+desc.getText());
                        startActivity(Intent.createChooser(waIntent, "Share with"));

                    } catch (PackageManager.NameNotFoundException e) {
                        Toast.makeText(SingleItemView.this, "WhatsApp not Installed", Toast.LENGTH_SHORT).show();

                        Intent emailIntent = new Intent(Intent.ACTION_SEND);
                        emailIntent.setData(Uri.parse("mailto:"));
                        emailIntent.setType("text/html");
                        emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your ward's academic details are here");
                        emailIntent.putExtra(Intent.EXTRA_TEXT, "Please find the details attached....");
                        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "\n\n" + txtrank.getText().toString() + "\n" + txtcountry.getText()+"\n"+
                                txtpopulation.getText()+"\n"+desc.getText());
                        startActivity(emailIntent);
                        try {
                            startActivity(Intent.createChooser(emailIntent, "Send mail..."));
                            finish();
                            Log.i("Finished Data", "");
                        } catch (android.content.ActivityNotFoundException ex) {
                            Toast.makeText(SingleItemView.this,
                                    "No way you can share Reciepies,enjoy alone :-P", Toast.LENGTH_SHORT).show();
                        }

                    }


            }
        });

会有很多try和catch语句。

默认的分享类型是whats app

关于android - 如何在 Android 中的 ImageView 上设置的 whatsapp 上共享图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31502267/

相关文章:

android - 在android屏幕底部添加组件

java - 谷歌电视插件 Android 模拟器低空间通知

android - 为什么 Android 为图像分配的内存是我预期的两倍?

ios - 如何在快速延迟的情况下一一显示 subview

android - 图像拉伸(stretch)

android - 让 Android 模拟器与 iPhone 热点一起工作

不调整图像大小的CSS图像边框翻转效果?

java - 如何在不继承 Swing 的情况下正确地获取 "layer"图像(并更改源)

.net - 有可靠的.NET 图像元数据库吗?

android - 错误 : The class 'SingleTickerProviderStateMixin' can't be used as a mixin because it extends a class other than Object