我需要从服务器下载图像并将其保存到文件夹,所以我使用的是Retrofit 2.
问题是当我在文件夹中查找时保存的图像为空,我试图调试并看到Bitmap为空。
我不明白为什么,这是我的代码:
@GET("images/{userId}/{imageName}")
@Streaming
Call<ResponseBody> downloadImage(@Path("userId") String userId, @Path("imageName") String imageName);
下载图片代码:
private void downloadImage(final int position) {
String url = "htttp://myserver.com/";
retrofitImage = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
imageApi = retrofitImage.create(BlastApiService.class);
String userId = feedList.get(position).getUserId();
String fileName = feedList.get(position).getFile();
Call<ResponseBody> imageCall = imageApi.downloadImage(userId, fileName );
imageCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.isSuccess()){
String fileName = feedList.get(position).getFile();
InputStream is = response.body().byteStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
saveImage1(bitmap, fileName);
} else{
try {
Log.d("TAG", "response error: "+response.errorBody().string().toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("TAG", "Image download error: " + t.getLocalizedMessage());
}
});
}
以下是保存图片的方法。
private void saveImage1(Bitmap imageToSave, String fileName) {
// get the path to sdcard
File sdcard = Environment.getExternalStorageDirectory();
// to this path add a new directory path
File dir = new File(sdcard.getAbsolutePath() + "/FOLDER_NAME/");
// create this directory if not already created
dir.mkdir();
// create the file in which we will write the contents
File file = new File(dir, fileName);
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
counter++;
// if (counter < feedList.size()) {
//downloadImage(counter);
//} else {
setImage();
//}
} catch (Exception e) {
e.printStackTrace();
}
}
答案 0 :(得分:2)
这对我有用:
public static boolean writeResponseBody(ResponseBody body, String path) {
try {
File file = new File(path);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
//long fileSize = body.contentLength();
//long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(file);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
//fileSizeDownloaded += read;
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
调用此方法后,您可以从路径获取图像:
boolean result = writeResponseBody(body, path);
if(result) {
Bitmap bitmap = BitmapFactory.decodeFile(path)
}
答案 1 :(得分:0)
private boolean writeResponseBodyToDisk(ResponseBody body, String name) {
try {
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/MyApp";
File dir = new File(path);
if (!dir.exists())
dir.mkdirs();
File futureStudioIconFile = new File(path, name + ".pdf");//am saving pdf file
if (futureStudioIconFile.exists())
futureStudioIconFile.delete();
futureStudioIconFile.createNewFile();
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
}
outputStream.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}