android网络下载图片并缓存

功能:

实现网络下载图片,并缓存。缓存之后,即使断网,也能从缓存中读取已有的数据。(当缓存中有数据时,则不会启动异步任务)

--------------------------------------------MainActivity.java------------------------------------------------------------------------------

package com.example.downloadpicturetest;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;

public class MainActivity extends Activity {


private ImageView imageView;
private String url = "http://img0.bdstatic.com/img/image/shouye/mxym-9447375568.jpg";
private String imagesDocument = null; 
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找到存储图片文件的文件夹路径
imagesDocument = getApplication().getCacheDir().getAbsolutePath()+File.separator+"images";

imageView = (ImageView) findViewById(R.id.imageViewId);
//创建图片文件路径所指向文件的文件对象
File imageFile = new File(imagesDocument,ImageCacheUtils.getFileName(url));
if(imageFile.exists()){//如果图片文件存在
//从缓存中取出图片文件
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
//在imageView上显示图片
imageView.setImageBitmap(bitmap);

}else{//如果文件不存在
//创建异步任务对象,并启动异步任务(下载并缓存图片)
MyTask myTask = new MyTask();
myTask.execute(url);
}

}
/**
* 异步任务   下载图片
*/
class MyTask extends AsyncTask<String,Void, Bitmap>{

//创建一个虚拟的路径 指向 缓存目录下的 images文件夹
String imagesDocument = getApplication().getCacheDir().getAbsolutePath()+File.separator+"images"; 

@Override
protected Bitmap doInBackground(String... params) {
try{
HttpClient client=new DefaultHttpClient();
HttpGet get=new HttpGet(params[0]);
HttpResponse response=client.execute(get);
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
//将请求响应的数据转成字节数组
byte[] bytes=EntityUtils.toByteArray(response.getEntity()); //开始从网络下载数据
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}


}catch(Exception e){
e.printStackTrace();
}


return null;
}




@Override
protected void onPostExecute(Bitmap result) {
if(result!=null){
File fileDir = new File(imagesDocument);//创建路径为imagesDir的文件夹对象
if(!fileDir.exists()){//如果文件夹对象不存在
fileDir.mkdir();//创建该文件夹
}
File imageFile = new File(fileDir,ImageCacheUtils.getFileName(url));//创建路径为fileDir+File.separator+getFileName()的文件对象
if(!imageFile.exists()){//如果文件不存在
try {
//将图片保存在该路径下(此处的result表示已经下载好的图片数据  bitmap )
result.compress(CompressFormat.JPEG, 100, new FileOutputStream(imageFile));

} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
imageView.setImageBitmap(result);
}
}

}
}

----------------------------------------------imageCacheUtils.java(工具类)-----------------------------------------------------------------------

package com.example.downloadpicturetest;


import java.io.File;


public class ImageCacheUtils {

/**
* 从Url中截取图片的名称
* 例如:
* url:"http://img0.bdstatic.com/img/image/shouye/mxym-9447375568.jpg"
* 截取出来的结果:mxym-9447375568.jpg
*/
public static String getFileName(String url){
return url.substring(url.lastIndexOf("/")+1);
}
}

-----------------------------------------------------------------------------------------------------------------------------------------------------

总结:

核心代码

1、//将图片写入缓存
      result.compress(CompressFormat.JPEG, 100, new FileOutputStream(imageFile));

2、//从缓存中取出图片文件
      Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
































  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android中,可以通过使用Retrofit等网络请求库来实现头像的上传和下载,并将头像缓存到本地。以下是一个简单的示例: 1. 添加Retrofit和OkHttp依赖: ```gradle implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' implementation 'com.squareup.okhttp3:okhttp:4.9.0' ``` 2. 定义上传和下载接口: ```java public interface ApiService { @Multipart @POST("upload_avatar") Call<ResponseBody> uploadAvatar(@Part MultipartBody.Part file); @GET("download_avatar") Call<ResponseBody> downloadAvatar(); } ``` 在上述代码中,使用@Multipart注解标记上传的请求,@Part注解标记上传的文件。下载接口使用@GET注解标记,并返回一个ResponseBody对象。 3. 实现上传头像的逻辑: ```java // 选择图片并上传头像 Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); startActivityForResult(intent, 1); @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1 && resultCode == RESULT_OK && data != null) { Uri uri = data.getData(); File file = new File(getRealPathFromUri(this, uri)); RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file); MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), requestBody); ApiService apiService = createApiService(); Call<ResponseBody> call = apiService.uploadAvatar(filePart); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Toast.makeText(MainActivity.this, "上传失败", Toast.LENGTH_SHORT).show(); } }); } } // 获取URI对应的真实路径 public String getRealPathFromUri(Context context, Uri uri) { String[] projection = {MediaStore.Images.Media.DATA}; Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null); if (cursor != null && cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); String filePath = cursor.getString(columnIndex); cursor.close(); return filePath; } return ""; } ``` 在上述代码中,使用Intent.ACTION_GET_CONTENT打开文件选择器,选择图片后将图片文件构造成RequestBody和MultipartBody.Part对象,然后使用Retrofit上传头像。 4. 实现下载头像并缓存到本地的逻辑: ```java // 下载头像并缓存到本地 ApiService apiService = createApiService(); Call<ResponseBody> call = apiService.downloadAvatar(); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if (response.isSuccessful()) { try (InputStream inputStream = response.body().byteStream()) { Bitmap bitmap = BitmapFactory.decodeStream(inputStream); imageView.setImageBitmap(bitmap); // 将头像保存到本地文件 File file = new File(getCacheDir(), "avatar.png"); try (FileOutputStream fos = new FileOutputStream(file)) { bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); } catch (IOException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Toast.makeText(MainActivity.this, "下载失败", Toast.LENGTH_SHORT).show(); } }); ``` 在上述代码中,使用Retrofit下载头像,如果下载成功,将头像设置到ImageView中,并将头像保存到本地文件中。需要注意的是,下载头像时需要在异步线程中执行,否则会抛出NetworkOnMainThreadException异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值