0

我必须从中下载图像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。有任何想法吗?

4

1 回答 1

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);
于 2013-08-13T06:37:53.610 回答