public void downloadImage(String url) {
//创建Retrofit对象
Retrofit retrofit =new Retrofit.Builder()
.baseUrl(url)
.build();
///构建网络请求接口实例
getImage_Interface getImage_interface = retrofit.create(getImage_Interface.class);
//构建请求体
Call call = getImage_interface.getImage();
//异步请求
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
//请求成功后拿到图片 解析成bitmap
ResponseBody responseBody = response.body();
bitmap = BitmapFactory.decodeStream(responseBody.byteStream());
image.setImageBitmap(bitmap);
}
@Override
public void onFailure(Call call, Throwable t) {
///请求失败显示错误信息
Toast.makeText(MainActivity.this, "请求失败" t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
Retrofit网络请求接口
public interface getImage_Interface {
@GET("22.jpg")
Call getImage();
}
将下载的图片保存到本地
public static void saveBitmap(Context context, Bitmap bmp, String picName) {
String fileName =null;
//系统相册目录
String galleryPath = Environment.getExternalStorageDirectory()
File.separator Environment.DIRECTORY_DCIM
File.separator "Camera" File.separator;
// 声明文件对象
File file =null;
// 声明输出流
FileOutputStream outStream =null;
try {
// 如果有目标文件,直接获取文件对象,否则创建新文件
file =new File(galleryPath, picName ".jpg");
// file = new File(galleryPath, photoName);
// 获取文件的相对路径
fileName = file.toString();
// 如果文件中有内容,则获得输出流
outStream =new FileOutputStream(fileName);
if (null != outStream) {
//压缩图片
bmp.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
}
}catch (Exception e) {
e.getStackTrace();
}finally {
try {
if (outStream !=null) {
outStream.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}
try {
///将图片保存到本地
MediaStore.Images.Media.insertImage(context.getContentResolver(), bmp, fileName, null);
///发广播让相册刷新
Intent intent =new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(file);
intent.setData(uri);
context.sendBroadcast(intent);
Toast.makeText(context, "图片保存成功", Toast.LENGTH_SHORT).show();
}catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "图片保存失败", Toast.LENGTH_SHORT).show();
}
}
点击调用方法
@OnClick({R.id.submit, R.id.save})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.submit:
downloadImage("http://dmimg.5054399.com/allimg/pkm/pk/");
break;
case R.id.save:
saveBitmap(this, bitmap, "pikaqiu");
break;
}
}