【问题标题】:How to share an image on whats app which is set on an ImageView in android如何在 android 的 ImageView 上设置的什么应用程序上共享图像
【发布时间】:2015-07-20 02:38:53
【问题描述】:

我在我的代码中的图像视图上设置了一个图像(通过互联网下载)。我通过 json 获取这张图片。

我想在 whats 应用程序上分享这张图片,但我不知道文件名或其路径。

我试过这个代码

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 应用轻松分享文本。

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

我的 jsonfetcher

公共类 DownloadJSON 扩展 AsyncTask { // 私有最终 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();
    }

}

【问题讨论】:

    标签: android image imageview


    【解决方案1】:

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

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

    默认分享类型是whats app

    【讨论】:

    • @MayankSugandhi 如果是这样,那么请投票给答案:-D
    • :- 我已经为你的答案投了赞成票,兄弟。不幸的是,你的答案降到了-1 ..在我投了赞成票后,现在是 0..
    【解决方案2】:

    通过在将图像分配给 ImageView 之前将图像的本地副本保存到 sdcard,您可以共享它。

    关于用于将图像从 JSON 设置为 ImageView 的代码,您能否再详细一点?

    [如果提供数据,我将编辑此答案。]

    【讨论】:

    • 嗨 surya,我可以保存图像文件,但在这里我有大约 1000 张具有不同名称格式的图像,即使我保存我也无法以编程方式写入每个文件的名称,所以我只是想要获取图像并将其设置在图像视图中,感谢您的回复:-)
    • 在这种情况下,您可以编辑问题并添加实际的 JSON 输出以及用于将图像设置为 ImageView 的确切代码吗?我是 JSON 和 Android 通信的初学者。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    • 1970-01-01
    相关资源
    最近更新 更多