Android调用系统的分享来分享网络图片,是不能直接分享网络图片的,需要把图片保存到本地:
// 保存图片
public static void saveBitmap(Bitmap bitmap, String filePath, String fileName) {
File headDir = new File(filePath);
if (!headDir.exists()) {
headDir.mkdirs();
}
FileOutputStream headFos = null;
File headFile = null;
try {
//重命名并保存
headFile = new File(filePath, fileName);
headFile.createNewFile();
headFos = new FileOutputStream(headFile);
bitmap.compress(CompressFormat.JPEG, 100, headFos);
headFos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (headFos != null) {
try {
headFos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// 网络图片转成bigmap对象
public static Bitmap getBitMBitmap(String urlpath) {
Bitmap map = null;
try {
URL url = new URL(urlpath);
URLConnection conn = url.openConnection();
conn.connect();
InputStream in;
in = conn.getInputStream();
map = BitmapFactory.decodeStream(in);
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
// 调用系统分享
public void share(String imgUrl) {
String imgPath = "自已定义路径";
String imgName = "share.jpg";
saveBitmap(getBitMBitmap(imgUrl), imgPath, imgName);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(imgPath + "/" + imgPath ));
startActivity(Intent.createChooser(intent, "图片描述,随便写"));
}
但是这时候我们去分享是不行的,我开始这样去分享只有QQ好友成功了,其他的都没成功,因为你只是把图片存到本地了,而你调系统的分享,系统不知道你给它保存了这个图片,所以它去分享的时候它会说我不知道有这张图片,可不就是资源未找到,所以我们要告诉系统 我给你保存了一张图片:
/**
* 这个参数是你保存到本地图片的绝对路径(包括文件名.jpg的)
*/
public static String insertImageToSystem(Context context, String imagePath) {
String url = "";
try {
url = MediaStore.Images.Media.insertImage(context.getContentResolver(), imagePath, imgName , "分享");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return url;
}
最终调用系统分享:
// 调用系统分享
public void share(String imgUrl) {
String imgPath = "自已定义路径";
String imgName = "share.jpg";
saveBitmap(getBitMBitmap(imgUrl), imgPath, imgName);
insertImageToSystem(context, imgAbsPath);// imgAbsPath:图片绝对路径
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(imgPath + "/" + imgPath ));
startActivity(Intent.createChooser(intent, "图片描述,随便写"));
}