Android一键转发图片多张图片到微信,朋友圈功能实现
效果图
一键转发按钮,直接把多张图片拉起朋友圈,自动填充图片,或者多张图片发给好友,文字可以复制过去直接粘贴,
实现思路:
1.先把接口请求下来的多张图片保存到本地,这里是用Glide做的本地缓存
//缓存图片到本地 for (int i = 0; i < images.size(); i++) { Glide.with(this) .load(images.get(i).getPic_url()).asBitmap().into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { ImgFileUtils.saveBitmap(PosterXQActivity.this, resource, StringUtils.setDateTime()); } }); }
/**工具类代码 * author:zhengfeng on 2017/8/21 10:13 */ public class ImgFileUtils { /** * 生成文件夹路径 */ public static String SDPATH = Environment.getExternalStorageDirectory() + "/WS_IMG/"; public static void saveImageToGallery(Context context, Bitmap bmp) { // 首先保存图片 File appDir = new File(Environment.getExternalStorageDirectory(), "/WS_IMG/"); if (!appDir.exists()) { appDir.mkdir(); } String fileName = System.currentTimeMillis() + ".jpg"; File file = new File(appDir, fileName); try { FileOutputStream fos = new FileOutputStream(file); bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 其次把文件插入到系统图库 try { MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null); } catch (FileNotFoundException e) { e.printStackTrace(); } // 最后通知图库更新 // context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path))); } /** * 将图片压缩保存到文件夹 * * @param bm * @param picName */ public static void saveBitmap(Context context,Bitmap bm, String picName) { try { // 如果没有文件夹就创建一个程序文件夹 if (!isFileExist("")) { File tempf = createSDDir(""); } File f = new File(SDPATH, picName + ".JPEG"); Log.e("filepath",f.getAbsolutePath()); PosterXQImgCache.getInstance().setImgCache(f.getAbsolutePath());//缓存保存后的图片路径 // 如果该文件夹中有同名的文件,就先删除掉原文件 if (f.exists()) { f.delete(); } FileOutputStream out = new FileOutputStream(f); bm.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); Log.e("imgfile", "已经保存"); //保存图片后发送广播通知更新数据库 Uri uri = Uri.fromFile(f); context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 质量压缩 并返回Bitmap * * @param image * 要压缩的图片 * @return 压缩后的图片 */ private Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 int options = 100; while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩 baos.reset();// 重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中 options -= 10;// 每次都减少10 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中 Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片 return bitmap; } /** * 质量压缩 * * @param bitmap * @param picName */ public static void compressImageByQuality(final Bitmap bitmap, String picName) { // 如果没有文件夹就创建一个程序文件夹 if (!isFileExist("")) { try { File tempf = createSDDir(""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } File f = new File(SDPATH, picName + ".JPEG"); // 如果该文件夹中有同名的文件,就先删除掉原文件 if (f.exists()) { f.delete(); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); int options = 100; // 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos); // 循环判断如果压缩后图片是否大于200kb,大于继续压缩 while (baos.toByteArray().length / 1024 > 500) { // 重置baos即让下一次的写入覆盖之前的内容 baos.reset(); // 图片质量每次减少5 options -= 5; // 如果图片质量小于10,则将图片的质量压缩到最小值 if (options < 0) options = 0; // 将压缩后的图片保存到baos中 bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos); // 如果图片的质量已降到最低则,不再进行压缩 if (options == 0) break; } // 将压缩后的图片保存的本地上指定路径中 FileOutputStream fos; try { fos = new FileOutputStream(new File(SDPATH, picName + ".JPEG")); fos.write(baos.toByteArray()); fos.flush(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 创建文件夹 * * @param dirName * 文件夹名称 * @return 文件夹路径 * @throws IOException */ public static File createSDDir(String dirName) throws IOException { File dir = new File(SDPATH + dirName); if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { System.out.println("createSDDir:" + dir.getAbsolutePath()); System.out.println("createSDDir:" + dir.mkdir()); } return dir; } /** * 判断改文件是否是一个标准文件 * * @param fileName * 判断的文件路径 * @return 判断结果 */ public static boolean isFileExist(String fileName) { File file = new File(SDPATH + fileName); file.isFile(); return file.exists(); } /** * 删除指定文件 * * @param fileName */ public static void delFile(String fileName) { File file = new File(SDPATH + fileName); if (file.isFile()) { file.delete(); } file.exists(); } /** * 删除指定文件 * @param file */ public static void deleteFile(File file) { if (file.exists()) { // 判断文件是否存在 if (file.isFile()) { // 判断是否是文件 file.delete(); // delete()方法 你应该知道 是删除的意思; } else if (file.isDirectory()) { // 否则如果它是一个目录 File files[] = file.listFiles(); // 声明目录下所有的文件 files[]; for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件 deleteFile(files[i]); // 把每个文件 用这个方法进行迭代 } } file.delete(); } else { Log.i("TAG", "文件不存在!"); } } /** * 删除指定文件夹中的所有文件 */ public static void deleteDir() { File dir = new File(SDPATH); if (dir == null || !dir.exists() || !dir.isDirectory()) return; for (File file : dir.listFiles()) { if (file.isFile()) file.delete(); else if (file.isDirectory()) deleteDir(); } dir.delete(); } /** * 判断是否存在该文件 * * @param path * 文件路径 * @return */ public static boolean fileIsExists(String path) { try { File f = new File(path); if (!f.exists()) { return false; } } catch (Exception e) { return false; } return true; } }2.缓存图片的同时把图片路径做一个缓存,为了拉起朋友圈直接带过去多张图片路径
public class PosterXQImgCache { private List<String> imgCache = new ArrayList<>();//用于存放保存后的图片路径 private static final PosterXQImgCache instance = new PosterXQImgCache(); public static PosterXQImgCache getInstance() { return instance; } public List<String> getImgCache() { return imgCache; } public void setImgCache(String path) {//传入保存后的图片绝对路径 imgCache.add(path); } public void removeImgCache() {//清空缓存 imgCache.clear(); } }3,一键转发点击事件,直接拿到缓存后的图片路径集合,以Uri数组的形式传入多张图片文件
case R.id.one_tranmit://一键转发 imgCache = PosterXQImgCache.getInstance().getImgCache(); Uri[] uris = new Uri[imgCache.size()];//创建用于存放图片的Uri数组 //循环缓存路径分别生成文件,添加到图片Uri数组中 for (int i = 0; i < imgCache.size(); i++) { uris[i] = Uri.fromFile(new File(imgCache.get(i))); } requestCopy(text);//复制文字内容到粘贴板 //调用转发微信功能类 shareUtils = new ShareUtils(this, text); shareUtils.setUri(uris); break;
package com.derivative.client.util; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.PopupWindow; import com.derivative.client.R; import java.io.File; import java.util.ArrayList; /** * 拉起微信,朋友圈功能类,支持单张图片,多张图片,文字 */ public class ShareUtils { PopupWindow popupWindow; Context context; private String path;//单张图片路径 private String content; private Button btn; private Uri[] uris;//多张图片路径uri数组 public ShareUtils(Context context, String content){ this.context=context; // this.path=path; this.content=content; // this.btn=btn; showpop(); } public void setUri(Uri[] uris){ this.uris = uris; } public void setPath(String path){ this.path = path; } private void showpop() { View view= LayoutInflater.from(context).inflate( R.layout.share_view, null); ImageView img_weixin= (ImageView) view.findViewById(R.id.share_weixin); ImageView img_pyq= (ImageView) view.findViewById(R.id.share_pengyouquan); popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true); popupWindow.setBackgroundDrawable(new BitmapDrawable()); // 点击返回按钮popwindow消失 img_weixin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (StringUtils.isWeixinAvilible(context)) {// 判断是否安装微信客户端 // shareweixin(path); shareWXSomeImg(context,uris); // login(SHARE_MEDIA.WEIXIN); } else { ActivityUtil.showToast(context, "请安装微信客户端"); } popupWindow.dismiss(); } }); img_pyq.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (StringUtils.isWeixinAvilible(context)) {// 判断是否安装微信客户端 // shareweipyq(path,content);//拉起微信朋友圈带一张图片 shareweipyqSomeImg(context,uris);//拉起微信朋友圈带多张图片 // login(SHARE_MEDIA.WEIXIN); } else { ActivityUtil.showToast(context, "请安装微信客户端"); } popupWindow.dismiss(); } }); popupWindow.showAtLocation( LayoutInflater.from(context).inflate( R.layout.activity_posterxq, null).findViewById(R.id.img_share), Gravity.BOTTOM, 0, 0);// 先设置popwindow的所有参数,最后再show } /** * 拉起微信好友发送单张图片 * */ private void shareweixin(String path){ Uri uriToImage = Uri.fromFile(new File(path)); Intent shareIntent = new Intent(); //发送图片到朋友圈 //ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI"); //发送图片给好友。 ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI"); shareIntent.setComponent(comp); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage); shareIntent.setType("image/jpeg"); context.startActivity(Intent.createChooser(shareIntent, "分享图片")); } /** * 拉起微信朋友圈发送单张图片 * */ private void shareweipyq(String path,String content){ Uri uriToImage = Uri.fromFile(new File(path)); Intent shareIntent = new Intent(); //发送图片到朋友圈 ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI"); //发送图片给好友。 // ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI"); shareIntent.setComponent(comp); shareIntent.putExtra("Kdescription", content); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage); shareIntent.setType("image/jpeg"); context.startActivity(Intent.createChooser(shareIntent, "分享图片")); } /** * 拉起微信朋友圈发送多张图片 * */ private void shareweipyqSomeImg(Context context,Uri[] uri){ Intent shareIntent = new Intent(); //1调用系统分析 shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE); shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //2添加图片数组 ArrayList<Uri> imageUris = new ArrayList<>(); for (int i = 0; i < uri.length; i++) { imageUris.add(uri[i]); } shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,imageUris); shareIntent.setType("image/*"); //3指定选择微信 ComponentName componentName = new ComponentName("com.tencent.mm","com.tencent.mm.ui.tools.ShareToTimeLineUI"); shareIntent.setComponent(componentName); //4开始分享 context.startActivity(Intent.createChooser(shareIntent,"分享图片")); } /** * 拉起微信发送多张图片给好友 * */ private void shareWXSomeImg(Context context,Uri[] uri){ Intent shareIntent = new Intent(); //1调用系统分析 shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE); shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //2添加图片数组 ArrayList<Uri> imageUris = new ArrayList<>(); for (int i = 0; i < uri.length; i++) { imageUris.add(uri[i]); } shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,imageUris); shareIntent.setType("image/*"); //3指定选择微信 ComponentName componentName = new ComponentName("com.tencent.mm","com.tencent.mm.ui.tools.ShareImgUI"); shareIntent.setComponent(componentName); //4开始分享 context.startActivity(Intent.createChooser(shareIntent,"分享图片")); } }
4,每次新的页面打开,请求数据回来记得情况把缓存清空,每次只保存新的
PosterXQImgCache.getInstance().removeImgCache();//先清空路径缓存 ImgFileUtils.deleteDir();//删除本地缓存的图片 //缓存图片到本地 for (int i = 0; i < images.size(); i++) { Glide.with(this) .load(images.get(i).getPic_url()).asBitmap().into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { ImgFileUtils.saveBitmap(PosterXQActivity.this, resource, StringUtils.setDateTime()); } }); }这样就实现一键转发图片或者文字到微信或者朋友圈的功能,每一个问题的解决都将让你前进一步,加油!