我正在从我的服务器下载请求的图像,下载后该图像已成功显示,但是当我尝试将相同的图像存储在我的 SD 卡上时,它返回 null。这是我下载图像并保存它的代码。我在调用 bitmap.compress() 时得到空值
void saveImage() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "Image.png";
File file = new File (myDir, fname);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
message_bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
//write the bytes in file
FileOutputStream fo;
try {
fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
message_bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}*/
}
static public Bitmap downloadBitmap(String url) {
final DefaultHttpClient client = new DefaultHttpClient();
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
final Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// Could provide a more explicit error message for IOException or IllegalStateException
getRequest.abort();
Log.w("ImageDownloader", "Error while retrieving bitmap from " + url + e.toString());
} finally {
if (client != null) {
}
}
return null;
}