我必须从httpResponse
下载图像并将其保存在Android设备上的内部存储中。我有这段代码试图这样做:
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
Bitmap logo = BitmapFactory.decodeStream(inputStream);
FileOutputStream fos = null;
try {
fos = getApplicationContext().openFileOutput("logo.png",Context.MODE_PRIVATE);
logo.compress(Bitmap.CompressFormat.PNG, 90, fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
fos.close();
}
但我没有得到我需要的结果。保存的图像无法与图像查看器一起打开,而且其尺寸也略大。要下载的图像是1.71 KB,结果是2.01 KB。任何想法?
答案 0 :(得分:0)
我不知道您的代码中存在什么问题,但如果您愿意,可以尝试使用此代码,此代码对我来说没有任何问题
保存到内部存储器......
File fileWithinMyDir = getApplicationContext().getFilesDir();
try
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL("http://t2.gstatic.com /images?q=tbn:ANd9GcQjZgUffqqe2mKKb5VOrDNd-ZxD7sJOU7WAHlFAy6PLbtXpyQZYdw");
File file = new File( fileWithinMyDir.getAbsolutePath() + "/" +"sun.jpg");
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
}
catch (IOException e)
{
Log.e("download", e.getMessage());
}
从内存中加载图像..
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
Bitmap bitmap = BitmapFactory.decodeFile(fileWithinMyDir.getAbsolutePath() + "/" +"sunn"+".file extension");
mImgView1.setImageBitmap(bitmap);