如何将下载的图像存储到android中的sdcard

时间:2012-05-08 00:18:16

标签: android image

我有以下代码可以正常下载图像表单网址。 我想在按钮点击时将图像视图中加载的图像保存到SD卡。 任何人都可以帮助我如何将下载的图像保存到SD卡。

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 个答案:

答案 0 :(得分:1)

final Bitmap downloadBitma = downloadBitmap(...);

你的位图名称在末尾缺少'p',所以这不起作用......

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

哦,不要给变量和方法同名 - 我甚至不知道这在Java中是否合法。