// data 为Base64的图片格式 private void shareReportToWX(String data){ if(data!= null){ try { /**data 为纯Base64的图片格式 * byte[] imageByte = Base64.decode(data,Base64.DEFAULT); */ // 我自己的项目带有其他数据,截取"," 后面的数据才是Base64图片数据 String[] image = data.split(","); byte[] imageByte = Base64.decode(image[1],Base64.DEFAULT); // 可用其他方法代替 byte[] imageByte 格式转换成Bitmap decodedByte图片 Bitmap decodedByte = BitmapFactory.decodeByteArray(imageByte, 0, imageByte.length); // 首先保存图片 保存路径可以更改 String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "dearxy"; File appDir = new File(storePath); if (!appDir.exists()) { appDir.mkdir(); } String fileName = "share_report.jpg"; File file = new File(appDir, fileName); Log.e("js", "分享日报图片保存路径:" + file.getAbsolutePath()); try { FileOutputStream fos = new FileOutputStream(file); //通过io流的方式来压缩保存图片 boolean isSuccess = decodedByte.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); if(isSuccess){ /** * FileProvider生成的Uri无法被识别, * 分享给微信朋友时提示 获取资源失败 * 代替解决方法 getImageContentUri(context,file); */ //Uri contentUri = CakeFileProvider.getUriForFile(this, com.feinnoui.library.utils.FileUtils.getFileProviderAuthority(this), file);//通过FileProvider创建一个content类型的Uri Uri contentUri = getImageContentUri(this,file); //保存图片后发送广播通知更新数据库 this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, contentUri)); Intent shareIntent = new Intent(); shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM,contentUri); shareIntent.setType("image/*"); startActivity(Intent.createChooser(shareIntent, "分享到")); }else{ ToastUtils.showLongToast(this, "保存图片失败"); } } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } } }
/** * FileProvider生成的Uri无法被识别 */ public Uri getImageContentUri(Context context, File imageFile) { String filePath = imageFile.getAbsolutePath(); Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Images.Media._ID }, MediaStore.Images.Media.DATA + "=? ", new String[] { filePath }, null); Uri uri = null; if (cursor != null) { if (cursor.moveToFirst()) { int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID)); Uri baseUri = Uri.parse("content://media/external/images/media"); uri = Uri.withAppendedPath(baseUri, "" + id); } cursor.close(); } if (uri == null) { ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.DATA, filePath); uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } return uri; } 效果图