如何在Android上的ImageView上设置的应用程序上共享图像 [英] How to share an image on whats app which is set on an ImageView in android

查看:107
本文介绍了如何在Android上的ImageView上设置的应用程序上共享图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有一个在imageview上设置的图像(通过互联网下载)。我通过json获取此图像。

I have an image(downloaded via internet) set on an imageview in my code. I am gettting this image via json.

我想在什么应用程序上共享此图像,但我不知道文件名或其路径。

I want to share this image on whats app, but i do not know the file name or its path.

我试过这段代码

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

但是当你看到传递文件路径时,我不知道文件路径或文件名。

But as you see it is passing a filepath, i do not know the filepath nor the file name.

无论如何,我可以从ImageView获取图像并通过<$共享它c $ c> share.putExtra ....

因为我可以通过什么应用轻松分享文字。

as i am able to share text easily by whats app.

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

I am specific of getting the image from ImageView approach as it satisfies my requirement, not by getting image by file pathname.

My jsonfetcher

My jsonfetcher

public class DownloadJSON extends AsyncTask {
// private final ProgressDialog progressDialog;

public class DownloadJSON extends 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);


}

}

然后我就是这样设置的。

Then this is how i am setting it.

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

ImageLoader类(我如何下载图像的方法)

ImageLoader class(Method to how i am downloading images)

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();
    }

}


推荐答案

好的,所以经过大量的点击和试用以及谷歌搜索后我发现了一个解决方案,但事实证明我必须保存图像,这是最好的程序,但我的这个答案将消除命名的麻烦,你只需要给出一个默认名称。

Ok, so after a lot of hit and trial and googling i found out a solution, it turns out i have to save the image anyhow, that is the best procedure, but my this answer will take out the hassle of naming, you just need to give a default name.

   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语句。

There will be a lot of try and catch statements.

默认的共享类型是什么应用

这篇关于如何在Android上的ImageView上设置的应用程序上共享图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆