最近項(xiàng)目上有這樣一個(gè)需求,需要分享網(wǎng)絡(luò)圖片到微信,在網(wǎng)上查閱了相關(guān)資料,然后結(jié)合自己的思路,總結(jié)了一下實(shí)現(xiàn)的具體流程:
1、將網(wǎng)絡(luò)圖片下載下來(lái),轉(zhuǎn)換成Bitmap:
/**
* @param path 網(wǎng)絡(luò)圖片地址
*/
public Bitmap getBitmap(String path) {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
InputStream inputStream = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
2、將Bitmap格式的文件保存在本地:
/**
* 保存文件
*/
public void saveFile(Bitmap bm) throws IOException {
File sd = Environment.getExternalStorageDirectory();
File dirFile = new File(sd.getPath() + "/Download/imgurl.jpg");
FileOutputStream fos;
fos = new FileOutputStream(dirFile);
if (fos!=null ) {
bm.compress(Bitmap.CompressFormat.JPEG, 50, fos);
fos.flush();
fos.close();
}
}
3、調(diào)用系統(tǒng)分享:
private Uri U;
private void shareCode() {
File sd = Environment.getExternalStorageDirectory();
String path = sd.getPath() + "/Download/imgurl.jpg";
File file = new File(path);
if (Build.VERSION.SDK_INT < 24) {
U = Uri.fromFile(file);
} else {
//android 7.0及以上權(quán)限適配
U= FileProvider.getUriForFile(this,
"cn.izis.whteachtest.provider",
file);
}
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
intent.putExtra(Intent.EXTRA_STREAM, U);
startActivity(Intent.createChooser(intent, getTitle()));
}