Android一鍵轉發圖片多張圖片到微信,朋友圈功能實現
阿新 • • 發佈:2019-02-14
效果圖
一鍵轉發按鈕,直接把多張圖片拉起朋友圈,自動填充圖片,或者多張圖片發給好友,文字可以複製過去直接貼上,
實現思路:
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 voidonResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { ImgFileUtils.saveBitmap(PosterXQActivity.this, resource, StringUtils.setDateTime()); } }); }
/**工具類程式碼 * author:zhengfeng on 2017/8/21 10:13 */ public class ImgFileUtils { /** * 生成資料夾路徑 */2.快取圖片的同時把圖片路徑做一個快取,為了拉起朋友圈直接帶過去多張圖片路徑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; } }
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()); } }); }這樣就實現一鍵轉發圖片或者文字到微信或者朋友圈的功能,每一個問題的解決都將讓你前進一步,加油!