2012-05-08 58 views
-1

我有以下代碼,它可以正常工作以下載圖像表單url。 我想按下按鈕,將加載到圖像視圖中的圖像保存到SD卡上。 任何人都可以請幫助我如何將下載的圖像保存到SD卡。如何將下載的圖像存儲到android中的sdcard

public class DownloadimageActivity extends Activity { 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    } 
    public void downloadPicture(View view) { 
    final ProgressDialog dialog = ProgressDialog.show(this, "Snapshot", 
      "retriving image.."); 
    dialog.show(); 
    new Thread(new Runnable() { 
     @Override 
     public void run() { 
      try { 
       final Bitmap downloadBitma = downloadBitmap("http://42.60.144.184:8081/snapshot.cgi?&user=admin&pwd=admin&resolution=8"); 
       final ImageView imageView = (ImageView) findViewById(R.id.imageView1); 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         imageView.setImageBitmap(downloadBitma); 

        } 
       }); 

      } catch (IOException e) { 
       e.printStackTrace(); 
      } finally { 
       dialog.dismiss(); 
      } 
     } 
    }).start(); 

} 

private Bitmap downloadBitmap(String url) throws IOException { 
    HttpUriRequest request = new HttpGet(url.toString()); 
    HttpClient httpClient = new DefaultHttpClient(); 
    HttpResponse response = httpClient.execute(request); 

    StatusLine statusLine = response.getStatusLine(); 
    int statusCode = statusLine.getStatusCode(); 
    if (statusCode == 200) { 
     HttpEntity entity = response.getEntity(); 
     byte[] bytes = EntityUtils.toByteArray(entity); 

     Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, 
       bytes.length); 

     return bitmap; 
    } else { 
     throw new IOException("Retrive failed, HTTP response code " 
       + statusCode + " - " + statusLine.getReasonPhrase()); 
    } 

} 
} 

我試着用下面的代碼,但它不工作。

 ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
    downloadBitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes); 
    //you can create a new file name "test.jpg" in sdcard folder. 
    File f = new File(Environment.getExternalStorageDirectory() 
          + File.separator + "test.jpg"); 
    f.createNewFile(); 
    //write the bytes in file 
    FileOutputStream fo = new FileOutputStream(f); 
    fo.write(bytes.toByteArray()); 
+1

你是什麼意思「它不工作」?什麼失敗?它是否會拋出異常?另外,您是否請求了寫入外部存儲的權限? – kabuko

+0

在eclipse中它要求創建一個新變量downloadBitmap – radish

+0

Eclipse是否要求你的代碼在上面的某一行? –

回答

1
final Bitmap downloadBitma = downloadBitmap(...); 

位圖名缺少的「P」末所以這是不行的......

downloadBitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes); 

哦,不給一個變量相同的名稱作爲一種方法 - 我甚至不知道這在Java中是否合法。

+0

起初我想過,但他後來在代碼中使用了'downloadBitma'。 –

+0

downloadBitma是一個變量,並且代碼工作正常,它可以下載並在imageview中顯示圖像。現在我想保存在圖像視圖中顯示的圖像 – radish

+0

然後將您要壓縮的行更改爲'downloadBitma.compress(...)' - 這正是我試圖在答案中展示給您的。 – Squonk

相關問題